Fix the broken marketing attribution report that stopped working after GA4 migration
harbor run -t snowflake-labs/dbt-fix-marketing-attributionharbor download snowflake-labs/dbt-fix-marketing-attributionThe marketing attribution report (marts/marketing/rpt_attribution_BROKEN.sql) has been broken since the GA4 migration on 2024-03-01. The model produces incorrect attribution metrics due to faulty UTM parsing logic and incorrect field references.
The broken model has several issues:
SPLIT_PART logic that doesn't work with GA4 data formatevent_date which doesn't existconversion_flag instead of is_convertedThis task supports both DuckDB and Snowflake. Run echo $DB_TYPE in a shell BEFORE you write any code or spawn any subagents — the live env determines which backend the verifier runs against. Do NOT assume a default from this prose. Both /app/dbt_models_duckdb/ and /app/dbt_models_snowflake/ exist on disk; the verifier only checks the project matching the live $DB_TYPE.
DB_TYPE=duckdb$DUCKDB_PATH (default: /app/database/retail.duckdb)/app/dbt_models_duckdbDB_TYPE=snowflakeSNOWFLAKE_ACCOUNTSNOWFLAKE_USERSNOWFLAKE_PASSWORDSNOWFLAKE_DATABASE - The clone database to useSNOWFLAKE_SCHEMASNOWFLAKE_WAREHOUSESNOWFLAKE_ROLE (optional)/app/dbt_models_snowflakeNote: For Snowflake, the entrypoint automatically creates a clone database and sets SNOWFLAKE_DATABASE. The clone is destroyed when the task completes.
int_sessions_events_joined - Joins sessions and events (has fanout: one session -> many events)
t2_ (e.g., t2_event_name, t2_event_value, t2_event_timestamp)session_id, t2_event_name, t2_event_value, t2_event_timestampstg_ga__sessions - Sessions table with UTM parameters (utm_source, utm_medium, utm_campaign) and conversion flag (is_converted)
session_id, session_start, utm_source, utm_medium, utm_campaign, is_convertedstg_ga__events - Events table with event-level data and timestampsImportant (read carefully -- this task is intentionally tricky):
CAST(x AS DATE) for date extraction. DATE(x) may not be available in all backends.main (e.g., main.stg_ga__sessions). Your solution must be robust to this.is_converted may behave as a boolean or a numeric value depending on the backend. Use explicit casting when comparing.int_sessions_events_joined may omit some event fields (and may omit t2_event_value entirely). If that happens, you must source revenue from stg_ga__events.event_value instead.dbt ls and direct SQL to verify what columns exist in this environment before finalizing your logic.retail_dw_masterprofiles.yml in the dbt project directoryDBT_PROFILES_DIR environment variable to the directory containing profiles.ymlConfigure with type: duckdb and the database path from $DUCKDB_PATH.
Configure with type: snowflake using password authentication:
/app/dbt_projectanalyticsmain (the default schema of the clone database)Configuration Note: Set the schema in profiles.yml. Do not add +schema in dbt_project.yml.
Snowflake schema routing: On Snowflake, models must land in the main schema (not analytics). To achieve this, override the generate_schema_name macro so that dbt places all models in the target schema defined in profiles.yml (i.e., main), ignoring any custom schema config. Create macros/generate_schema_name.sql with a macro that returns the default schema unconditionally.
Examine marts/marketing/rpt_attribution_BROKEN.sql in the reference dbt project to understand:
int_sessions_events_joinedCreate a new model marts/marketing/rpt_attribution_fixed.sql that:
Correctly extracts UTM parameters:
channel: Extract from utm_source in stg_ga__sessions (GA4 stores this directly, no parsing needed)medium: Extract from utm_medium in stg_ga__sessions (GA4 stores this directly)campaign: Extract from utm_campaign in stg_ga__sessions (GA4 stores this directly)Uses correct date field:
session_start from sessions table (cast to date) for attribution dateCorrectly calculates metrics:
sessions: Count distinct session_id (handle fanout from join if using int_sessions_events_joined)conversions: Count sessions where is_converted is truthyattributed_revenue:
t2_event_value from int_sessions_events_joined if it exists in your environmentevent_value from stg_ga__eventsevent_name = 'purchase' / t2_event_name = 'purchase')conversion_rate: conversions / sessions (handle division by zero, round to 4 decimals)Handles data quality:
The model must produce the following columns:
attribution_date (DATE) - Date of the sessionchannel (VARCHAR) - Marketing channel (from utm_source)medium (VARCHAR) - Marketing medium (from utm_medium)campaign (VARCHAR) - Campaign name (from utm_campaign)sessions (INTEGER) - Count of distinct sessionsconversions (INTEGER) - Count of converted sessionsattributed_revenue (DECIMAL) - Total revenue attributed to these sessionsconversion_rate (DECIMAL) - Conversion rate (conversions / sessions, rounded to 4 decimals)UTM Parameter Extraction:
utm_source is NULL, set channel to 'direct'utm_medium is NULL, set medium to 'none'utm_campaign is NULL, set campaign to 'none'Session Counting:
session_id to avoid double-counting from join fanoutsession_start is not NULLConversion Logic:
is_converted = 1 in the sessions table (stg_ga__sessions)t2_event_name = 'purchase' in int_sessions_events_joined represent conversion eventst2_event_value from int_sessions_events_joined for revenue (this is the event value column from the joined events table)t2_event_value is NULL, treat as 0Date Handling:
CAST(session_start AS DATE) for attribution_dateCAST(session_start AS DATE) >= (SELECT MAX(CAST(session_start AS DATE)) FROM <sessions_source>) - interval '90 days'The rpt_attribution_fixed model must:
dbt runconversions <= sessions for every rowconversion_rate must equal conversions/sessions rounded to 4 decimalsSchema References:
main in this environment (e.g., main.stg_ga__sessions).analytics schema.main schema. Use a generate_schema_name macro override to ensure dbt routes the model to main instead of appending a custom schema suffix.Column Naming in int_sessions_events_joined:
int_sessions_events_joined model prefixes columns from the events table with t2_t2_event_name for event names (e.g., 'purchase' for conversion events)t2_event_value for event values (revenue) if present in your environmentt2_event_timestamp for event timestampsModel Setup:
cd /app/dbt_models_duckdb && dbt deps && dbt run --select stg_ga__sessions stg_ga__events int_sessions_events_joinedcd /app/dbt_models_snowflake && dbt deps && dbt run --select stg_ga__sessions stg_ga__events int_sessions_events_joinedThe int_sessions_events_joined model has a LEFT JOIN that creates fanout (one session -> many events)
You must use COUNT(DISTINCT session_id) to avoid double-counting sessions
UTM parameters are already clean in GA4 - no parsing needed
The SQL syntax should work on both DuckDB and Snowflake (ANSI SQL compatible)
Ensure idempotent execution (multiple runs produce same results)
You can explore the data using:
dbt ls - List available modelsdbt run --select int_sessions_events_joined - Run the source modeldbt show --select int_sessions_events_joined --limit 10 - Preview dataCAST(... AS DATE) instead of DATE(...) functionDATEDIFF for date differencesCOALESCE for NULL handlingNULLIF to protect against division by zero