:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(marketing-analytics): share live attribution session resolution (#108008)
Javier Bahamondes9cc3dbb5f791
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.mdindex 566024e4b8c9..b2efc950cd92 100644--- a/docs/internal/marketing-attribution-session-precompute.md+++ b/docs/internal/marketing-attribution-session-precompute.md@@ -49,3 +49,27 @@ Attribution filters compare the event timestamp directly with the date bounds, uThis avoids copying timestamp casts into session filters and preserves the shared raw-session timestamp definition.If either date boundary falls within a repeated local hour at a daylight saving transition, the reader uses live attribution because conversion filters parse dates without a UTC offset.Ranges that cross a transition can still use cached dimensions when both boundaries are unambiguous.++## Live session resolution++The independent `marketing-analytics-live-session-resolution` flag opts attribution tables and paths into shared live session resolution.+It takes precedence over the sessions-precomputation flag for eligible queries and does not require precomputed jobs.+The default remains off.+Attribution result cache keys distinguish the flag state, so enabling or disabling it cannot reuse results computed with the opposite setting.++This route materializes pageview session IDs and current person IDs once, then resolves current dimensions from the matching raw sessions.+Reach and credit share those rows and the conversion aggregation.+Late-arriving events and session updates therefore do not depend on a cached dimension snapshot or its recorded ingestion time.+A missing cache window at a calendar boundary does not switch this route back to the legacy live query.+The report's date range and timezone remain unchanged.++The initial rollout keeps the cached reader's eligibility restrictions, including date-boundary, access-control, test-account, range, and session-modifier checks.+Conversion goals that depend on session fields or deferred action expressions also use legacy live attribution, preserving its wider session-ID lookup window.+Ineligible queries continue to use legacy live attribution.+Raw session lookups retain that path's session-ID timestamp bounds, including its three-day buffer.+This does not extend coverage for older session IDs or guarantee that independently replicated events and sessions arrive together.++Validate result parity and query cost before enabling this flag: current dimensions require more source reads than a warm dimension cache.+The query telemetry property `live_session_resolution_used` identifies this route; `sessions_precompute_used` remains false for it.+Disabling the new flag restores the existing selection between cached and legacy live attribution.+The writer, schedule, existing jobs, TTLs, and job hashes are unchanged.diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambrindex 7bfbaa12d22c..0abad9a9913e 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambr@@ -353,3 +353,210 @@SETTINGS load_balancing='in_order''''# ---+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_6_shared_campaign+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_12)s)), `$start_timestamp`, %(hogql_val_13)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_14)s)), %(hogql_val_15)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_16)s)), %(hogql_val_17)s, %(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s) AS dimensions, now64(6, %(hogql_val_21)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_10)s), %(hogql_val_11)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_22)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_23)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_24)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_25)s), ''), 'null'), '^"|"$', ''), %(hogql_val_26)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_27)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_28)s))) AS last_conversion+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_29)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_30)s, %(hogql_val_31)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_32)s, 6, %(hogql_val_33)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_34)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_35)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (+ SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (+ SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key+ FROM per_conversion_path+ WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)+ GROUP BY per_conversion_path.path), paths_footer AS (+ SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion_path)+ SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key+ FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)+ ORDER BY conversions DESC, path ASC+ LIMIT 51+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_7_shared_source+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_10)s)), `$start_timestamp`, %(hogql_val_11)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_12)s)), %(hogql_val_13)s, %(hogql_val_14)s, %(hogql_val_15)s, %(hogql_val_16)s, %(hogql_val_17)s, %(hogql_val_18)s) AS dimensions, now64(6, %(hogql_val_19)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_20)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_21)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_22)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_23)s), ''), 'null'), '^"|"$', ''), %(hogql_val_24)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_25)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_26)s))) AS last_conversion+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_27)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_28)s, %(hogql_val_29)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_30)s, 6, %(hogql_val_31)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_32)s)), cached_sessions.utm_source, %(hogql_val_33)s)), [%(hogql_val_34)s, %(hogql_val_35)s, %(hogql_val_36)s]), %(hogql_val_37)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_38)s)), cached_sessions.utm_source, %(hogql_val_39)s)), [%(hogql_val_40)s, %(hogql_val_41)s, %(hogql_val_42)s, %(hogql_val_43)s, %(hogql_val_44)s, %(hogql_val_45)s, %(hogql_val_46)s, %(hogql_val_47)s]), %(hogql_val_48)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_49)s)), cached_sessions.utm_source, %(hogql_val_50)s)), [%(hogql_val_51)s]), %(hogql_val_52)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_53)s)), cached_sessions.utm_source, %(hogql_val_54)s)), [%(hogql_val_55)s, %(hogql_val_56)s, %(hogql_val_57)s, %(hogql_val_58)s, %(hogql_val_59)s, %(hogql_val_60)s, %(hogql_val_61)s, %(hogql_val_62)s, %(hogql_val_63)s]), %(hogql_val_64)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_65)s)), cached_sessions.utm_source, %(hogql_val_66)s)), [%(hogql_val_67)s]), %(hogql_val_68)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_69)s)), cached_sessions.utm_source, %(hogql_val_70)s)), [%(hogql_val_71)s, %(hogql_val_72)s]), %(hogql_val_73)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_74)s)), cached_sessions.utm_source, %(hogql_val_75)s)), [%(hogql_val_76)s, %(hogql_val_77)s, %(hogql_val_78)s]), %(hogql_val_79)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_80)s)), cached_sessions.utm_source, %(hogql_val_81)s)), [%(hogql_val_82)s]), %(hogql_val_83)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_84)s)), cached_sessions.utm_source, %(hogql_val_85)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_86)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (+ SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (+ SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key+ FROM per_conversion_path+ WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)+ GROUP BY per_conversion_path.path), paths_footer AS (+ SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion_path)+ SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key+ FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)+ ORDER BY conversions DESC, path ASC+ LIMIT 51+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_8_shared_channel+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_127)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_128)s)), `$channel_type`, %(hogql_val_129)s), %(hogql_val_130)s, %(hogql_val_131)s, %(hogql_val_132)s, %(hogql_val_133)s, %(hogql_val_134)s, %(hogql_val_135)s, %(hogql_val_136)s) AS dimensions, now64(6, %(hogql_val_137)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_8)s), %(hogql_val_9)s), %(hogql_val_10)s), %(hogql_val_11)s)), %(hogql_val_12)s), %(hogql_val_13)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_14)s), %(hogql_val_15)s), %(hogql_val_16)s), %(hogql_val_17)s)), tuple(%(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s, %(hogql_val_21)s, %(hogql_val_22)s, %(hogql_val_23)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_24)s), %(hogql_val_25)s), %(hogql_val_26)s), %(hogql_val_27)s)), %(hogql_val_28)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_29)s), %(hogql_val_30)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_31)s), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s)), %(hogql_val_43)s), %(hogql_val_44)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_45)s), %(hogql_val_46)s), %(hogql_val_47)s), %(hogql_val_48)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_51)s), %(hogql_val_52)s), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), 0), %(hogql_val_56)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_57)s), %(hogql_val_58)s), %(hogql_val_59)s), %(hogql_val_60)s)), %(hogql_val_61)s), %(hogql_val_62)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_63)s), %(hogql_val_64)s)), %(hogql_val_65)s, %(hogql_val_66)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_67)s), %(hogql_val_68)s), %(hogql_val_69)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_70)s), %(hogql_val_71)s), %(hogql_val_72)s), %(hogql_val_73)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_74)s), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s)), tuple(%(hogql_val_82)s, %(hogql_val_83)s, %(hogql_val_84)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_85)s), %(hogql_val_86)s)))), %(hogql_val_87)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_92)s), %(hogql_val_93)s), %(hogql_val_94)s), %(hogql_val_95)s)), %(hogql_val_96)s), %(hogql_val_97)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_98)s), %(hogql_val_99)s), %(hogql_val_100)s), %(hogql_val_101)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_104)s), %(hogql_val_105)s), %(hogql_val_106)s), %(hogql_val_107)s)), %(hogql_val_108)s), %(hogql_val_109)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_110)s), %(hogql_val_111)s), %(hogql_val_112)s), %(hogql_val_113)s)), %(hogql_val_114)s), %(hogql_val_115)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_116)s), %(hogql_val_117)s)), %(hogql_val_118)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s), 0), %(hogql_val_122)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_123)s), %(hogql_val_124)s)), %(hogql_val_125)s, %(hogql_val_126)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_138)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_139)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_140)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_141)s), ''), 'null'), '^"|"$', ''), %(hogql_val_142)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_143)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_144)s))) AS last_conversion+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_145)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_146)s, %(hogql_val_147)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_148)s, 6, %(hogql_val_149)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_150)s)), cached_sessions.channel_type, %(hogql_val_151)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_152)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (+ SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (+ SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key+ FROM per_conversion_path+ WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)+ GROUP BY per_conversion_path.path), paths_footer AS (+ SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion_path)+ SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key+ FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)+ ORDER BY conversions DESC, path ASC+ LIMIT 51+ OFFSET 0+ '''+# ---diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambrindex ea26289f39c0..50f061f38411 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambr@@ -353,3 +353,210 @@SETTINGS load_balancing='in_order''''# ---+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_6_shared_campaign[new_events_schema]+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_12)s)), `$start_timestamp`, %(hogql_val_13)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_14)s)), %(hogql_val_15)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_16)s)), %(hogql_val_17)s, %(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s) AS dimensions, now64(6, %(hogql_val_21)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_10)s), %(hogql_val_11)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_22)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_23)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_24)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_25)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_26)s))) AS last_conversion+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_27)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_28)s, %(hogql_val_29)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_30)s, 6, %(hogql_val_31)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_32)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_33)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (+ SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (+ SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key+ FROM per_conversion_path+ WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)+ GROUP BY per_conversion_path.path), paths_footer AS (+ SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion_path)+ SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key+ FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)+ ORDER BY conversions DESC, path ASC+ LIMIT 51+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_7_shared_source[new_events_schema]+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_10)s)), `$start_timestamp`, %(hogql_val_11)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_12)s)), %(hogql_val_13)s, %(hogql_val_14)s, %(hogql_val_15)s, %(hogql_val_16)s, %(hogql_val_17)s, %(hogql_val_18)s) AS dimensions, now64(6, %(hogql_val_19)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_20)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_21)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_22)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_23)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_24)s))) AS last_conversion+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_25)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_26)s, %(hogql_val_27)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_28)s, 6, %(hogql_val_29)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_30)s)), cached_sessions.utm_source, %(hogql_val_31)s)), [%(hogql_val_32)s, %(hogql_val_33)s, %(hogql_val_34)s]), %(hogql_val_35)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_36)s)), cached_sessions.utm_source, %(hogql_val_37)s)), [%(hogql_val_38)s, %(hogql_val_39)s, %(hogql_val_40)s, %(hogql_val_41)s, %(hogql_val_42)s, %(hogql_val_43)s, %(hogql_val_44)s, %(hogql_val_45)s]), %(hogql_val_46)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_47)s)), cached_sessions.utm_source, %(hogql_val_48)s)), [%(hogql_val_49)s]), %(hogql_val_50)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_51)s)), cached_sessions.utm_source, %(hogql_val_52)s)), [%(hogql_val_53)s, %(hogql_val_54)s, %(hogql_val_55)s, %(hogql_val_56)s, %(hogql_val_57)s, %(hogql_val_58)s, %(hogql_val_59)s, %(hogql_val_60)s, %(hogql_val_61)s]), %(hogql_val_62)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_63)s)), cached_sessions.utm_source, %(hogql_val_64)s)), [%(hogql_val_65)s]), %(hogql_val_66)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_67)s)), cached_sessions.utm_source, %(hogql_val_68)s)), [%(hogql_val_69)s, %(hogql_val_70)s]), %(hogql_val_71)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_72)s)), cached_sessions.utm_source, %(hogql_val_73)s)), [%(hogql_val_74)s, %(hogql_val_75)s, %(hogql_val_76)s]), %(hogql_val_77)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_78)s)), cached_sessions.utm_source, %(hogql_val_79)s)), [%(hogql_val_80)s]), %(hogql_val_81)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_82)s)), cached_sessions.utm_source, %(hogql_val_83)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_84)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (+ SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (+ SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key+ FROM per_conversion_path+ WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)+ GROUP BY per_conversion_path.path), paths_footer AS (+ SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion_path)+ SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key+ FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)+ ORDER BY conversions DESC, path ASC+ LIMIT 51+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_8_shared_channel[new_events_schema]+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_127)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_128)s)), `$channel_type`, %(hogql_val_129)s), %(hogql_val_130)s, %(hogql_val_131)s, %(hogql_val_132)s, %(hogql_val_133)s, %(hogql_val_134)s, %(hogql_val_135)s, %(hogql_val_136)s) AS dimensions, now64(6, %(hogql_val_137)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_8)s), %(hogql_val_9)s), %(hogql_val_10)s), %(hogql_val_11)s)), %(hogql_val_12)s), %(hogql_val_13)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_14)s), %(hogql_val_15)s), %(hogql_val_16)s), %(hogql_val_17)s)), tuple(%(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s, %(hogql_val_21)s, %(hogql_val_22)s, %(hogql_val_23)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_24)s), %(hogql_val_25)s), %(hogql_val_26)s), %(hogql_val_27)s)), %(hogql_val_28)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_29)s), %(hogql_val_30)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_31)s), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s)), %(hogql_val_43)s), %(hogql_val_44)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_45)s), %(hogql_val_46)s), %(hogql_val_47)s), %(hogql_val_48)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_51)s), %(hogql_val_52)s), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), 0), %(hogql_val_56)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_57)s), %(hogql_val_58)s), %(hogql_val_59)s), %(hogql_val_60)s)), %(hogql_val_61)s), %(hogql_val_62)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_63)s), %(hogql_val_64)s)), %(hogql_val_65)s, %(hogql_val_66)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_67)s), %(hogql_val_68)s), %(hogql_val_69)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_70)s), %(hogql_val_71)s), %(hogql_val_72)s), %(hogql_val_73)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_74)s), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s)), tuple(%(hogql_val_82)s, %(hogql_val_83)s, %(hogql_val_84)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_85)s), %(hogql_val_86)s)))), %(hogql_val_87)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_92)s), %(hogql_val_93)s), %(hogql_val_94)s), %(hogql_val_95)s)), %(hogql_val_96)s), %(hogql_val_97)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_98)s), %(hogql_val_99)s), %(hogql_val_100)s), %(hogql_val_101)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_104)s), %(hogql_val_105)s), %(hogql_val_106)s), %(hogql_val_107)s)), %(hogql_val_108)s), %(hogql_val_109)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_110)s), %(hogql_val_111)s), %(hogql_val_112)s), %(hogql_val_113)s)), %(hogql_val_114)s), %(hogql_val_115)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_116)s), %(hogql_val_117)s)), %(hogql_val_118)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s), 0), %(hogql_val_122)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_123)s), %(hogql_val_124)s)), %(hogql_val_125)s, %(hogql_val_126)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_138)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_139)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_140)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_141)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_142)s))) AS last_conversion+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_143)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_144)s, %(hogql_val_145)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_146)s, 6, %(hogql_val_147)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_148)s)), cached_sessions.channel_type, %(hogql_val_149)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_150)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (+ SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (+ SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key+ FROM per_conversion_path+ WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)+ GROUP BY per_conversion_path.path), paths_footer AS (+ SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion_path)+ SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key+ FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)+ ORDER BY conversions DESC, path ASC+ LIMIT 51+ OFFSET 0+ '''+# ---diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.ambrindex e70f768f236c..76cd5a584a11 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.ambr@@ -449,3 +449,246 @@SETTINGS load_balancing='in_order''''# ---+# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_3_live_campaign+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_12)s)), `$start_timestamp`, %(hogql_val_13)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_14)s)), %(hogql_val_15)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_16)s)), %(hogql_val_17)s, %(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s) AS dimensions, now64(6, %(hogql_val_21)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_10)s), %(hogql_val_11)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_22)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_23)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_24)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_25)s), ''), 'null'), '^"|"$', ''), %(hogql_val_26)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_27)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_28)s))) AS last_conversion+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_29)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_30)s, %(hogql_val_31)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_32)s, 6, %(hogql_val_33)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors+ FROM (+ SELECT cached_sessions.person_id AS person_id, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_34)s)) AS breakdown_value+ FROM resolved_cached_sessions AS cached_sessions+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s+ GROUP BY s.breakdown_value), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_35)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_36)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_37)s), 1.0)), touch_ts) AS w_linear, arrayMap(w -> divide(w, greatest(arraySum(arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)), 1e-06)), arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)) AS w_decay, if(ifNull(equals(length(touch_ts), 0), 0), [], if(ifNull(equals(length(touch_ts), 1), 0), [1.0], if(ifNull(equals(length(touch_ts), 2), 0), [0.5, 0.5], arrayMap(w -> divide(w, greatest(arraySum(arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_38)s), 2.0), 1.0)))), touch_ts))), 1e-06)), arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_39)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position+ FROM per_touchpoint+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value+ FROM per_conversion_dim+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_40)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion)+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)+ ORDER BY influenced_conversions DESC, visitors DESC+ LIMIT 101+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_4_live_source+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_10)s)), `$start_timestamp`, %(hogql_val_11)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_12)s)), %(hogql_val_13)s, %(hogql_val_14)s, %(hogql_val_15)s, %(hogql_val_16)s, %(hogql_val_17)s, %(hogql_val_18)s) AS dimensions, now64(6, %(hogql_val_19)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_20)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_21)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_22)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_23)s), ''), 'null'), '^"|"$', ''), %(hogql_val_24)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_25)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_26)s))) AS last_conversion+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_27)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_28)s, %(hogql_val_29)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_30)s, 6, %(hogql_val_31)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors+ FROM (+ SELECT cached_sessions.person_id AS person_id, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_32)s)), cached_sessions.utm_source, %(hogql_val_33)s)), [%(hogql_val_34)s, %(hogql_val_35)s, %(hogql_val_36)s]), %(hogql_val_37)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_38)s)), cached_sessions.utm_source, %(hogql_val_39)s)), [%(hogql_val_40)s, %(hogql_val_41)s, %(hogql_val_42)s, %(hogql_val_43)s, %(hogql_val_44)s, %(hogql_val_45)s, %(hogql_val_46)s, %(hogql_val_47)s]), %(hogql_val_48)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_49)s)), cached_sessions.utm_source, %(hogql_val_50)s)), [%(hogql_val_51)s]), %(hogql_val_52)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_53)s)), cached_sessions.utm_source, %(hogql_val_54)s)), [%(hogql_val_55)s, %(hogql_val_56)s, %(hogql_val_57)s, %(hogql_val_58)s, %(hogql_val_59)s, %(hogql_val_60)s, %(hogql_val_61)s, %(hogql_val_62)s, %(hogql_val_63)s]), %(hogql_val_64)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_65)s)), cached_sessions.utm_source, %(hogql_val_66)s)), [%(hogql_val_67)s]), %(hogql_val_68)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_69)s)), cached_sessions.utm_source, %(hogql_val_70)s)), [%(hogql_val_71)s, %(hogql_val_72)s]), %(hogql_val_73)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_74)s)), cached_sessions.utm_source, %(hogql_val_75)s)), [%(hogql_val_76)s, %(hogql_val_77)s, %(hogql_val_78)s]), %(hogql_val_79)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_80)s)), cached_sessions.utm_source, %(hogql_val_81)s)), [%(hogql_val_82)s]), %(hogql_val_83)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_84)s)), cached_sessions.utm_source, %(hogql_val_85)s))))))))) AS breakdown_value+ FROM resolved_cached_sessions AS cached_sessions+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s+ GROUP BY s.breakdown_value), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_86)s)), cached_sessions.utm_source, %(hogql_val_87)s)), [%(hogql_val_88)s, %(hogql_val_89)s, %(hogql_val_90)s]), %(hogql_val_91)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_92)s)), cached_sessions.utm_source, %(hogql_val_93)s)), [%(hogql_val_94)s, %(hogql_val_95)s, %(hogql_val_96)s, %(hogql_val_97)s, %(hogql_val_98)s, %(hogql_val_99)s, %(hogql_val_100)s, %(hogql_val_101)s]), %(hogql_val_102)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_103)s)), cached_sessions.utm_source, %(hogql_val_104)s)), [%(hogql_val_105)s]), %(hogql_val_106)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_107)s)), cached_sessions.utm_source, %(hogql_val_108)s)), [%(hogql_val_109)s, %(hogql_val_110)s, %(hogql_val_111)s, %(hogql_val_112)s, %(hogql_val_113)s, %(hogql_val_114)s, %(hogql_val_115)s, %(hogql_val_116)s, %(hogql_val_117)s]), %(hogql_val_118)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_119)s)), cached_sessions.utm_source, %(hogql_val_120)s)), [%(hogql_val_121)s]), %(hogql_val_122)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_123)s)), cached_sessions.utm_source, %(hogql_val_124)s)), [%(hogql_val_125)s, %(hogql_val_126)s]), %(hogql_val_127)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_128)s)), cached_sessions.utm_source, %(hogql_val_129)s)), [%(hogql_val_130)s, %(hogql_val_131)s, %(hogql_val_132)s]), %(hogql_val_133)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_134)s)), cached_sessions.utm_source, %(hogql_val_135)s)), [%(hogql_val_136)s]), %(hogql_val_137)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_138)s)), cached_sessions.utm_source, %(hogql_val_139)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_140)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_141)s), 1.0)), touch_ts) AS w_linear, arrayMap(w -> divide(w, greatest(arraySum(arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)), 1e-06)), arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)) AS w_decay, if(ifNull(equals(length(touch_ts), 0), 0), [], if(ifNull(equals(length(touch_ts), 1), 0), [1.0], if(ifNull(equals(length(touch_ts), 2), 0), [0.5, 0.5], arrayMap(w -> divide(w, greatest(arraySum(arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_142)s), 2.0), 1.0)))), touch_ts))), 1e-06)), arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_143)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position+ FROM per_touchpoint+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value+ FROM per_conversion_dim+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_144)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion)+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)+ ORDER BY influenced_conversions DESC, visitors DESC+ LIMIT 101+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_5_live_channel+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_127)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_128)s)), `$channel_type`, %(hogql_val_129)s), %(hogql_val_130)s, %(hogql_val_131)s, %(hogql_val_132)s, %(hogql_val_133)s, %(hogql_val_134)s, %(hogql_val_135)s, %(hogql_val_136)s) AS dimensions, now64(6, %(hogql_val_137)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_8)s), %(hogql_val_9)s), %(hogql_val_10)s), %(hogql_val_11)s)), %(hogql_val_12)s), %(hogql_val_13)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_14)s), %(hogql_val_15)s), %(hogql_val_16)s), %(hogql_val_17)s)), tuple(%(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s, %(hogql_val_21)s, %(hogql_val_22)s, %(hogql_val_23)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_24)s), %(hogql_val_25)s), %(hogql_val_26)s), %(hogql_val_27)s)), %(hogql_val_28)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_29)s), %(hogql_val_30)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_31)s), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s)), %(hogql_val_43)s), %(hogql_val_44)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_45)s), %(hogql_val_46)s), %(hogql_val_47)s), %(hogql_val_48)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_51)s), %(hogql_val_52)s), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), 0), %(hogql_val_56)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_57)s), %(hogql_val_58)s), %(hogql_val_59)s), %(hogql_val_60)s)), %(hogql_val_61)s), %(hogql_val_62)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_63)s), %(hogql_val_64)s)), %(hogql_val_65)s, %(hogql_val_66)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_67)s), %(hogql_val_68)s), %(hogql_val_69)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_70)s), %(hogql_val_71)s), %(hogql_val_72)s), %(hogql_val_73)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_74)s), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s)), tuple(%(hogql_val_82)s, %(hogql_val_83)s, %(hogql_val_84)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_85)s), %(hogql_val_86)s)))), %(hogql_val_87)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_92)s), %(hogql_val_93)s), %(hogql_val_94)s), %(hogql_val_95)s)), %(hogql_val_96)s), %(hogql_val_97)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_98)s), %(hogql_val_99)s), %(hogql_val_100)s), %(hogql_val_101)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_104)s), %(hogql_val_105)s), %(hogql_val_106)s), %(hogql_val_107)s)), %(hogql_val_108)s), %(hogql_val_109)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_110)s), %(hogql_val_111)s), %(hogql_val_112)s), %(hogql_val_113)s)), %(hogql_val_114)s), %(hogql_val_115)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_116)s), %(hogql_val_117)s)), %(hogql_val_118)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s), 0), %(hogql_val_122)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_123)s), %(hogql_val_124)s)), %(hogql_val_125)s, %(hogql_val_126)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_138)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_139)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_140)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_141)s), ''), 'null'), '^"|"$', ''), %(hogql_val_142)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_143)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_144)s))) AS last_conversion+ FROM events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_145)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_146)s, %(hogql_val_147)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_148)s, 6, %(hogql_val_149)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors+ FROM (+ SELECT cached_sessions.person_id AS person_id, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_150)s)), cached_sessions.channel_type, %(hogql_val_151)s) AS breakdown_value+ FROM resolved_cached_sessions AS cached_sessions+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s+ GROUP BY s.breakdown_value), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_152)s)), cached_sessions.channel_type, %(hogql_val_153)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_154)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_155)s), 1.0)), touch_ts) AS w_linear, arrayMap(w -> divide(w, greatest(arraySum(arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)), 1e-06)), arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)) AS w_decay, if(ifNull(equals(length(touch_ts), 0), 0), [], if(ifNull(equals(length(touch_ts), 1), 0), [1.0], if(ifNull(equals(length(touch_ts), 2), 0), [0.5, 0.5], arrayMap(w -> divide(w, greatest(arraySum(arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_156)s), 2.0), 1.0)))), touch_ts))), 1e-06)), arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_157)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position+ FROM per_touchpoint+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value+ FROM per_conversion_dim+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_158)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion)+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)+ ORDER BY influenced_conversions DESC, visitors DESC+ LIMIT 101+ OFFSET 0+ '''+# ---diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambrindex fa521e4b028c..610a2df85408 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambr@@ -449,3 +449,246 @@SETTINGS load_balancing='in_order''''# ---+# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_3_live_campaign[new_events_schema]+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_12)s)), `$start_timestamp`, %(hogql_val_13)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_14)s)), %(hogql_val_15)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_16)s)), %(hogql_val_17)s, %(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s) AS dimensions, now64(6, %(hogql_val_21)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_10)s), %(hogql_val_11)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_22)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_23)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_24)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_25)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_26)s))) AS last_conversion+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_27)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_28)s, %(hogql_val_29)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_30)s, 6, %(hogql_val_31)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors+ FROM (+ SELECT cached_sessions.person_id AS person_id, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_32)s)) AS breakdown_value+ FROM resolved_cached_sessions AS cached_sessions+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s+ GROUP BY s.breakdown_value), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_33)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_34)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_35)s), 1.0)), touch_ts) AS w_linear, arrayMap(w -> divide(w, greatest(arraySum(arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)), 1e-06)), arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)) AS w_decay, if(ifNull(equals(length(touch_ts), 0), 0), [], if(ifNull(equals(length(touch_ts), 1), 0), [1.0], if(ifNull(equals(length(touch_ts), 2), 0), [0.5, 0.5], arrayMap(w -> divide(w, greatest(arraySum(arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_36)s), 2.0), 1.0)))), touch_ts))), 1e-06)), arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_37)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position+ FROM per_touchpoint+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value+ FROM per_conversion_dim+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_38)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion)+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)+ ORDER BY influenced_conversions DESC, visitors DESC+ LIMIT 101+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_4_live_source[new_events_schema]+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_10)s)), `$start_timestamp`, %(hogql_val_11)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_12)s)), %(hogql_val_13)s, %(hogql_val_14)s, %(hogql_val_15)s, %(hogql_val_16)s, %(hogql_val_17)s, %(hogql_val_18)s) AS dimensions, now64(6, %(hogql_val_19)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_8)s), %(hogql_val_9)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_20)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_21)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_22)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_23)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_24)s))) AS last_conversion+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_25)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_26)s, %(hogql_val_27)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_28)s, 6, %(hogql_val_29)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors+ FROM (+ SELECT cached_sessions.person_id AS person_id, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_30)s)), cached_sessions.utm_source, %(hogql_val_31)s)), [%(hogql_val_32)s, %(hogql_val_33)s, %(hogql_val_34)s]), %(hogql_val_35)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_36)s)), cached_sessions.utm_source, %(hogql_val_37)s)), [%(hogql_val_38)s, %(hogql_val_39)s, %(hogql_val_40)s, %(hogql_val_41)s, %(hogql_val_42)s, %(hogql_val_43)s, %(hogql_val_44)s, %(hogql_val_45)s]), %(hogql_val_46)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_47)s)), cached_sessions.utm_source, %(hogql_val_48)s)), [%(hogql_val_49)s]), %(hogql_val_50)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_51)s)), cached_sessions.utm_source, %(hogql_val_52)s)), [%(hogql_val_53)s, %(hogql_val_54)s, %(hogql_val_55)s, %(hogql_val_56)s, %(hogql_val_57)s, %(hogql_val_58)s, %(hogql_val_59)s, %(hogql_val_60)s, %(hogql_val_61)s]), %(hogql_val_62)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_63)s)), cached_sessions.utm_source, %(hogql_val_64)s)), [%(hogql_val_65)s]), %(hogql_val_66)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_67)s)), cached_sessions.utm_source, %(hogql_val_68)s)), [%(hogql_val_69)s, %(hogql_val_70)s]), %(hogql_val_71)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_72)s)), cached_sessions.utm_source, %(hogql_val_73)s)), [%(hogql_val_74)s, %(hogql_val_75)s, %(hogql_val_76)s]), %(hogql_val_77)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_78)s)), cached_sessions.utm_source, %(hogql_val_79)s)), [%(hogql_val_80)s]), %(hogql_val_81)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_82)s)), cached_sessions.utm_source, %(hogql_val_83)s))))))))) AS breakdown_value+ FROM resolved_cached_sessions AS cached_sessions+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s+ GROUP BY s.breakdown_value), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_84)s)), cached_sessions.utm_source, %(hogql_val_85)s)), [%(hogql_val_86)s, %(hogql_val_87)s, %(hogql_val_88)s]), %(hogql_val_89)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_90)s)), cached_sessions.utm_source, %(hogql_val_91)s)), [%(hogql_val_92)s, %(hogql_val_93)s, %(hogql_val_94)s, %(hogql_val_95)s, %(hogql_val_96)s, %(hogql_val_97)s, %(hogql_val_98)s, %(hogql_val_99)s]), %(hogql_val_100)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_101)s)), cached_sessions.utm_source, %(hogql_val_102)s)), [%(hogql_val_103)s]), %(hogql_val_104)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_105)s)), cached_sessions.utm_source, %(hogql_val_106)s)), [%(hogql_val_107)s, %(hogql_val_108)s, %(hogql_val_109)s, %(hogql_val_110)s, %(hogql_val_111)s, %(hogql_val_112)s, %(hogql_val_113)s, %(hogql_val_114)s, %(hogql_val_115)s]), %(hogql_val_116)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_117)s)), cached_sessions.utm_source, %(hogql_val_118)s)), [%(hogql_val_119)s]), %(hogql_val_120)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_121)s)), cached_sessions.utm_source, %(hogql_val_122)s)), [%(hogql_val_123)s, %(hogql_val_124)s]), %(hogql_val_125)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_126)s)), cached_sessions.utm_source, %(hogql_val_127)s)), [%(hogql_val_128)s, %(hogql_val_129)s, %(hogql_val_130)s]), %(hogql_val_131)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_132)s)), cached_sessions.utm_source, %(hogql_val_133)s)), [%(hogql_val_134)s]), %(hogql_val_135)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_136)s)), cached_sessions.utm_source, %(hogql_val_137)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_138)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_139)s), 1.0)), touch_ts) AS w_linear, arrayMap(w -> divide(w, greatest(arraySum(arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)), 1e-06)), arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)) AS w_decay, if(ifNull(equals(length(touch_ts), 0), 0), [], if(ifNull(equals(length(touch_ts), 1), 0), [1.0], if(ifNull(equals(length(touch_ts), 2), 0), [0.5, 0.5], arrayMap(w -> divide(w, greatest(arraySum(arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_140)s), 2.0), 1.0)))), touch_ts))), 1e-06)), arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_141)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position+ FROM per_touchpoint+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value+ FROM per_conversion_dim+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_142)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion)+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)+ ORDER BY influenced_conversions DESC, visitors DESC+ LIMIT 101+ OFFSET 0+ '''+# ---+# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_5_live_channel[new_events_schema]+ '''+ WITH attribution_session_identities AS MATERIALIZED (+ SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_2)s), greaterOrEquals(events.timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))+ GROUP BY session_id_v7, person_id), resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, dimensions AS latest, computed_at AS computed_at+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_127)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_128)s)), `$channel_type`, %(hogql_val_129)s), %(hogql_val_130)s, %(hogql_val_131)s, %(hogql_val_132)s, %(hogql_val_133)s, %(hogql_val_134)s, %(hogql_val_135)s, %(hogql_val_136)s) AS dimensions, now64(6, %(hogql_val_137)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_8)s), %(hogql_val_9)s), %(hogql_val_10)s), %(hogql_val_11)s)), %(hogql_val_12)s), %(hogql_val_13)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_14)s), %(hogql_val_15)s), %(hogql_val_16)s), %(hogql_val_17)s)), tuple(%(hogql_val_18)s, %(hogql_val_19)s, %(hogql_val_20)s, %(hogql_val_21)s, %(hogql_val_22)s, %(hogql_val_23)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_24)s), %(hogql_val_25)s), %(hogql_val_26)s), %(hogql_val_27)s)), %(hogql_val_28)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_29)s), %(hogql_val_30)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_31)s), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_35)s), %(hogql_val_36)s), %(hogql_val_37)s), %(hogql_val_38)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s)), %(hogql_val_43)s), %(hogql_val_44)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_45)s), %(hogql_val_46)s), %(hogql_val_47)s), %(hogql_val_48)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_49)s), %(hogql_val_50)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_51)s), %(hogql_val_52)s), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), 0), %(hogql_val_56)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_57)s), %(hogql_val_58)s), %(hogql_val_59)s), %(hogql_val_60)s)), %(hogql_val_61)s), %(hogql_val_62)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_63)s), %(hogql_val_64)s)), %(hogql_val_65)s, %(hogql_val_66)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_67)s), %(hogql_val_68)s), %(hogql_val_69)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_70)s), %(hogql_val_71)s), %(hogql_val_72)s), %(hogql_val_73)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_74)s), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s)), tuple(%(hogql_val_82)s, %(hogql_val_83)s, %(hogql_val_84)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_85)s), %(hogql_val_86)s)))), %(hogql_val_87)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_88)s), %(hogql_val_89)s), %(hogql_val_90)s), %(hogql_val_91)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_92)s), %(hogql_val_93)s), %(hogql_val_94)s), %(hogql_val_95)s)), %(hogql_val_96)s), %(hogql_val_97)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_98)s), %(hogql_val_99)s), %(hogql_val_100)s), %(hogql_val_101)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_102)s), %(hogql_val_103)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_104)s), %(hogql_val_105)s), %(hogql_val_106)s), %(hogql_val_107)s)), %(hogql_val_108)s), %(hogql_val_109)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_110)s), %(hogql_val_111)s), %(hogql_val_112)s), %(hogql_val_113)s)), %(hogql_val_114)s), %(hogql_val_115)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_116)s), %(hogql_val_117)s)), %(hogql_val_118)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s), 0), %(hogql_val_122)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_123)s), %(hogql_val_124)s)), %(hogql_val_125)s, %(hogql_val_126)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (+ SELECT DISTINCT attribution_session_identities.session_id_v7 AS session_id_v7+ FROM attribution_session_identities)), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))+ GROUP BY raw_sessions.session_id_v7)+ WHERE greater(toUnixTimestamp(`$start_timestamp`), 0)))), identities AS (+ SELECT attribution_session_identities.session_id_v7 AS session_id_v7, attribution_session_identities.person_id AS person_id, toTimeZone(attribution_session_identities.min_event_timestamp, %(hogql_val_138)s) AS min_event_timestamp, toTimeZone(attribution_session_identities.max_event_timestamp, %(hogql_val_139)s) AS max_event_timestamp, attribution_session_identities.pageview_count AS pageview_count+ FROM attribution_session_identities)+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_3)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_4)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_5)s) AS computed_at+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_140)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_141)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_142)s))) AS last_conversion+ FROM events_json AS events LEFT OUTER JOIN (+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 420)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_143)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_144)s, %(hogql_val_145)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_146)s, 6, %(hogql_val_147)s)))+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors+ FROM (+ SELECT cached_sessions.person_id AS person_id, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_148)s)), cached_sessions.channel_type, %(hogql_val_149)s) AS breakdown_value+ FROM resolved_cached_sessions AS cached_sessions+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s+ GROUP BY s.breakdown_value), person_arrays AS (+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints+ FROM (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS c LEFT JOIN (+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints+ FROM (+ SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_150)s)), cached_sessions.channel_type, %(hogql_val_151)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)+ WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), greaterOrEquals(toUnixTimestamp(toTimeZone(cached_sessions.max_event_timestamp, %(hogql_val_152)s)), minus(conv.first_conversion, 345600)))) AS d+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_153)s), 1.0)), touch_ts) AS w_linear, arrayMap(w -> divide(w, greatest(arraySum(arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)), 1e-06)), arrayMap(ts -> exp(multiply(-0.6931471805599453, divide(minus(conversion_time, ts), 86400))), touch_ts)) AS w_decay, if(ifNull(equals(length(touch_ts), 0), 0), [], if(ifNull(equals(length(touch_ts), 1), 0), [1.0], if(ifNull(equals(length(touch_ts), 2), 0), [0.5, 0.5], arrayMap(w -> divide(w, greatest(arraySum(arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_154)s), 2.0), 1.0)))), touch_ts))), 1e-06)), arrayMap(_pw -> ifNull(_pw, 0.0), arrayMap(ts -> if(ifNull(equals(ts, arrayMin(touch_ts)), isNull(ts) and isNull(arrayMin(touch_ts))), 0.4, if(ifNull(equals(ts, arrayMax(touch_ts)), isNull(ts) and isNull(arrayMax(touch_ts))), 0.4, divide(0.2, greatest(minus(accurateCastOrNull(length(touch_ts), %(hogql_val_155)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position+ FROM per_touchpoint+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value+ FROM per_conversion_dim+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_156)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key+ FROM per_conversion)+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)+ ORDER BY influenced_conversions DESC, visitors DESC+ LIMIT 101+ OFFSET 0+ '''+# ---diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.pyindex 2918f2be1bcd..529ffdc8524d 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_base.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py@@ -58,6 +58,12 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon# Narrower than the session-breakdown base's union: everything below reads attribution-only fields.query: MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery+ def get_cache_key_variant(self) -> str:+ variant = super().get_cache_key_variant()+ if self.config.live_session_resolution_enabled:+ return f"{variant}_live_session_resolution"+ return variant+@cached_propertydef goal(self) -> ConversionGoal:"""The requested goal, found among the team's configured goals.@@ -241,14 +247,19 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon)def _person_arrays_select(self, date_range: QueryDateRange) -> ast.SelectQuery:- """The credit side, served from the precompute when it can."""- if self.config.sessions_precomputation_enabled:+ """The credit side, using shared session resolution when eligible."""+ if self.config.sessions_precomputation_enabled or self.config.live_session_resolution_enabled:from .attribution_sessions_read import build_person_arrays # noqa: PLC0415 (import cycle)- with self.timings.measure("attribution_sessions_precompute_credit"):+ with self.timings.measure(+ "attribution_live_session_resolution"+ if self.config.live_session_resolution_enabled+ else "attribution_sessions_precompute_credit"+ ):precomputed = build_person_arrays(self, date_range)if precomputed is not None:- self._sessions_precompute_used = True+ self._sessions_precompute_used = not self.config.live_session_resolution_enabled+ self._live_session_resolution_used = self.config.live_session_resolution_enabledreturn precomputedreturn self._build_person_arrays_select(date_range)diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.pyindex 85f2ba9097a2..46cc2a19e411 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py@@ -31,9 +31,7 @@ _DIMENSION_FIELDS = {}-def _exceptional_dimensions(- modifiers: HogQLQueryModifiers, columns: set[str], start: datetime, end: datetime-) -> ast.SelectQuery:+def _raw_session_source(modifiers: HogQLQueryModifiers) -> tuple[str, ast.Expr]:is_v3 = modifiers.sessionTableVersion == SessionTableVersion.V3table = "raw_sessions_v3" if is_v3 else "raw_sessions"timestamp = (@@ -41,42 +39,31 @@ def _exceptional_dimensions(if is_v3else uuid_uint128_expr_to_timestamp_expr_v2(ast.Field(chain=[table, "session_id_v7"])))- # Use the live join's ID timestamp window so both paths count the same sessions.- bounds: dict[str, ast.Expr] = {- "start": ast.Constant(value=start),- "end": ast.Constant(value=end),- "reachback": ast.Constant(value=start - timedelta(days=SESSION_READ_REACHBACK_DAYS)),- "max_seconds": ast.Constant(value=MAX_PRECOMPUTED_SESSION_SECONDS),- }- # Split the duration budget around the ID timestamp to keep long sessions even when IDs and first events disagree.- # An earlier start either has an older ID with overlapping activity or crosses the earlier limit.- candidates = parse_select(- """- SELECT DISTINCT session_id_v7 FROM {table}- WHERE {timestamp} >= {lower} AND {timestamp} <= {upper}- AND ((max_timestamp >= {start} AND {timestamp} < {start})- OR min_timestamp < {timestamp} - toIntervalDay({reachback_days})- OR max_timestamp > {timestamp} + toIntervalSecond({remaining_budget}))- """,- placeholders={- "table": ast.Field(chain=[table]),- "timestamp": timestamp,- "lower": ast.Constant(value=start - timedelta(days=SESSION_BUFFER_DAYS)),- "upper": ast.Constant(value=end + timedelta(days=SESSION_BUFFER_DAYS)),- "start": bounds["start"],- "reachback_days": ast.Constant(value=SESSION_READ_REACHBACK_DAYS),- "remaining_budget": ast.Constant(- value=MAX_PRECOMPUTED_SESSION_SECONDS - int(timedelta(days=SESSION_READ_REACHBACK_DAYS).total_seconds())- ),- },- )+ return table, timestamp+++def _raw_dimensions(+ modifiers: HogQLQueryModifiers,+ columns: set[str],+ start: datetime,+ end: datetime,+ candidates: ast.SelectQuery,+ *,+ having: ast.Expr | None = None,+ require_valid_start: bool = False,+) -> ast.SelectQuery:+ table, timestamp = _raw_session_source(modifiers)fields = ["$start_timestamp","$end_timestamp",*[field for column, field in _DIMENSION_FIELDS.items() if column in columns],]context = HogQLContext(modifiers=modifiers)- select_sessions = select_from_sessions_table_v3 if is_v3 else select_from_sessions_table_v2+ select_sessions = (+ select_from_sessions_table_v3+ if modifiers.sessionTableVersion == SessionTableVersion.V3+ else select_from_sessions_table_v2+ )source = select_sessions({field: [field] for field in fields}, ast.SelectQuery(select=[ast.Constant(value=1)]), context)@@ -100,14 +87,7 @@ def _exceptional_dimensions(),])- source.having = parse_expr(- """- $end_timestamp >= {start} AND $start_timestamp <= {end}- AND ($start_timestamp < {reachback}- OR $end_timestamp > $start_timestamp + toIntervalSecond({max_seconds}))- """,- placeholders=bounds,- )+ source.having = having# Empty slots preserve tuple positions without reading unused entry properties.dimensions: list[ast.Expr] = [parse_expr("toStartOfHour(toTimeZone($start_timestamp, 'UTC'))"),@@ -130,12 +110,80 @@ def _exceptional_dimensions(placeholders={"source": source, "dimensions": ast.Tuple(exprs=dimensions)},)assert isinstance(query, ast.SelectQuery)+ if require_valid_start:+ query.where = parse_expr("toUnixTimestamp($start_timestamp) > 0")return query+def _exceptional_dimensions(+ modifiers: HogQLQueryModifiers, columns: set[str], start: datetime, end: datetime+) -> ast.SelectQuery:+ table, timestamp = _raw_session_source(modifiers)+ # Use the live join's ID timestamp window so both paths count the same sessions.+ bounds: dict[str, ast.Expr] = {+ "start": ast.Constant(value=start),+ "end": ast.Constant(value=end),+ "reachback": ast.Constant(value=start - timedelta(days=SESSION_READ_REACHBACK_DAYS)),+ "max_seconds": ast.Constant(value=MAX_PRECOMPUTED_SESSION_SECONDS),+ }+ # Split the duration budget around the ID timestamp to keep long sessions even when IDs and first events disagree.+ # An earlier start either has an older ID with overlapping activity or crosses the earlier limit.+ candidates = parse_select(+ """+ SELECT DISTINCT session_id_v7 FROM {table}+ WHERE {timestamp} >= {lower} AND {timestamp} <= {upper}+ AND ((max_timestamp >= {start} AND {timestamp} < {start})+ OR min_timestamp < {timestamp} - toIntervalDay({reachback_days})+ OR max_timestamp > {timestamp} + toIntervalSecond({remaining_budget}))+ """,+ placeholders={+ "table": ast.Field(chain=[table]),+ "timestamp": timestamp,+ "lower": ast.Constant(value=start - timedelta(days=SESSION_BUFFER_DAYS)),+ "upper": ast.Constant(value=end + timedelta(days=SESSION_BUFFER_DAYS)),+ "start": bounds["start"],+ "reachback_days": ast.Constant(value=SESSION_READ_REACHBACK_DAYS),+ "remaining_budget": ast.Constant(+ value=MAX_PRECOMPUTED_SESSION_SECONDS - int(timedelta(days=SESSION_READ_REACHBACK_DAYS).total_seconds())+ ),+ },+ )+ assert isinstance(candidates, ast.SelectQuery)+ having = parse_expr(+ """+ $end_timestamp >= {start} AND $start_timestamp <= {end}+ AND ($start_timestamp < {reachback}+ OR $end_timestamp > $start_timestamp + toIntervalSecond({max_seconds}))+ """,+ placeholders=bounds,+ )+ return _raw_dimensions(modifiers, columns, start, end, candidates, having=having)+++def _live_dimensions(+ modifiers: HogQLQueryModifiers, columns: set[str], start: datetime, end: datetime+) -> ast.SelectQuery:+ candidates = parse_select("SELECT DISTINCT session_id_v7 FROM attribution_session_identities")+ assert isinstance(candidates, ast.SelectQuery)+ return _raw_dimensions(modifiers, columns, start, end, candidates, require_valid_start=True)++def session_dimensions(- modifiers: HogQLQueryModifiers, columns: set[str], job_ids: list[str], start: datetime, end: datetime+ modifiers: HogQLQueryModifiers,+ columns: set[str],+ job_ids: list[str],+ start: datetime,+ end: datetime,+ *,+ live: bool = False,) -> ast.SelectQuery:+ if live:+ query = parse_select(+ "SELECT session_id_v7, dimensions AS latest, computed_at FROM {live}",+ placeholders={"live": _live_dimensions(modifiers, columns, start, end)},+ )+ assert isinstance(query, ast.SelectQuery)+ return query# A cached session can grow after materialization, so live exceptions must replace its old dimensions.query = parse_select("""diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.pyindex bd0ff85a5ed5..867911c0a9f9 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py@@ -1,6 +1,6 @@-"""Read cached session dimensions with the same event identity resolution as live attribution.+"""Share session dimensions and current event identities across attribution calculations.-Stored person IDs can outlive a merge, so only session dimensions come from the cache.+Stored person IDs can outlive a merge, so identity always comes from events."""from datetime import UTC, datetime, timedelta@@ -14,6 +14,7 @@ from posthog.hogql import astfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone+from posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.query_tagging import get_query_tag_valuefrom posthog.dataclasses import frozen@@ -84,6 +85,23 @@ def _session_modifiers_reason(runner: "AttributionQueryRunnerBase") -> Optional[return None+class _SessionConversionVisitor(TraversingVisitor):+ def __init__(self) -> None:+ super().__init__()+ self.depends_on_sessions = False++ def visit_field(self, node: ast.Field) -> None:+ if any(part in {"session", "sessions", "raw_sessions", "raw_sessions_v3"} for part in node.chain):+ self.depends_on_sessions = True+ super().visit_field(node)++ def visit_call(self, node: ast.Call) -> None:+ # matchesAction expands after this eligibility check and can introduce session filters.+ if node.name == "matchesAction":+ self.depends_on_sessions = True+ super().visit_call(node)++def ineligible_reason(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[str]:"""Why this query cannot read from the precompute, or None if it can.@@ -93,6 +111,13 @@ def ineligible_reason(runner: "AttributionQueryRunnerBase", date_range: QueryDatif reason := _session_modifiers_reason(runner):return reason+ if runner.config.live_session_resolution_enabled:+ conversion = _SessionConversionVisitor()+ conversion.visit(runner.conversion_condition)+ if conversion.depends_on_sessions:+ # The separate conversion scan has narrower session-ID bounds than the legacy combined scan.+ return "session_filtered_conversion_goal"+if not is_integer_timezone(runner.team.timezone):# `period_bucket` is an hourly UTC bucket, so a half-hour-offset team's midnight lands# mid-bucket and moves sessions across each edge.@@ -162,6 +187,8 @@ def _resolve(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -logger.info("attribution_sessions_precompute_ineligible", team_id=runner.team.pk, reason=reason)return None+ if runner.config.live_session_resolution_enabled:+ return []read = window(runner, date_range)# Materialize from a session's length before the window: the writer files a session under the# chunk holding its start, so a session that opened earlier and ran into the window lives in@@ -188,10 +215,9 @@ def _resolve(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -return [str(j) for j in result.job_ids]-def _read_sessions(dimensions: ast.SelectQuery, start: datetime, end: datetime) -> ast.SelectQuery:+def _session_identities(start: datetime, end: datetime) -> ast.SelectQuery:query = parse_select("""- WITH dimensions AS (SELECT * FROM {dimensions}), identities AS (SELECT events.$session_id_uuid AS session_id_v7, events.person_id AS person_id,min(events.timestamp) AS min_event_timestamp,max(events.timestamp) AS max_event_timestamp,@@ -200,7 +226,19 @@ def _read_sessions(dimensions: ast.SelectQuery, start: datetime, end: datetime)WHERE events.event = '$pageview'AND events.timestamp >= {start} AND events.timestamp <= {end}GROUP BY session_id_v7, person_id- )+ """,+ placeholders={"start": ast.Constant(value=start), "end": ast.Constant(value=end)},+ )+ assert isinstance(query, ast.SelectQuery)+ return query+++def _read_sessions(+ dimensions: ast.SelectQuery, start: datetime, end: datetime, *, live: bool = False+) -> ast.SelectQuery:+ query = parse_select(+ """+ WITH dimensions AS (SELECT * FROM {dimensions}), identities AS ({identities})SELECT i.session_id_v7, i.person_id, i.min_event_timestamp, i.max_event_timestamp, i.pageview_count,d.latest.1 AS period_bucket, d.latest.2 AS start_timestamp, d.latest.3 AS channel_type,d.latest.4 AS utm_source, d.latest.5 AS utm_medium, d.latest.6 AS utm_campaign,@@ -211,8 +249,11 @@ def _read_sessions(dimensions: ast.SelectQuery, start: datetime, end: datetime)""",placeholders={"dimensions": dimensions,- "start": ast.Constant(value=start),- "end": ast.Constant(value=end),+ "identities": (+ parse_select("SELECT * FROM attribution_session_identities")+ if live+ else _session_identities(start, end)+ ),},)assert isinstance(query, ast.SelectQuery)@@ -390,7 +431,7 @@ def _conversions_per_person(runner: "AttributionQueryRunnerBase", date_range: Qudef session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> dict[str, ast.CTE]:- if not runner.config.sessions_precomputation_enabled:+ if not (runner.config.sessions_precomputation_enabled or runner.config.live_session_resolution_enabled):return {}job_ids = _ensure(runner, date_range)if job_ids is None:@@ -401,38 +442,41 @@ def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRangcolumns.add("utm_source")if runner.query.excludeDirectTraffic:columns.add("channel_type")- # Reach and credit share the event scan; conversion bounds share the revenue aggregation.- return {- _SESSIONS_CTE: ast.CTE(- name=_SESSIONS_CTE,- expr=_read_sessions(- session_dimensions(- runner.modifiers or create_default_modifiers_for_team(runner.team),- columns,- job_ids,- read.start,- read.end,- ),- read.start,- read.end,- ),- cte_type="subquery",- materialized=True,- ),- _CONVERSIONS_CTE: ast.CTE(- name=_CONVERSIONS_CTE,- expr=_conversions_per_person(runner, date_range),+ dimensions = session_dimensions(+ runner.modifiers or create_default_modifiers_for_team(runner.team),+ columns,+ job_ids,+ read.start,+ read.end,+ live=runner.config.live_session_resolution_enabled,+ )+ sessions = _read_sessions(dimensions, read.start, read.end, live=runner.config.live_session_resolution_enabled)+ ctes: dict[str, ast.CTE] = {}+ if runner.config.live_session_resolution_enabled:+ ctes["attribution_session_identities"] = ast.CTE(+ name="attribution_session_identities",+ expr=_session_identities(read.start, read.end),cte_type="subquery",materialized=True,- ),- }+ )+ # Reach and credit share the event scan; conversion bounds share the revenue aggregation.+ ctes[_SESSIONS_CTE] = ast.CTE(+ name=_SESSIONS_CTE,+ expr=sessions,+ cte_type="subquery",+ materialized=True,+ )+ ctes[_CONVERSIONS_CTE] = ast.CTE(+ name=_CONVERSIONS_CTE,+ expr=_conversions_per_person(runner, date_range),+ cte_type="subquery",+ materialized=True,+ )+ return ctesdef build_person_arrays(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[ast.SelectQuery]:- """One row per converting person: its conversions, plus its touchpoints read from the precompute.-- Session dimensions stay cached while both touchpoints and conversions resolve identity from events.- """+ """One row per converting person, with touchpoints from the shared session resolution."""job_ids = _ensure(runner, date_range)if job_ids is None:return None@@ -448,6 +492,21 @@ def build_person_arrays(runner: "AttributionQueryRunnerBase", date_range: QueryD# after it is creditable either.upper = "last_conversion" if runner.allows_multiple_conversions_per_visitor else "first_conversion"+ conditions = _scope(read)+ if runner.config.live_session_resolution_enabled:+ # Event and session replicas can lag independently; credit still requires a pageview in the person's window.+ conditions.append(+ ast.CompareOperation(+ left=ast.Call(name="toUnixTimestamp", args=[_field("max_event_timestamp")]),+ op=ast.CompareOperationOp.GtEq,+ right=ast.ArithmeticOperation(+ left=ast.Field(chain=["conv", "first_conversion"]),+ op=ast.ArithmeticOperationOp.Sub,+ right=ast.Constant(value=runner.attribution_window_seconds),+ ),+ )+ )+# One conversion-bounds row per person preserves the CTE's unique session/person pairs.per_session = ast.SelectQuery(select=[@@ -481,7 +540,7 @@ def build_person_arrays(runner: "AttributionQueryRunnerBase", date_range: QueryD),),),- where=ast.And(exprs=_scope(read)),+ where=ast.And(exprs=conditions),)# Creditability is judged on the collapsed start, so a superseded row cannot decide it.diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.pyindex 590a32a9362f..338b1b50e504 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py@@ -104,11 +104,16 @@ class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[Marketvisitors to the display window instead let a conversion be credited to a touch from before therange while its person was missing from the denominator, reporting rates above 100%."""- if self.config.sessions_precomputation_enabled:- with self.timings.measure("attribution_sessions_precompute"):+ if self.config.sessions_precomputation_enabled or self.config.live_session_resolution_enabled:+ with self.timings.measure(+ "attribution_live_session_resolution"+ if self.config.live_session_resolution_enabled+ else "attribution_sessions_precompute"+ ):precomputed = build_reach(self, date_range)if precomputed is not None:- self._sessions_precompute_used = True+ self._sessions_precompute_used = not self.config.live_session_resolution_enabled+ self._live_session_resolution_used = self.config.live_session_resolution_enabledreturn precomputedbreakdown = self._breakdown_expr()diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.pyindex 696b6c248677..876b83b75bd5 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py@@ -191,6 +191,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,# Without this, a rollout where every query falls back to the live path looks identical to# one that works.self._sessions_precompute_used: bool = False+ self._live_session_resolution_used: bool = False# The job set backing this query, resolved once and shared by the reach and credit sides.# `resolved` separates "not looked up yet" from "looked up, cannot use the precompute".self._sessions_precompute_resolved: bool = False@@ -261,6 +262,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,"costs_sources_materialized": self._costs_sources_materialized,"costs_grain": self._costs_grain,"sessions_precompute_used": self._sessions_precompute_used,+ "live_session_resolution_used": self._live_session_resolution_used,}if error is None:props["timings"] = [{"k": t.k, "t": t.t} for t in self.timings.to_list()]diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.pyindex 246952433459..914a4d67d6dd 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py@@ -112,6 +112,7 @@ class MarketingAnalyticsConfig:conversion_goal_precomputation_enabled: bool = Falsecosts_precomputation_enabled: bool = Falsesessions_precomputation_enabled: bool = False+ live_session_resolution_enabled: bool = False@staticmethoddef _precompute_flags(team: "Team") -> dict[str, bool]:@@ -147,6 +148,12 @@ class MarketingAnalyticsConfig:groups=groups,group_properties=group_properties,),+ "live_sessions": feature_enabled_or_false(+ "marketing-analytics-live-session-resolution",+ str(team.uuid),+ groups=groups,+ group_properties=group_properties,+ ),"sessions": feature_enabled_or_false("marketing-analytics-sessions-precomputation",str(team.uuid),@@ -207,6 +214,7 @@ class MarketingAnalyticsConfig:config.conversion_goal_precomputation_enabled = flags["conversion"]config.costs_precomputation_enabled = flags["costs"]config.sessions_precomputation_enabled = flags["sessions"]+ config.live_session_resolution_enabled = flags["live_sessions"]# Gate multi-touch attribution behind its flag; fall back to last-touch when disabled. Evaluated# only for multi-touch modes so single-touch never triggers the flag call.diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.pyindex bbfedb31767e..7fe64a7eeb59 100644--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py@@ -409,17 +409,20 @@ class TestMarketingAnalyticsAttributionPathsQueryRunner(ClickhouseTestMixin, Bas# Same three shapes as the attribution table: direct read, alias normalization, classifier.@parameterized.expand([- ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, False),- ("source", MarketingAnalyticsAttributionBreakdown.SOURCE, False),- ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, False),- ("cached_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True),- ("cached_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True),- ("cached_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True),+ ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, False, False),+ ("source", MarketingAnalyticsAttributionBreakdown.SOURCE, False, False),+ ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, False, False),+ ("cached_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True, False),+ ("cached_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True, False),+ ("cached_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True, False),+ ("shared_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True, True),+ ("shared_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True, True),+ ("shared_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True, True),])@pytest.mark.usefixtures("unittest_snapshot")def test_attribution_paths_sql(- self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown, precomputed: bool+ self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown, precomputed: bool, live_resolution: bool) -> None:query = MarketingAnalyticsAttributionPathsQuery(dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),@@ -429,6 +432,7 @@ class TestMarketingAnalyticsAttributionPathsQueryRunner(ClickhouseTestMixin, Bas)runner = MarketingAnalyticsAttributionPathsQueryRunner(query=query, team=self.team)runner.config.sessions_precomputation_enabled = precomputed+ runner.config.live_session_resolution_enabled = live_resolutioncontext = runner._shared_hogql_contextcontext.enable_select_queries = Truewith patch(@@ -436,7 +440,8 @@ class TestMarketingAnalyticsAttributionPathsQueryRunner(ClickhouseTestMixin, Basreturn_value=LazyComputationResult(ready=True, job_ids=[UUID(int=1)]),):printed = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")- assert runner._sessions_precompute_used == precomputed+ assert runner._sessions_precompute_used == (precomputed and not live_resolution)+ assert runner._live_session_resolution_used == live_resolutionsql = printed[0] if isinstance(printed, tuple) else printedpretty = pretty_print_in_tests(sql, self.team.pk)assert pretty == self.sql_snapshot(pretty)diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.pyindex 47677a4b70de..1f7ce50ad555 100644--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py@@ -1,6 +1,7 @@from datetime import UTC, datetime, timedeltafrom typing import Optionalfrom uuid import UUID+from zoneinfo import ZoneInfoimport time_machinefrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events@@ -24,6 +25,8 @@ from posthog.schema import (SessionTableVersion,)+from posthog.hogql.escape_sql import escape_clickhouse_identifier+from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import tags_contextfrom posthog.dataclasses import frozen@@ -101,7 +104,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):campaign: str,event_offsets_minutes: list[int],source: Optional[str] = None,- ) -> None:+ ) -> UUID:"""A session opening at `opened_at` with a pageview at each offset after it."""session_id = str(uuid7(opened_at.strftime("%Y-%m-%dT%H:%M:%SZ")))for offset in event_offsets_minutes:@@ -122,6 +125,8 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):},)+ return UUID(session_id)+def _conversion(self, distinct_id: str, at: datetime) -> None:_create_event(team=self.team,@@ -136,6 +141,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):breakdown: MarketingAnalyticsAttributionBreakdown,*,precomputed: bool,+ live_resolution: bool = False,exclude_direct: bool = False,exclude_unattributed: bool = False,allow_multiple_conversions: bool | None = None,@@ -153,6 +159,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):)runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)runner.config.sessions_precomputation_enabled = precomputed+ runner.config.live_session_resolution_enabled = live_resolutionresponse = runner.calculate()rows = {row.breakdownValue: _AttributionCounts(visitors=row.visitors, conversions=row.influencedConversions)@@ -223,6 +230,9 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):assert not live_usedassert pre_used, "the precomputed path was not used, so this proves nothing"assert pre == live, f"precomputed={pre} live={live}"+ shared, used = self._run(breakdown, precomputed=False, live_resolution=True)+ assert not used+ assert shared == livedef test_a_session_stored_under_two_jobs_is_one_touchpoint(self) -> None:# A session's stored start is the earliest event seen when its chunk ran. A later event that@@ -508,7 +518,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):(MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),):responses = []- for precomputed in (False, True):+ for precomputed, live_resolution in ((False, False), (True, False), (True, True)):runner = runner_type(query=query_type(dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),@@ -519,8 +529,10 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):team=self.team,)runner.config.sessions_precomputation_enabled = precomputed+ runner.config.live_session_resolution_enabled = live_resolutionresponse = runner.calculate()- assert runner._sessions_precompute_used is (precomputed and ready)+ assert runner._sessions_precompute_used is (precomputed and ready and not live_resolution)+ assert runner._live_session_resolution_used is live_resolutionassert response.resultsresponses.append(response.results)if isinstance(response, MarketingAnalyticsAttributionQueryResponse):@@ -530,6 +542,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):else:assert response.attributedConversions == 2self.assertCountEqual(responses[0], responses[1])+ self.assertCountEqual(responses[0], responses[2])@parameterized.expand([(SessionTableVersion.V2,), (SessionTableVersion.V3,)])def test_long_session_growth_replaces_cached_dimensions(self, version: SessionTableVersion) -> None:@@ -665,11 +678,13 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):(MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),):responses = []- for precomputed in (False, True):+ for precomputed, live_resolution in ((False, False), (True, False), (True, True)):runner = runner_type(query=query_type(**query_args), team=self.team)runner.config.sessions_precomputation_enabled = precomputed+ runner.config.live_session_resolution_enabled = live_resolutionresponse = runner.calculate()- self.assertEqual(runner._sessions_precompute_used, precomputed)+ self.assertEqual(runner._sessions_precompute_used, precomputed and not live_resolution)+ self.assertEqual(runner._live_session_resolution_used, live_resolution)responses.append(response.results)if isinstance(response, MarketingAnalyticsAttributionQueryResponse):self.assertEqual(response.totalConversions, 1)@@ -677,6 +692,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):else:self.assertEqual(response.attributedConversions, 0 if state == "mapping_first" else 1)self.assertCountEqual(responses[0], responses[1])+ self.assertCountEqual(responses[0], responses[2])stored_after = sync_execute("SELECT * FROM web_sessions_dimensional_preaggregated WHERE team_id = %(team)s ORDER BY session_id_v7",@@ -856,3 +872,201 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):assert response.attributedConversions == expected_conversionsresults.append(response.results)self.assertCountEqual(results[0], results[1])++ def _assert_shared_live_parity(+ self, date_range: DateRange, *, campaigns: set[str], total_conversions: int, attributed_conversions: int+ ) -> None:+ for query_type, runner_type in (+ (MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),+ (MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),+ ):+ results = []+ for shared in (False, True):+ runner = runner_type(+ query=query_type(+ dateRange=date_range,+ breakdownBy=MarketingAnalyticsAttributionBreakdown.CAMPAIGN,+ conversionGoalId=GOAL_ID,+ properties=[],+ ),+ team=self.team,+ )+ runner.config.sessions_precomputation_enabled = shared+ runner.config.live_session_resolution_enabled = shared+ response = runner.calculate()+ assert not runner._sessions_precompute_used+ assert runner._live_session_resolution_used is shared+ assert response.totalConversions == total_conversions+ if isinstance(response, MarketingAnalyticsAttributionQueryResponse):+ assert {row.breakdownValue for row in response.results or []} == campaigns+ assert response.unattributedConversions == total_conversions - attributed_conversions+ else:+ assert response.attributedConversions == attributed_conversions+ results.append(response.results)+ self.assertCountEqual(results[0], results[1])++ @parameterized.expand(+ [+ (version, tz)+ for version in (SessionTableVersion.V2, SessionTableVersion.V3)+ for tz in ("UTC", "America/Los_Angeles")+ ]+ )+ def test_shared_live_resolution_crosses_midnight_without_cached_jobs(+ self, version: SessionTableVersion, boundary_timezone: str+ ) -> None:+ self.team.timezone = "America/Los_Angeles"+ self.team.modifiers = {"sessionTableVersion": version}+ boundary = datetime(2023, 1, 13, tzinfo=ZoneInfo(boundary_timezone)).astimezone(UTC)+ create_person(team=self.team, distinct_ids=["before-midnight", "after-midnight"])+ with time_machine.travel(boundary - timedelta(minutes=1), tick=False) as clock:+ self._session(+ "before-midnight", boundary - timedelta(minutes=3), campaign="before", event_offsets_minutes=[0]+ )+ self._conversion("before-midnight", boundary - timedelta(minutes=2))+ flush_persons_and_events()+ self._assert_shared_live_parity(+ DateRange(date_from="-7d"), campaigns={"before"}, total_conversions=1, attributed_conversions=1+ )+ clock.shift(timedelta(minutes=3))+ self._session(+ "after-midnight", boundary + timedelta(seconds=30), campaign="after", event_offsets_minutes=[0]+ )+ self._conversion("after-midnight", boundary + timedelta(minutes=1))+ flush_persons_and_events()+ self._assert_shared_live_parity(+ DateRange(date_from="-7d"), campaigns={"before", "after"}, total_conversions=2, attributed_conversions=2+ )+ assert not PreaggregationJob.objects.filter(team=self.team).exists()++ def test_shared_live_resolution_reads_delayed_nullable_campaign(self) -> None:+ self.team.modifiers = {"sessionTableVersion": SessionTableVersion.V3}+ create_person(team=self.team, distinct_ids=["visitor"])+ opened_at = datetime(2023, 1, 11, 9, tzinfo=UTC)+ session_id = uuid7("2023-01-11T09:00:00Z")+ _create_event(+ team=self.team,+ distinct_id="visitor",+ event="$pageview",+ timestamp=opened_at,+ properties={"$session_id": str(session_id), "$current_url": "https://example.com/"},+ )+ self._conversion("visitor", opened_at + timedelta(hours=1))+ flush_persons_and_events()+ self._materialize()+ sync_execute(+ """+ INSERT INTO raw_sessions_v3+ (team_id, session_id_v7, min_timestamp, max_timestamp, max_inserted_at, entry_utm_campaign)+ SELECT %(team)s, toUInt128(%(session)s),+ toDateTime64('2023-01-11 09:05:00', 6, 'UTC'),+ toDateTime64('2023-01-11 09:05:00', 6, 'UTC'),+ toDateTime64('2023-01-11 09:05:00', 6, 'UTC'),+ initializeAggregation('argMinState', toNullable('delayed'), toDateTime64('2023-01-11 09:05:00', 6, 'UTC'))+ SETTINGS insert_distributed_sync=1+ """,+ {"team": self.team.pk, "session": str(session_id.int)},+ )+ self._assert_shared_live_parity(+ DateRange(date_from=DATE_FROM, date_to=DATE_TO),+ campaigns={"delayed"},+ total_conversions=1,+ attributed_conversions=1,+ )++ @parameterized.expand([(SessionTableVersion.V2,), (SessionTableVersion.V3,)])+ def test_shared_live_resolution_preserves_independent_session_and_event_bounds(+ self, version: SessionTableVersion+ ) -> None:+ self.team.modifiers = {"sessionTableVersion": version}+ normal_pageview = datetime(2023, 1, 11, 9, tzinfo=UTC)+ before_credit_bound = datetime(2023, 1, 8, 11, 59, 59, tzinfo=UTC)+ later_raw_start = datetime(2023, 1, 8, 12, 0, 1, tzinfo=UTC)+ scenarios = [+ ("raw-before-range", normal_pageview, [0], datetime(2023, 1, 5, 23, tzinfo=UTC)),+ ("raw-after-range", normal_pageview, [0], datetime(2023, 1, 21, 12, tzinfo=UTC)),+ ("raw-epoch", normal_pageview, [0], datetime(1970, 1, 1, tzinfo=UTC)),+ ("pageview-before-credit-bound", before_credit_bound, [0], later_raw_start),+ ("later-pageview-meets-credit-bound", before_credit_bound, [0, 1], later_raw_start),+ ("raw-absent", normal_pageview, [0], None),+ ]+ session_ids = {}+ for campaign, pageview_at, offsets, _ in scenarios:+ create_person(team=self.team, distinct_ids=[campaign])+ session_ids[campaign] = self._session(+ campaign, pageview_at, campaign=campaign, event_offsets_minutes=offsets+ )+ self._conversion(campaign, datetime(2023, 1, 12, 12, tzinfo=UTC))+ flush_persons_and_events()+ table = escape_clickhouse_identifier(+ "sharded_raw_sessions_v3" if version == SessionTableVersion.V3 else "sharded_raw_sessions"+ )+ for campaign, _, _, raw_at in scenarios:+ parameters = {"team": self.team.pk, "session": str(session_ids[campaign].int)}+ if raw_at is None:+ sync_execute(+ f"ALTER TABLE {table} DELETE WHERE team_id = %(team)s AND session_id_v7 = toUInt128(%(session)s) SETTINGS mutations_sync = 2",+ parameters,+ )+ else:+ sync_execute(+ f"ALTER TABLE {table} UPDATE min_timestamp = toDateTime64(%(timestamp)s, 6, 'UTC'), "+ "max_timestamp = toDateTime64(%(timestamp)s, 6, 'UTC') "+ "WHERE team_id = %(team)s AND session_id_v7 = toUInt128(%(session)s) SETTINGS mutations_sync = 2",+ {**parameters, "timestamp": raw_at.strftime("%Y-%m-%d %H:%M:%S.%f")},+ )+ self._assert_shared_live_parity(+ DateRange(date_from=DATE_FROM, date_to=DATE_TO),+ campaigns={+ "raw-before-range",+ "raw-after-range",+ "pageview-before-credit-bound",+ "later-pageview-meets-credit-bound",+ },+ total_conversions=len(scenarios),+ attributed_conversions=1,+ )++ def test_shared_live_resolution_preserves_session_filtered_conversion_goals(self) -> None:+ config = self.team.marketing_analytics_config+ config.conversion_goals[0]["properties"] = [+ {"type": "session", "key": "$entry_utm_source", "operator": "exact", "value": ["google"]}+ ]+ config.save()+ create_person(team=self.team, distinct_ids=["visitor"])+ for at, conversion_at, campaign in (+ (datetime(2023, 1, 6, 9, tzinfo=UTC), datetime(2023, 1, 13, 10, tzinfo=UTC), "older-id"),+ (datetime(2023, 1, 12, 9, tzinfo=UTC), datetime(2023, 1, 12, 10, tzinfo=UTC), "recent-id"),+ ):+ session_id = self._session("visitor", at, campaign=campaign, event_offsets_minutes=[0], source="google")+ _create_event(+ team=self.team,+ distinct_id="visitor",+ event=CONVERSION_EVENT,+ timestamp=conversion_at,+ properties={"$session_id": str(session_id), "revenue": 100},+ )+ flush_persons_and_events()+ for query_type, runner_type in (+ (MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),+ (MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),+ ):+ responses = []+ for shared in (False, True):+ runner = runner_type(+ query=query_type(+ dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),+ breakdownBy=MarketingAnalyticsAttributionBreakdown.CAMPAIGN,+ conversionGoalId=GOAL_ID,+ properties=[],+ allowMultipleConversionsPerVisitor=True,+ ),+ team=self.team,+ )+ runner.config.sessions_precomputation_enabled = False+ runner.config.live_session_resolution_enabled = shared+ response = runner.calculate()+ assert response.totalConversions == 2+ assert not runner._live_session_resolution_used+ responses.append(response.results)+ self.assertCountEqual(responses[0], responses[1])diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.pyindex 3a3d08a0993b..c968fa43c65e 100644--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py@@ -1,3 +1,4 @@+from copy import copyfrom datetime import UTC, datetime, timedeltafrom uuid import UUID@@ -12,7 +13,9 @@ from posthog.schema import (ConversionGoalFilter1,CustomChannelRule,DateRange,+ HogQLPropertyFilter,HogQLQueryModifiers,+ MarketingAnalyticsAttributionPathsQuery,MarketingAnalyticsAttributionQuery,PropertyMathType,)@@ -32,6 +35,9 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execucompute_query_hash,)from products.marketing_analytics.backend.hogql_queries import attribution_sessions_read, marketing_sessions_precompute+from products.marketing_analytics.backend.hogql_queries.attribution_paths_query_runner import (+ MarketingAnalyticsAttributionPathsQueryRunner,+)from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (MarketingAnalyticsAttributionQueryRunner,)@@ -321,3 +327,82 @@ class TestAttributionSessionsRead(SimpleTestCase):with patch.object(attribution_sessions_read, "ensure_marketing_sessions_precomputed") as ensure:runner.to_query()ensure.assert_not_called()++ @parameterized.expand(+ [+ ("session.$entry_utm_source = 'google'", True),+ ("events.session.$channel_type = 'Paid Search'", True),+ ("$session_id IN (SELECT session_id FROM sessions)", True),+ ("matchesAction(1)", True),+ ("not(matchesAction(1))", True),+ ("properties.utm_source = 'google'", False),+ ("$session_id IS NOT NULL", False),+ ]+ )+ def test_session_dependent_conversion_conditions_keep_legacy_resolution(self, condition: str, legacy: bool) -> None:+ goal = ConversionGoalFilter1(+ event="purchase",+ name="Purchases",+ conversion_goal_id="session-goal",+ conversion_goal_name="Purchases",+ schema_map={},+ properties=[HogQLPropertyFilter(type="hogql", key=condition)],+ )+ self.team.marketing_analytics_config.conversion_goals = [goal.model_dump()]+ runner = MarketingAnalyticsAttributionQueryRunner(+ team=self.team,+ query=MarketingAnalyticsAttributionQuery(+ conversionGoalId="session-goal",+ properties=[],+ lookbackWindowDays=4,+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-20"),+ ),+ )+ runner.config.live_session_resolution_enabled = True+ reason = attribution_sessions_read.ineligible_reason(runner, runner.query_date_range)+ assert reason == ("session_filtered_conversion_goal" if legacy else None)++ @parameterized.expand(+ [+ ("table", MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),+ ("paths", MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),+ ]+ )+ def test_live_resolution_rollout_and_rollback_isolate_cached_results(+ self,+ _name: str,+ query_type: type[MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery],+ runner_type: type[MarketingAnalyticsAttributionQueryRunner | MarketingAnalyticsAttributionPathsQueryRunner],+ ) -> None:+ self.enterContext(patch.object(runner_type, "_products_modifiers_for_cache", return_value={}))+ self.enterContext(patch.object(runner_type, "_get_property_access_restrictions", return_value=None))+ live_keys = []+ for precomputed in (False, True):+ keys = []+ identities = []+ for live in (False, True, False):+ flags = {+ "marketing-analytics-live-session-resolution": live,+ "marketing-analytics-sessions-precomputation": precomputed,+ }+ with patch(+ "products.marketing_analytics.backend.hogql_queries.marketing_analytics_config.feature_enabled_or_false",+ side_effect=lambda key, *_args, flags=flags, **_kwargs: flags.get(key, False),+ ):+ runner = runner_type(+ team=copy(self.team),+ query=query_type(+ conversionGoalId="goal",+ properties=[],+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),+ ),+ )+ keys.append(runner.get_cache_key())+ identities.append(runner.get_query_identity())+ assert keys[0] != keys[1]+ assert keys[0] == keys[2]+ assert identities[0].query_hash == identities[1].query_hash == identities[2].query_hash+ assert identities[0].runtime_hash != identities[1].runtime_hash+ assert identities[0].runtime_hash == identities[2].runtime_hash+ live_keys.append(keys[1])+ assert live_keys[0] == live_keys[1]diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.pyindex 954530f7bf00..048afb41cb39 100644--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py@@ -135,6 +135,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTestlookback_days: int | None = None,allow_multiple_conversions: bool | None = None,filter_test_accounts: bool | None = False,+ live_resolution: bool = False,):flush_persons_and_events()query = MarketingAnalyticsAttributionQuery(@@ -148,7 +149,11 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTestfilterTestAccounts=filter_test_accounts,properties=[],)- return MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).calculate()+ runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)+ runner.config.live_session_resolution_enabled = live_resolution+ response = runner.calculate()+ assert runner._live_session_resolution_used == live_resolution+ return response@parameterized.expand([(False, "frequent"), (True, "valuable")])def test_revenue_ranking_precedes_row_limit(self, include_revenue: bool, expected: str) -> None:@@ -349,7 +354,8 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTestself.assertAlmostEqual(last_touch.conversions, 2.0, places=4)self.assertAlmostEqual(last_touch.conversionValue or 0.0, 200.0, places=2)- def test_every_model_splits_one_conversion_its_own_way(self):+ @parameterized.expand([(False,), (True,)])+ def test_every_model_splits_one_conversion_its_own_way(self, live_resolution: bool) -> None:# The one test that catches this design's central risk: five weight arrays are built per# conversion and exploded through a single shared ARRAY JOIN, so indexing the wrong array into a# model's column, or an off-by-one in `arrayEnumerate(ts)`, silently reports another model's@@ -360,7 +366,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTestself._session("p1", ONE_DAY_BEFORE, utm_campaign="late")self._conversion("p1", CONVERSION_AT, revenue=100.0)- response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN)+ response = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, live_resolution=live_resolution)by_campaign = self._by_breakdown(response)self.assertEqual(set(by_campaign), {"early", "middle", "late"})@@ -1053,7 +1059,13 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTestwith self.assertRaises(ValueError):MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).to_query()- def _printed_sql(self, breakdown: MarketingAnalyticsAttributionBreakdown, *, precomputed: bool = False) -> str:+ def _printed_sql(+ self,+ breakdown: MarketingAnalyticsAttributionBreakdown,+ *,+ precomputed: bool = False,+ live_resolution: bool = False,+ ) -> str:query = MarketingAnalyticsAttributionQuery(dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),breakdownBy=breakdown,@@ -1062,6 +1074,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest)runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)runner.config.sessions_precomputation_enabled = precomputed+ runner.config.live_session_resolution_enabled = live_resolutioncontext = runner._shared_hogql_context# execute_hogql_query flips this on the context it is handed; do the same to print the real query.context.enable_select_queries = True@@ -1071,7 +1084,8 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTestreturn_value=ready,):printed = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")- assert runner._sessions_precompute_used == precomputed+ assert runner._sessions_precompute_used == (precomputed and not live_resolution)+ assert runner._live_session_resolution_used == live_resolutionreturn pretty_print_in_tests(printed[0] if isinstance(printed, tuple) else printed, self.team.pk)# One breakdown per SQL shape. Campaign reads a stored property, and the five breakdowns not listed@@ -1092,12 +1106,17 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest# Entry properties must merge only for exceptional sessions; classifying the full range defeats the cache.@parameterized.expand([- ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN),- ("source", MarketingAnalyticsAttributionBreakdown.SOURCE),- ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL),+ ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, False),+ ("source", MarketingAnalyticsAttributionBreakdown.SOURCE, False),+ ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, False),+ ("live_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True),+ ("live_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True),+ ("live_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True),])@pytest.mark.usefixtures("unittest_snapshot")- def test_precomputed_sessions_sql(self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown):- printed = self._printed_sql(breakdown, precomputed=True)+ def test_precomputed_sessions_sql(+ self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown, live_resolution: bool+ ):+ printed = self._printed_sql(breakdown, precomputed=True, live_resolution=live_resolution)assert printed == self.sql_snapshot(printed)diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.pyindex 42860330e250..bef29fcee239 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py@@ -150,7 +150,7 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):)# Set on the team, not the runner: the previous-period runner builds its own config from the same# team instance, and it is the one that has to read the flag as on.- self.team._ma_precompute_flags = {"conversion": True, "costs": False, "sessions": False} # type: ignore[attr-defined]+ self.team._ma_precompute_flags = {"conversion": True, "costs": False, "sessions": False, "live_sessions": False} # type: ignore[attr-defined]runner = self._create_query_runner(query)response = runner.calculate()