: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): recover long sessions in cached attribution (#105229)
Javier Bahamondesee23afd26290
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.mdindex 04299be56704..42c6af8a3aa8 100644--- a/docs/internal/marketing-attribution-session-precompute.md+++ b/docs/internal/marketing-attribution-session-precompute.md@@ -1,6 +1,10 @@# Attribution session precompute-The sessions-precomputation flag enables the attribution table and paths reader. Cold, ineligible, failed, or unproven session coverage falls back to live queries. A sessions-only check rejects sessions that overlap the read window but started before its one-day reachback; longer custom session IDs cannot silently lose attribution.+The sessions-precomputation flag enables the attribution table and paths reader. Cold, ineligible, or failed job lookups fall back to live queries. Sessions that started before the one-day reachback or exceed the three-day writer scan budget read their dimensions live, while other sessions use the cache. These exceptions do not disable the cache for the entire query.++The writer excludes sessions longer than its scan budget. The reader also replaces dimensions of cached sessions that later grow beyond that budget, including growth after the report end. It first selects conservative candidates from raw timestamp rows, then checks their exact start/end after aggregation. This avoids holding aggregate state for ordinary sessions. It filters candidate IDs before merging entry properties and joins both dimension sources to current pageview identities. Session IDs and dimensions remain inside ClickHouse, so the SQL size does not grow with the exception count. Both raw-session reads retain the timestamp bounds used by live attribution. Sessions whose ID timestamp is more than three days before the extended attribution read window remain outside both lookups. Their source events remain stored. Expanding this coverage requires changing and validating live and cached attribution together.++The writer query change invalidates existing job hashes. Deploy both writer and reader before warming the new jobs; keep the reader flag off until the controlled rollout validates coverage and query cost.`MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS` covers display days. The proposed warmer adds the team's attribution lookback and one reachback day: default 90 + 90 + 1 = 181 trailing days, previously 90. This approximately doubles initial daily chunks and retained job coverage; actual scan/storage cost depends on session volume and duration. The allowlist and environment values are unchanged. Evaluate this cost before rollout. Query overrides beyond the total warmed span remain ineligible.@@ -8,9 +12,9 @@ With the existing serve-stale flag, readers may use jobs expired within six hourThe reader caches session dimensions, then joins them to current pageview identities by `session_id_v7`. It resolves both touchpoints and conversions through `events.person_id`, so person merges, splits, and delayed identity mappings follow the same behavior as live attribution without rebuilding session jobs. The stored `person_id` is not used for attribution.-Materialized CTEs share the pageview identity scan between reach and credit, and share the conversion aggregation with the timestamp bounds. Event scans remain necessary for identity and conversions; cached dimensions avoid the sessions join and channel classification. This uses the existing `web_sessions_dimensional_preaggregated` schema and does not require a migration.+Materialized CTEs share the pageview identity scan between reach and credit, and share the conversion aggregation with the timestamp bounds. Event scans remain necessary for identity and conversions; cached dimensions avoid merging entry properties and classifying channels for ordinary sessions. A narrow timestamp scan and selective dimension lookup handle exceptional sessions. This uses the existing `web_sessions_dimensional_preaggregated` schema and does not require a migration.-Queries that override the session table version or v2 join mode fall back to live attribution when they differ from the writer. AUTO and v2 share the same session semantics. Custom channel rules on either the query or the team, and disabled project-timezone conversion, also use the live path. Identity and execution-only modifiers do not invalidate cached dimensions.+Queries that override the session table version or v2 join mode fall back to live attribution when they differ from the writer. AUTO and v2 share the same session semantics. Custom channel rules can use cached dimensions when they match the writer's project rules, including rules that depend on the full entry URL. The writer classifies the channel before storing it and includes the rules in the job hash, so rule changes require fresh jobs. Queries with different rules, or disabled project-timezone conversion, use the live path. Identity and execution-only modifiers do not invalidate cached dimensions.Live and cached pageview scans include the full final second of the selected date range, matching conversion filters. This also applies to explicit fractional date bounds and pageview conversion goals.Attribution filters compare the event timestamp directly with the date bounds, using microsecond precision for the end of the range.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 8f1e15a7d8b0..1822c8bc07bb 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@@ -191,11 +191,27 @@# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_0_campaign'''WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, argMax(tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_5)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_6)s), web_sessions_dimensional_preaggregated.channel_type, web_sessions_dimensional_preaggregated.utm_source, web_sessions_dimensional_preaggregated.utm_medium, web_sessions_dimensional_preaggregated.utm_campaign, web_sessions_dimensional_preaggregated.utm_term, web_sessions_dimensional_preaggregated.utm_content, web_sessions_dimensional_preaggregated.referring_domain, web_sessions_dimensional_preaggregated.entry_pathname, web_sessions_dimensional_preaggregated.job_id), toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_7)s)) AS latest, max(toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_8)s)) AS computed_at- FROM web_sessions_dimensional_preaggregated- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_9)s)))- GROUP BY web_sessions_dimensional_preaggregated.session_id_v7), identities AS (- 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_10)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_11)s)) AS max_event_timestamp, count() AS pageview_count+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at+ FROM (+ SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, web_sessions_dimensional_preaggregated.utm_campaign, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_11)s) AS computed_at, 0 AS source_priority+ FROM web_sessions_dimensional_preaggregated+ WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_12)s))) UNION ALL+ SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_19)s)), `$start_timestamp`, %(hogql_val_20)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_21)s)), %(hogql_val_22)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_23)s)), %(hogql_val_24)s, %(hogql_val_25)s, %(hogql_val_26)s, %(hogql_val_27)s) AS dimensions, now64(6, %(hogql_val_28)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_13)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_14)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_15)s), %(hogql_val_16)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_17)s), %(hogql_val_18)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 raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), 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')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1))), greater(raw_sessions.max_timestamp, plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800))))))), 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+ HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d+ GROUP BY d.session_id_v7)), identities AS (+ 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_29)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_30)s)) AS max_event_timestamp, count() AS pageview_countFROM 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_idFROM person_distinct_id_overrides@@ -203,11 +219,11 @@GROUP BY person_distinct_id_overrides.distinct_idHAVING 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_12)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')))+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_31)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)- SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_2)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_3)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, (d.latest).11 AS job_id, toTimeZone(d.computed_at, %(hogql_val_4)s) AS computed_at+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)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_2)s) AS computed_atFROM 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_13)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_14)s), ''), 'null'), '^"|"$', ''), %(hogql_val_15)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_16)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_17)s))) AS last_conversion+ 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_32)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_33)s), ''), 'null'), '^"|"$', ''), %(hogql_val_34)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_35)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_36)s))) AS last_conversionFROM 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_idFROM person_distinct_id_overrides@@ -215,13 +231,13 @@GROUP BY person_distinct_id_overrides.distinct_idHAVING 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_18)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_19)s, %(hogql_val_20)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_21)s, 6, %(hogql_val_22)s)))+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_37)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_38)s, %(hogql_val_39)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_40)s, 6, %(hogql_val_41)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 visitorsFROM (- SELECT cached_sessions.person_id AS person_id, argMax(toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_23)s)), toTimeZone(cached_sessions.computed_at, %(hogql_val_24)s)) AS breakdown_value+ SELECT cached_sessions.person_id AS person_id, argMax(toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_42)s)), toTimeZone(cached_sessions.computed_at, %(hogql_val_43)s)) AS breakdown_valueFROM resolved_cached_sessions AS cached_sessions- WHERE and(in(cached_sessions.job_id, tuple(%(hogql_val_25)s)), 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')))+ 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')))GROUP BY cached_sessions.session_id_v7, person_id) AS sGROUP 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@@ -230,16 +246,16 @@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 touchpointsFROM (- SELECT conv.conv_person_id AS person_id, argMax(toUnixTimestamp(cached_sessions.start_timestamp), toTimeZone(cached_sessions.computed_at, %(hogql_val_26)s)) AS session_ts, argMax(toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_27)s)), toTimeZone(cached_sessions.computed_at, %(hogql_val_28)s)) AS session_dim, any(conv.first_conversion) AS first_conversion, any(conv.last_conversion) AS upper_bound+ SELECT conv.conv_person_id AS person_id, argMax(toUnixTimestamp(cached_sessions.start_timestamp), toTimeZone(cached_sessions.computed_at, %(hogql_val_44)s)) AS session_ts, argMax(toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_45)s)), toTimeZone(cached_sessions.computed_at, %(hogql_val_46)s)) AS session_dim, any(conv.first_conversion) AS first_conversion, any(conv.last_conversion) AS upper_boundFROM 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_conversionFROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)- WHERE and(in(cached_sessions.job_id, tuple(%(hogql_val_29)s)), 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')))+ 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')))GROUP BY conv.conv_person_id, cached_sessions.session_id_v7) AS dWHERE 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_30)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_31)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_32)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ 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_47)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_48)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_49)s), 2.0), 1.0)))), touch_ts)))))) AS w_positionFROM 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_positionFROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (@@ -249,7 +265,7 @@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_valueFROM per_conversion_dimGROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (- SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_33)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+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_50)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_keyFROM 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_keyFROM per_conversion)@@ -264,11 +280,27 @@# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_1_source'''WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, argMax(tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_5)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_6)s), web_sessions_dimensional_preaggregated.channel_type, web_sessions_dimensional_preaggregated.utm_source, web_sessions_dimensional_preaggregated.utm_medium, web_sessions_dimensional_preaggregated.utm_campaign, web_sessions_dimensional_preaggregated.utm_term, web_sessions_dimensional_preaggregated.utm_content, web_sessions_dimensional_preaggregated.referring_domain, web_sessions_dimensional_preaggregated.entry_pathname, web_sessions_dimensional_preaggregated.job_id), toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_7)s)) AS latest, max(toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_8)s)) AS computed_at- FROM web_sessions_dimensional_preaggregated- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_9)s)))- GROUP BY web_sessions_dimensional_preaggregated.session_id_v7), identities AS (- 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_10)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_11)s)) AS max_event_timestamp, count() AS pageview_count+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at+ FROM (+ SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority+ FROM web_sessions_dimensional_preaggregated+ WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL+ SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_18)s)), `$start_timestamp`, %(hogql_val_19)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_20)s)), %(hogql_val_21)s, %(hogql_val_22)s, %(hogql_val_23)s, %(hogql_val_24)s, %(hogql_val_25)s, %(hogql_val_26)s) AS dimensions, now64(6, %(hogql_val_27)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_16)s), %(hogql_val_17)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 raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), 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')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1))), greater(raw_sessions.max_timestamp, plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800))))))), 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+ HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d+ GROUP BY d.session_id_v7)), identities AS (+ 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_28)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_29)s)) AS max_event_timestamp, count() AS pageview_countFROM 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_idFROM person_distinct_id_overrides@@ -276,11 +308,11 @@GROUP BY person_distinct_id_overrides.distinct_idHAVING 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_12)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')))+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_30)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)- SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_2)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_3)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, (d.latest).11 AS job_id, toTimeZone(d.computed_at, %(hogql_val_4)s) AS computed_at+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)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_2)s) AS computed_atFROM 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_13)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_14)s), ''), 'null'), '^"|"$', ''), %(hogql_val_15)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_16)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_17)s))) AS last_conversion+ 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_31)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_32)s), ''), 'null'), '^"|"$', ''), %(hogql_val_33)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_34)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_35)s))) AS last_conversionFROM 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_idFROM person_distinct_id_overrides@@ -288,13 +320,13 @@GROUP BY person_distinct_id_overrides.distinct_idHAVING 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_18)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_19)s, %(hogql_val_20)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_21)s, 6, %(hogql_val_22)s)))+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_36)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_37)s, %(hogql_val_38)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_39)s, 6, %(hogql_val_40)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 visitorsFROM (- SELECT cached_sessions.person_id AS person_id, argMax(if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_23)s)), cached_sessions.utm_source, %(hogql_val_24)s)), [%(hogql_val_25)s, %(hogql_val_26)s, %(hogql_val_27)s]), %(hogql_val_28)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_29)s)), cached_sessions.utm_source, %(hogql_val_30)s)), [%(hogql_val_31)s, %(hogql_val_32)s, %(hogql_val_33)s, %(hogql_val_34)s, %(hogql_val_35)s, %(hogql_val_36)s, %(hogql_val_37)s, %(hogql_val_38)s]), %(hogql_val_39)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_40)s)), cached_sessions.utm_source, %(hogql_val_41)s)), [%(hogql_val_42)s]), %(hogql_val_43)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_44)s)), cached_sessions.utm_source, %(hogql_val_45)s)), [%(hogql_val_46)s, %(hogql_val_47)s, %(hogql_val_48)s, %(hogql_val_49)s, %(hogql_val_50)s, %(hogql_val_51)s, %(hogql_val_52)s, %(hogql_val_53)s, %(hogql_val_54)s]), %(hogql_val_55)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_56)s)), cached_sessions.utm_source, %(hogql_val_57)s))))), toTimeZone(cached_sessions.computed_at, %(hogql_val_58)s)) AS breakdown_value+ SELECT cached_sessions.person_id AS person_id, argMax(if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_41)s)), cached_sessions.utm_source, %(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, %(hogql_val_51)s, %(hogql_val_52)s, %(hogql_val_53)s, %(hogql_val_54)s, %(hogql_val_55)s, %(hogql_val_56)s]), %(hogql_val_57)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_58)s)), cached_sessions.utm_source, %(hogql_val_59)s)), [%(hogql_val_60)s]), %(hogql_val_61)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_62)s)), cached_sessions.utm_source, %(hogql_val_63)s)), [%(hogql_val_64)s, %(hogql_val_65)s, %(hogql_val_66)s, %(hogql_val_67)s, %(hogql_val_68)s, %(hogql_val_69)s, %(hogql_val_70)s, %(hogql_val_71)s, %(hogql_val_72)s]), %(hogql_val_73)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_74)s)), cached_sessions.utm_source, %(hogql_val_75)s))))), toTimeZone(cached_sessions.computed_at, %(hogql_val_76)s)) AS breakdown_valueFROM resolved_cached_sessions AS cached_sessions- WHERE and(in(cached_sessions.job_id, tuple(%(hogql_val_59)s)), 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')))+ 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')))GROUP BY cached_sessions.session_id_v7, person_id) AS sGROUP 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@@ -303,16 +335,16 @@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 touchpointsFROM (- SELECT conv.conv_person_id AS person_id, argMax(toUnixTimestamp(cached_sessions.start_timestamp), toTimeZone(cached_sessions.computed_at, %(hogql_val_60)s)) AS session_ts, argMax(if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_61)s)), cached_sessions.utm_source, %(hogql_val_62)s)), [%(hogql_val_63)s, %(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, %(hogql_val_72)s, %(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(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_82)s)), cached_sessions.utm_source, %(hogql_val_83)s)), [%(hogql_val_84)s, %(hogql_val_85)s, %(hogql_val_86)s, %(hogql_val_87)s, %(hogql_val_88)s, %(hogql_val_89)s, %(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s]), %(hogql_val_93)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_94)s)), cached_sessions.utm_source, %(hogql_val_95)s))))), toTimeZone(cached_sessions.computed_at, %(hogql_val_96)s)) AS session_dim, any(conv.first_conversion) AS first_conversion, any(conv.last_conversion) AS upper_bound+ SELECT conv.conv_person_id AS person_id, argMax(toUnixTimestamp(cached_sessions.start_timestamp), toTimeZone(cached_sessions.computed_at, %(hogql_val_77)s)) AS session_ts, argMax(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, %(hogql_val_82)s]), %(hogql_val_83)s, 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, %(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s, %(hogql_val_93)s]), %(hogql_val_94)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_95)s)), cached_sessions.utm_source, %(hogql_val_96)s)), [%(hogql_val_97)s]), %(hogql_val_98)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_99)s)), cached_sessions.utm_source, %(hogql_val_100)s)), [%(hogql_val_101)s, %(hogql_val_102)s, %(hogql_val_103)s, %(hogql_val_104)s, %(hogql_val_105)s, %(hogql_val_106)s, %(hogql_val_107)s, %(hogql_val_108)s, %(hogql_val_109)s]), %(hogql_val_110)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_111)s)), cached_sessions.utm_source, %(hogql_val_112)s))))), toTimeZone(cached_sessions.computed_at, %(hogql_val_113)s)) AS session_dim, any(conv.first_conversion) AS first_conversion, any(conv.last_conversion) AS upper_boundFROM 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_conversionFROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)- WHERE and(in(cached_sessions.job_id, tuple(%(hogql_val_97)s)), 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')))+ 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')))GROUP BY conv.conv_person_id, cached_sessions.session_id_v7) AS dWHERE 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_98)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_99)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_100)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ 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_114)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_115)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_116)s), 2.0), 1.0)))), touch_ts)))))) AS w_positionFROM 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_positionFROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (@@ -322,7 +354,7 @@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_valueFROM per_conversion_dimGROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (- SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_101)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+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_117)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_keyFROM 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_keyFROM per_conversion)@@ -337,11 +369,27 @@# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_2_channel'''WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, argMax(tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_5)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_6)s), web_sessions_dimensional_preaggregated.channel_type, web_sessions_dimensional_preaggregated.utm_source, web_sessions_dimensional_preaggregated.utm_medium, web_sessions_dimensional_preaggregated.utm_campaign, web_sessions_dimensional_preaggregated.utm_term, web_sessions_dimensional_preaggregated.utm_content, web_sessions_dimensional_preaggregated.referring_domain, web_sessions_dimensional_preaggregated.entry_pathname, web_sessions_dimensional_preaggregated.job_id), toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_7)s)) AS latest, max(toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_8)s)) AS computed_at- FROM web_sessions_dimensional_preaggregated- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_9)s)))- GROUP BY web_sessions_dimensional_preaggregated.session_id_v7), identities AS (- 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_10)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_11)s)) AS max_event_timestamp, count() AS pageview_count+ SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at+ FROM (+ SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at+ FROM (+ SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), web_sessions_dimensional_preaggregated.channel_type, %(hogql_val_5)s, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority+ FROM web_sessions_dimensional_preaggregated+ WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL+ SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority+ FROM (+ SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_135)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_136)s)), `$channel_type`, %(hogql_val_137)s), %(hogql_val_138)s, %(hogql_val_139)s, %(hogql_val_140)s, %(hogql_val_141)s, %(hogql_val_142)s, %(hogql_val_143)s, %(hogql_val_144)s) AS dimensions, now64(6, %(hogql_val_145)s) AS computed_at, 1 AS source_priority+ FROM (+ SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_16)s), %(hogql_val_17)s), %(hogql_val_18)s), %(hogql_val_19)s)), %(hogql_val_20)s), %(hogql_val_21)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_22)s), %(hogql_val_23)s), %(hogql_val_24)s), %(hogql_val_25)s)), tuple(%(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s, %(hogql_val_30)s, %(hogql_val_31)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s), %(hogql_val_35)s)), %(hogql_val_36)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_37)s), %(hogql_val_38)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)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_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)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_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_47)s), %(hogql_val_48)s), %(hogql_val_49)s), %(hogql_val_50)s)), %(hogql_val_51)s), %(hogql_val_52)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_53)s), %(hogql_val_54)s), %(hogql_val_55)s), %(hogql_val_56)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_59)s), %(hogql_val_60)s), %(hogql_val_61)s), %(hogql_val_62)s), %(hogql_val_63)s), 0), %(hogql_val_64)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_65)s), %(hogql_val_66)s), %(hogql_val_67)s), %(hogql_val_68)s)), %(hogql_val_69)s), %(hogql_val_70)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_71)s), %(hogql_val_72)s)), %(hogql_val_73)s, %(hogql_val_74)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_82)s), %(hogql_val_83)s), %(hogql_val_84)s), %(hogql_val_85)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_86)s), %(hogql_val_87)s), %(hogql_val_88)s), %(hogql_val_89)s)), tuple(%(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_93)s), %(hogql_val_94)s)))), %(hogql_val_95)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_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)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_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_100)s), %(hogql_val_101)s), %(hogql_val_102)s), %(hogql_val_103)s)), %(hogql_val_104)s), %(hogql_val_105)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_106)s), %(hogql_val_107)s), %(hogql_val_108)s), %(hogql_val_109)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_112)s), %(hogql_val_113)s), %(hogql_val_114)s), %(hogql_val_115)s)), %(hogql_val_116)s), %(hogql_val_117)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_118)s), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s)), %(hogql_val_122)s), %(hogql_val_123)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_124)s), %(hogql_val_125)s)), %(hogql_val_126)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_127)s), %(hogql_val_128)s), %(hogql_val_129)s), 0), %(hogql_val_130)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_131)s), %(hogql_val_132)s)), %(hogql_val_133)s, %(hogql_val_134)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 raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 420), 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')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1))), greater(raw_sessions.max_timestamp, plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800))))))), 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+ HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d+ GROUP BY d.session_id_v7)), identities AS (+ 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_146)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_147)s)) AS max_event_timestamp, count() AS pageview_countFROM 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_idFROM person_distinct_id_overrides@@ -349,11 +397,11 @@GROUP BY person_distinct_id_overrides.distinct_idHAVING 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_12)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')))+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_148)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)- SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_2)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_3)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, (d.latest).11 AS job_id, toTimeZone(d.computed_at, %(hogql_val_4)s) AS computed_at+ SELECT i.session_id_v7 AS session_id_v7, i.person_id AS person_id, toTimeZone(i.min_event_timestamp, %(hogql_val_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)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_2)s) AS computed_atFROM 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_13)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_14)s), ''), 'null'), '^"|"$', ''), %(hogql_val_15)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_16)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_17)s))) AS last_conversion+ 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_149)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_150)s), ''), 'null'), '^"|"$', ''), %(hogql_val_151)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_152)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_153)s))) AS last_conversionFROM 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_idFROM person_distinct_id_overrides@@ -361,13 +409,13 @@GROUP BY person_distinct_id_overrides.distinct_idHAVING 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_18)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_19)s, %(hogql_val_20)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_21)s, 6, %(hogql_val_22)s)))+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_154)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_155)s, %(hogql_val_156)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_157)s, 6, %(hogql_val_158)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 visitorsFROM (- SELECT cached_sessions.person_id AS person_id, argMax(if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_23)s)), cached_sessions.channel_type, %(hogql_val_24)s), toTimeZone(cached_sessions.computed_at, %(hogql_val_25)s)) AS breakdown_value+ SELECT cached_sessions.person_id AS person_id, argMax(if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_159)s)), cached_sessions.channel_type, %(hogql_val_160)s), toTimeZone(cached_sessions.computed_at, %(hogql_val_161)s)) AS breakdown_valueFROM resolved_cached_sessions AS cached_sessions- WHERE and(in(cached_sessions.job_id, tuple(%(hogql_val_26)s)), 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')))+ 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')))GROUP BY cached_sessions.session_id_v7, person_id) AS sGROUP 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@@ -376,16 +424,16 @@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 touchpointsFROM (- SELECT conv.conv_person_id AS person_id, argMax(toUnixTimestamp(cached_sessions.start_timestamp), toTimeZone(cached_sessions.computed_at, %(hogql_val_27)s)) AS session_ts, argMax(if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_28)s)), cached_sessions.channel_type, %(hogql_val_29)s), toTimeZone(cached_sessions.computed_at, %(hogql_val_30)s)) AS session_dim, any(conv.first_conversion) AS first_conversion, any(conv.last_conversion) AS upper_bound+ SELECT conv.conv_person_id AS person_id, argMax(toUnixTimestamp(cached_sessions.start_timestamp), toTimeZone(cached_sessions.computed_at, %(hogql_val_162)s)) AS session_ts, argMax(if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_163)s)), cached_sessions.channel_type, %(hogql_val_164)s), toTimeZone(cached_sessions.computed_at, %(hogql_val_165)s)) AS session_dim, any(conv.first_conversion) AS first_conversion, any(conv.last_conversion) AS upper_boundFROM 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_conversionFROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)- WHERE and(in(cached_sessions.job_id, tuple(%(hogql_val_31)s)), 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')))+ 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')))GROUP BY conv.conv_person_id, cached_sessions.session_id_v7) AS dWHERE 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_32)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_33)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_34)s), 2.0), 1.0)))), touch_ts)))))) AS w_position+ 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_166)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_167)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_168)s), 2.0), 1.0)))), touch_ts)))))) AS w_positionFROM 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_positionFROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (@@ -395,7 +443,7 @@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_valueFROM per_conversion_dimGROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (- SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_35)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+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_169)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_keyFROM 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_keyFROM per_conversion)diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.pynew file mode 100644index 000000000000..85f2ba9097a2--- /dev/null+++ b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py@@ -0,0 +1,172 @@+from __future__ import annotations++from datetime import datetime, timedelta+from typing import TYPE_CHECKING++from posthog.schema import SessionTableVersion++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.schema.sessions_v2 import select_from_sessions_table_v2+from posthog.hogql.database.schema.sessions_v3 import select_from_sessions_table_v3+from posthog.hogql.database.schema.util.uuid import uuid_uint128_expr_to_timestamp_expr_v2+from posthog.hogql.database.schema.util.where_clause_extractor import SESSION_BUFFER_DAYS+from posthog.hogql.parser import parse_expr, parse_select++from .marketing_sessions_precompute import MAX_PRECOMPUTED_SESSION_SECONDS, SESSION_READ_REACHBACK_DAYS++if TYPE_CHECKING:+ from posthog.schema import HogQLQueryModifiers+++_DIMENSION_FIELDS = {+ "channel_type": "$channel_type",+ "utm_source": "$entry_utm_source",+ "utm_medium": "$entry_utm_medium",+ "utm_campaign": "$entry_utm_campaign",+ "utm_term": "$entry_utm_term",+ "utm_content": "$entry_utm_content",+ "referring_domain": "$entry_referring_domain",+ "entry_pathname": "$entry_pathname",+}+++def _exceptional_dimensions(+ modifiers: HogQLQueryModifiers, columns: set[str], start: datetime, end: datetime+) -> ast.SelectQuery:+ is_v3 = modifiers.sessionTableVersion == SessionTableVersion.V3+ table = "raw_sessions_v3" if is_v3 else "raw_sessions"+ timestamp = (+ ast.Field(chain=[table, "session_timestamp"])+ if is_v3+ else 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())+ ),+ },+ )+ 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+ source = select_sessions(+ {field: [field] for field in fields}, ast.SelectQuery(select=[ast.Constant(value=1)]), context+ )+ assert isinstance(source, ast.SelectQuery)+ # Filter IDs before merging entry properties; a HAVING alone classifies every session in the range.+ # GLOBAL IN sends the complete set to each shard without depending on session sharding.+ source.where = ast.And(+ exprs=[+ ast.CompareOperation(+ left=ast.Field(chain=[table, "session_id_v7"]), op=ast.CompareOperationOp.GlobalIn, right=candidates+ ),+ ast.CompareOperation(+ left=timestamp,+ op=ast.CompareOperationOp.GtEq,+ right=ast.Constant(value=start - timedelta(days=SESSION_BUFFER_DAYS)),+ ),+ ast.CompareOperation(+ left=timestamp,+ op=ast.CompareOperationOp.LtEq,+ right=ast.Constant(value=end + timedelta(days=SESSION_BUFFER_DAYS)),+ ),+ ]+ )+ 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,+ )+ # Empty slots preserve tuple positions without reading unused entry properties.+ dimensions: list[ast.Expr] = [+ parse_expr("toStartOfHour(toTimeZone($start_timestamp, 'UTC'))"),+ ast.Field(chain=["$start_timestamp"]),+ ]+ for column, field in _DIMENSION_FIELDS.items():+ if column not in columns:+ dimensions.append(ast.Constant(value=""))+ elif column == "channel_type":+ dimensions.append(parse_expr("if(notEmpty(ifNull($channel_type, '')), $channel_type, 'Unknown')"))+ else:+ dimensions.append(+ parse_expr("toString(ifNull({field}, ''))", placeholders={"field": ast.Field(chain=[field])})+ )+ query = parse_select(+ """+ SELECT session_id_v7, {dimensions} AS dimensions, now() AS computed_at, 1 AS source_priority+ FROM {source}+ """,+ placeholders={"source": source, "dimensions": ast.Tuple(exprs=dimensions)},+ )+ assert isinstance(query, ast.SelectQuery)+ return query+++def session_dimensions(+ modifiers: HogQLQueryModifiers, columns: set[str], job_ids: list[str], start: datetime, end: datetime+) -> ast.SelectQuery:+ # A cached session can grow after materialization, so live exceptions must replace its old dimensions.+ query = parse_select(+ """+ SELECT d.session_id_v7,+ argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest,+ max(d.computed_at) AS computed_at+ FROM (+ SELECT session_id_v7,+ {cached_dimensions} AS dimensions,+ computed_at, 0 AS source_priority+ FROM posthog.web_sessions_dimensional_preaggregated+ WHERE job_id IN {jobs}+ UNION ALL+ SELECT * FROM {live}+ ) AS d+ GROUP BY d.session_id_v7+ """,+ placeholders={+ "jobs": ast.Tuple(exprs=[ast.Constant(value=job) for job in job_ids]),+ "cached_dimensions": ast.Tuple(+ exprs=[+ ast.Field(chain=["period_bucket"]),+ ast.Field(chain=["start_timestamp"]),+ *[+ ast.Field(chain=[column]) if column in columns else ast.Constant(value="")+ for column in _DIMENSION_FIELDS+ ],+ ]+ ),+ "live": _exceptional_dimensions(modifiers, columns, start, end),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return querydiff --git a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.pyindex baf24912a53a..072d3e364bc9 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py@@ -13,7 +13,6 @@ from posthog.schema import MarketingAnalyticsAttributionBreakdown, SessionTableVfrom posthog.hogql import astfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_select-from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezonefrom posthog.clickhouse.query_tagging import get_query_tag_value@@ -29,6 +28,7 @@ from products.marketing_analytics.backend.hogql_queries.marketing_sessions_preco)from .attribution_base import MAX_CONVERSIONS_PER_PERSON, MAX_TOUCHPOINTS_PER_PERSON, PERSON_CONVERSION_COUNT+from .attribution_session_dimensions import session_dimensionsfrom .constants import UNKNOWN_CHANNELfrom .marketing_lazy_precompute import (BACKGROUND_WARMING_TRIGGERS,@@ -73,9 +73,8 @@ def _session_table_version(modifiers: "HogQLQueryModifiers") -> SessionTableVersdef _session_modifiers_reason(runner: "AttributionQueryRunnerBase") -> Optional[str]:writer_modifiers = create_default_modifiers_for_team(runner.team)modifiers = runner.modifiers or writer_modifiers- if modifiers.customChannelTypeRules or writer_modifiers.customChannelTypeRules:- # Custom rules can depend on the full URL, which the shared dimensions do not store.- return "custom_channel_rules"+ if (modifiers.customChannelTypeRules or []) != (writer_modifiers.customChannelTypeRules or []):+ return "custom_channel_rules_mismatch"if modifiers.convertToProjectTimezone is False:return "project_timezone_disabled"version = _session_table_version(modifiers)@@ -188,21 +187,6 @@ def _resolve(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -)if not result.job_ids or not result.ready:return None- # Custom session IDs have no maximum duration. Do not silently omit their earlier start chunks.- coverage = execute_hogql_query(- query="SELECT 1 FROM sessions WHERE $start_timestamp < {ensure_start} AND $end_timestamp >= {read_start} LIMIT 1",- team=runner.team,- user=runner.user,- placeholders={- "ensure_start": ast.Constant(value=ensure_start),- "read_start": ast.Constant(value=read.start),- },- modifiers=runner.modifiers,- query_type="marketing_attribution_session_coverage",- context=runner._shared_hogql_context,- )- if coverage.error or coverage.results:- return Noneexcept Exception:logger.exception("attribution_sessions_precompute_failed", team_id=runner.team.pk)return None@@ -211,18 +195,10 @@ def _resolve(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -return [str(j) for j in result.job_ids]-def _read_sessions(job_ids: list[str], start: datetime, end: datetime) -> ast.SelectQuery:+def _read_sessions(dimensions: ast.SelectQuery, start: datetime, end: datetime) -> ast.SelectQuery:query = parse_select("""- WITH dimensions AS (- SELECT session_id_v7,- argMax(tuple(period_bucket, start_timestamp, channel_type, utm_source, utm_medium,- utm_campaign, utm_term, utm_content, referring_domain, entry_pathname, job_id), computed_at) AS latest,- max(computed_at) AS computed_at- FROM posthog.web_sessions_dimensional_preaggregated- WHERE job_id IN {jobs}- GROUP BY session_id_v7- ), identities AS (+ 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,@@ -236,12 +212,12 @@ def _read_sessions(job_ids: list[str], start: datetime, end: datetime) -> ast.Sed.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, d.latest.11 AS job_id, d.computed_at+ d.latest.10 AS entry_pathname, d.computed_atFROM identities AS iINNER JOIN dimensions AS d ON i.session_id_v7 = d.session_id_v7""",placeholders={- "jobs": ast.Tuple(exprs=[ast.Constant(value=j) for j in job_ids]),+ "dimensions": dimensions,"start": ast.Constant(value=start),"end": ast.Constant(value=end),},@@ -250,8 +226,8 @@ def _read_sessions(job_ids: list[str], start: datetime, end: datetime) -> ast.Sereturn query-def _scope(job_ids: list[str], read: ReadWindow) -> list[ast.Expr]:- """Scope to the job set and the window, bounding by event time.+def _scope(read: ReadWindow) -> list[ast.Expr]:+ """Scope to the window by event time; cached dimensions already select the ready job set.The live path keeps a session whose events fall in the window and then reports its start as thetouchpoint time, so a session that opened before the window still counts. Bounding by@@ -259,7 +235,6 @@ def _scope(job_ids: list[str], read: ReadWindow) -> list[ast.Expr]:denominator."""return [- ast.Call(name="in", args=[_field("job_id"), ast.Tuple(exprs=[ast.Constant(value=j) for j in job_ids])]),ast.CompareOperation(left=_field("max_event_timestamp"), op=ast.CompareOperationOp.GtEq, right=ast.Constant(value=read.start)),@@ -356,7 +331,7 @@ def build_reach(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange*_exclusion_columns(runner),],select_from=ast.JoinExpr(table=ast.Field(chain=[_SESSIONS_CTE]), alias="cached_sessions"),- where=ast.And(exprs=_scope(job_ids, read)),+ where=ast.And(exprs=_scope(read)),group_by=[_field("session_id_v7"), _field("person_id")],)exclusions = _exclusions(runner, table_alias="s")@@ -436,11 +411,26 @@ def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRangif job_ids is None:return {}read = window(runner, date_range)+ columns = {BREAKDOWN_COLUMNS[runner.breakdown]}+ if runner.breakdown == MarketingAnalyticsAttributionBreakdown.CAMPAIGN:+ columns.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(job_ids, read.start, read.end),+ 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,),@@ -510,7 +500,7 @@ def build_person_arrays(runner: "AttributionQueryRunnerBase", date_range: QueryD),),),- where=ast.And(exprs=_scope(job_ids, read)),+ where=ast.And(exprs=_scope(read)),group_by=[ast.Field(chain=["conv", "conv_person_id"]), _field("session_id_v7")],)diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.pyindex 259e1373488f..81b22e959bc2 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py@@ -7,7 +7,6 @@ from datetime import datetimefrom posthog.hogql import astfrom posthog.hogql.database.schema.channel_type import expand_default_channel_type_callfrom posthog.hogql.modifiers import create_default_modifiers_for_team-from posthog.hogql.query import execute_hogql_queryfrom posthog.models.team import Teamfrom posthog.schema_enums import SessionTableVersion@@ -43,16 +42,6 @@ SESSION_READ_REACHBACK_DAYS = 1MAX_PRECOMPUTED_SESSION_SECONDS = 3 * 24 * 60 * 60SESSION_SETTLING_PERIOD_SECONDS = MAX_PRECOMPUTED_SESSION_SECONDS-# Keep start predicates unwrapped so the sessions resolver pushes them into raw sessions.-UNSUPPORTED_SESSIONS_QUERY = """-SELECT 1-FROM sessions-WHERE $start_timestamp >= {time_window_min}- AND $start_timestamp < {time_window_max}- AND $end_timestamp > $start_timestamp + toIntervalSecond({max_session_seconds})-LIMIT 1-"""-SESSIONS_INSERT_TEMPLATE = """SELECTtoStartOfHour(toTimeZone(min(events.session.$start_timestamp), 'UTC')) AS period_bucket,@@ -81,7 +70,8 @@ WHERE and(GROUP BY session_id_v7, person_idHAVING and(min(events.session.$start_timestamp) >= {time_window_min},- min(events.session.$start_timestamp) < {time_window_max}+ min(events.session.$start_timestamp) < {time_window_max},+ max(events.session.$end_timestamp) <= min(events.session.$start_timestamp) + toIntervalSecond({max_session_seconds}))"""@@ -125,27 +115,6 @@ def ensure_marketing_sessions_precomputed(if not windows:return LazyComputationResult(ready=True, job_ids=[])- # Check cache hits too: a session can outgrow the scan budget after its window was materialized.- unsupported = execute_hogql_query(- UNSUPPORTED_SESSIONS_QUERY,- team,- modifiers=modifiers,- query_type="marketing_sessions_precompute_coverage",- placeholders={- "time_window_min": ast.Constant(value=windows[0][0]),- "time_window_max": ast.Constant(value=windows[-1][1]),- "max_session_seconds": ast.Constant(value=MAX_PRECOMPUTED_SESSION_SECONDS),- },- )- if unsupported.error:- return LazyComputationResult(ready=False, job_ids=[], errors=["Could not verify session precompute coverage"])- if unsupported.results:- return LazyComputationResult(- ready=False,- job_ids=[],- errors=["Session duration exceeds the precompute scan budget; use live attribution"],- )-return ensure_precomputed(run_inserts=run_inserts,stale_while_revalidate_seconds=stale_while_revalidate_seconds,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 f3df10c5fc92..1d07bf515f19 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@@ -115,6 +115,8 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):"$pathname": "/","$referring_domain": "$direct" if source is None else "www.google.com","utm_campaign": campaign,+ "utm_term": "brand",+ "utm_content": "hero",**({"utm_source": source, "utm_medium": "cpc"} if source else {}),},)@@ -170,6 +172,12 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):[("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN),("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL),+ ("source", MarketingAnalyticsAttributionBreakdown.SOURCE),+ ("medium", MarketingAnalyticsAttributionBreakdown.MEDIUM),+ ("term", MarketingAnalyticsAttributionBreakdown.TERM),+ ("content", MarketingAnalyticsAttributionBreakdown.CONTENT),+ ("referrer", MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN),+ ("landing_page", MarketingAnalyticsAttributionBreakdown.LANDING_PAGE),])def test_session_open_before_the_window_with_events_inside_it_counts_in_both_paths(@@ -179,14 +187,28 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):# touchpoint. Bounding the precomputed read by session start instead dropped this person from# the denominator and moved their first-touch credit.create_person(team=self.team, distinct_ids=["straddler"])+ before_window_minutes = (+ 30+ if breakdown+ in (MarketingAnalyticsAttributionBreakdown.CAMPAIGN, MarketingAnalyticsAttributionBreakdown.CHANNEL)+ else 48 * 60+ )self._session(- "straddler", WINDOW_START - timedelta(minutes=30), campaign="straddle", event_offsets_minutes=[0, 60]+ "straddler",+ WINDOW_START - timedelta(minutes=before_window_minutes),+ campaign="straddle",+ event_offsets_minutes=[0, before_window_minutes + 30],+ source="google",)self._conversion("straddler", datetime(2023, 1, 12, 12, 0, tzinfo=UTC))create_person(team=self.team, distinct_ids=["inside"])self._session(- "inside", datetime(2023, 1, 11, 9, 0, tzinfo=UTC), campaign="inside", event_offsets_minutes=[0, 15]+ "inside",+ datetime(2023, 1, 11, 9, 0, tzinfo=UTC),+ campaign="inside",+ event_offsets_minutes=[0, 15],+ source="google",)self._conversion("inside", datetime(2023, 1, 12, 12, 0, tzinfo=UTC))flush_persons_and_events()@@ -385,20 +407,137 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):assert used, "the precomputed path was not used, so this proves nothing"assert "was_a_campaign" not in rows, f"the superseded campaign survived the exclusion: {rows}"- def test_session_starting_before_reachback_falls_back_without_losing_reach(self) -> None:+ @parameterized.expand(+ [+ (version, before_hours)+ for version in (SessionTableVersion.V2, SessionTableVersion.V3)+ for before_hours in (48, 120)+ ]+ )+ def test_session_starting_before_reachback_preserves_cached_and_live_reach(+ self, version: SessionTableVersion, before_hours: int+ ) -> None:+ self.team.modifiers = {"sessionTableVersion": version}create_person(team=self.team, distinct_ids=["long-session"])self._session(- "long-session", WINDOW_START - timedelta(hours=48), campaign="long", event_offsets_minutes=[0, 49 * 60]+ "long-session",+ WINDOW_START - timedelta(hours=before_hours),+ campaign="long",+ event_offsets_minutes=[0, (before_hours + 1) * 60],)self._conversion("long-session", datetime(2023, 1, 12, 12, tzinfo=UTC))+ create_person(team=self.team, distinct_ids=["short-session"])+ self._session(+ "short-session", datetime(2023, 1, 11, 9, tzinfo=UTC), campaign="short", event_offsets_minutes=[0, 10]+ )+ self._conversion("short-session", datetime(2023, 1, 12, 12, tzinfo=UTC))flush_persons_and_events()live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=False)self._materialize()pre, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)- assert not used- assert live.get("long") == _AttributionCounts(visitors=1, conversions=0)+ assert used+ assert live.get("long") == (_AttributionCounts(visitors=1, conversions=0) if before_hours == 48 else None)+ assert live.get("short") == _AttributionCounts(visitors=1, conversions=1)assert pre == live+ @parameterized.expand([(version,) for version in (SessionTableVersion.V2, SessionTableVersion.V3)])+ def test_custom_channels_match_live_and_rule_changes_invalidate_cache(self, version: SessionTableVersion) -> None:+ self.team.modifiers = {+ "sessionTableVersion": version,+ "customChannelTypeRules": [+ {+ "id": "member-offer",+ "channel_type": "Member offer",+ "combiner": "AND",+ "items": [{"id": "url-rule", "key": "url", "op": "icontains", "value": ["segment=members"]}],+ }+ ],+ }+ for name, duration_days in (("member-a", 0), ("member-b", 5)):+ create_person(team=self.team, distinct_ids=[name])+ opened_at = datetime(2023, 1, 7, 9, tzinfo=UTC)+ session_id_timestamp = opened_at + timedelta(days=duration_days / 2)+ session_id = str(uuid7(session_id_timestamp.strftime("%Y-%m-%dT%H:%M:%SZ")))+ for offset in (0, max(10, duration_days * 1440)):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=name,+ timestamp=opened_at + timedelta(minutes=offset),+ properties={+ "$session_id": session_id,+ "$current_url": "https://example.com/offers?segment=members",+ "utm_source": "partner-network",+ "utm_medium": "referral",+ },+ )+ self._conversion(name, datetime(2023, 1, 10, 12, tzinfo=UTC))+ flush_persons_and_events()+ original_jobs = self._materialize().job_ids+ for channel, ready in (("Member offer", True), ("Member referral", False), ("Member referral", True)):+ self.team.modifiers["customChannelTypeRules"][0]["channel_type"] = channel+ if channel == "Member referral" and ready:+ assert set(self._materialize().job_ids).isdisjoint(original_jobs)+ for query_type, runner_type in (+ (MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),+ (MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),+ ):+ responses = []+ for precomputed in (False, True):+ runner = runner_type(+ query=query_type(+ dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),+ breakdownBy=MarketingAnalyticsAttributionBreakdown.CHANNEL,+ conversionGoalId=GOAL_ID,+ properties=[],+ ),+ team=self.team,+ )+ runner.config.sessions_precomputation_enabled = precomputed+ response = runner.calculate()+ assert runner._sessions_precompute_used is (precomputed and ready)+ assert response.results+ responses.append(response.results)+ if isinstance(response, MarketingAnalyticsAttributionQueryResponse):+ assert response.totalConversions == 2+ assert response.unattributedConversions == 0+ assert {row.breakdownValue for row in response.results} == {channel}+ else:+ assert response.attributedConversions == 2+ self.assertCountEqual(responses[0], responses[1])++ @parameterized.expand([(SessionTableVersion.V2,), (SessionTableVersion.V3,)])+ def test_long_session_growth_replaces_cached_dimensions(self, version: SessionTableVersion) -> None:+ self.team.modifiers = {"sessionTableVersion": version}+ create_person(team=self.team, distinct_ids=["growing-session"])+ session_id = str(uuid7("2023-01-07T09:00:00Z"))+ _create_event(+ team=self.team,+ distinct_id="growing-session",+ event="$pageview",+ timestamp="2023-01-07T09:00:00Z",+ properties={"$session_id": session_id, "$current_url": "https://example.com/"},+ )+ self._conversion("growing-session", datetime(2023, 1, 10, 12, tzinfo=UTC))+ self._materialize()+ _create_event(+ team=self.team,+ distinct_id="growing-session",+ event="$pageview",+ timestamp="2023-01-26T09:00:00Z",+ properties={+ "$session_id": session_id,+ "$current_url": "https://example.com/",+ "utm_campaign": "late-campaign",+ },+ )+ live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=False)+ cached, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)+ assert used+ assert cached == live+ expected_campaign = "late-campaign" if version == SessionTableVersion.V3 else ""+ assert cached == {expected_campaign: _AttributionCounts(visitors=1, conversions=1)}+@time_machine.travel("2026-09-11T12:00:00Z", tick=False)def test_expired_jobs_are_served_with_grace_and_revalidation_rebuilds_them(self) -> None:create_person(team=self.team, distinct_ids=["stale-session"])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 75f260f5e05b..2a6f3019d620 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,5 +1,4 @@from datetime import UTC, datetime-from types import SimpleNamespacefrom uuid import UUIDfrom unittest.mock import PropertyMock, patch@@ -18,6 +17,7 @@ from posthog.schema import ()from posthog.hogql import ast+from posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_selectfrom posthog.clickhouse.query_tagging import Feature, tags_context@@ -47,12 +47,7 @@ class TestAttributionSessionsRead(SimpleTestCase):MarketingAnalyticsAttributionQueryRunner,"_shared_hogql_context",new_callable=PropertyMock,- return_value=None,- )- )- self.coverage = self.enterContext(- patch.object(- attribution_sessions_read, "execute_hogql_query", return_value=SimpleNamespace(results=[], error=None)+ return_value=HogQLContext(team_id=1),))self.enterContext(patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=False))@@ -155,11 +150,6 @@ class TestAttributionSessionsRead(SimpleTestCase):)with (tags_context(trigger=REVALIDATION_TRIGGER if refreshing else "test", feature=Feature.QUERY),- patch.object(- marketing_sessions_precompute,- "execute_hogql_query",- return_value=SimpleNamespace(results=[], error=None),- ),patch.object(marketing_sessions_precompute, "create_default_modifiers_for_team", return_value=runner.modifiers),@@ -180,10 +170,8 @@ class TestAttributionSessionsRead(SimpleTestCase):STALE_WHILE_REVALIDATE_SECONDS if flag and not refreshing else None)assert revalidate.call_count == int(stale)- assert self.coverage.call_count == int(ready)- @parameterized.expand([("older_session", [[1]], None), ("unproven", [], "Coverage query failed")])- def test_unproven_session_coverage_falls_back(self, _name: str, rows: list[list[int]], error: str | None) -> None:+ def test_failed_precompute_lookup_falls_back(self) -> None:runner = MarketingAnalyticsAttributionQueryRunner(team=self.team,modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),@@ -194,12 +182,10 @@ class TestAttributionSessionsRead(SimpleTestCase):dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),),)- self.coverage.return_value.results = rows- self.coverage.return_value.error = errorwith patch.object(attribution_sessions_read,"ensure_marketing_sessions_precomputed",- return_value=LazyComputationResult(ready=True, job_ids=[UUID(int=1)]),+ side_effect=RuntimeError("Precompute lookup failed"),) as ensure:assert attribution_sessions_read.build_person_arrays(runner, runner.query_date_range) is Noneensure.assert_called_once()@@ -217,7 +203,7 @@ class TestAttributionSessionsRead(SimpleTestCase):]),HogQLQueryModifiers(customChannelTypeRules=[]),- "custom_channel_rules",+ "custom_channel_rules_mismatch",),])@@ -240,7 +226,6 @@ class TestAttributionSessionsRead(SimpleTestCase):with patch.object(attribution_sessions_read, "ensure_marketing_sessions_precomputed") as ensure:assert attribution_sessions_read.build_person_arrays(runner, runner.query_date_range) is Noneensure.assert_not_called()- self.coverage.assert_not_called()@parameterized.expand([@@ -314,4 +299,3 @@ class TestAttributionSessionsRead(SimpleTestCase):with patch.object(attribution_sessions_read, "ensure_marketing_sessions_precomputed") as ensure:runner.to_query()ensure.assert_not_called()- self.coverage.assert_not_called()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 a6d8e91150cd..2479ed058cb3 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@@ -1088,8 +1088,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTestdef test_attribution_table_sql(self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown):assert self._printed_sql(breakdown) == self.snapshot- # The precomputed half of each pair must carry neither the channel classifier nor an argMinMerge- # over raw_sessions: resolving those at read time is what exhausts memory on a large team.+ # Entry properties must merge only for exceptional sessions; classifying the full range defeats the cache.@parameterized.expand([("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN),diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.pyindex 3beb52a90723..61dad69deac1 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.py@@ -4,19 +4,15 @@ from datetime import UTC, datetime, timedeltaimport time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events-from unittest.mock import patch--from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.schema import HogQLQueryModifiers, HogQLQueryResponse+from posthog.schema import HogQLQueryModifiersfrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client import sync_execute-from posthog.models import Teamfrom posthog.schema_enums import SessionTableVersionfrom posthog.test.persons import create_personfrom posthog.uuidt import uuid7@@ -97,16 +93,14 @@ class TestMarketingSessionsPrecompute(ClickhouseTestMixin, APIBaseTest):flush_persons_and_events()result = ensure_marketing_sessions_precomputed(self.team, start + timedelta(hours=1), end)- if duration_hours > 72:- assert not result.ready- assert not result.job_ids- return- assert result.ready+ assert result.ready, result.errorsassert sync_execute("SELECT session_id_v7, pageview_count FROM web_sessions_dimensional_preaggregated ""WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s",{"team_id": self.team.pk, "job_ids": result.job_ids},- ) == [(uuid.UUID(session_id).int, 2)]+ ) == ([] if duration_hours > 72 else [(uuid.UUID(session_id).int, 2)])+ if duration_hours > 72:+ returnresponse = execute_hogql_query(SESSIONS_INSERT_TEMPLATE,@@ -143,8 +137,8 @@ class TestMarketingSessionsPrecompute(ClickhouseTestMixin, APIBaseTest):)flush_persons_and_events()cached = ensure_marketing_sessions_precomputed(self.team, start, end, run_inserts=False)- assert not cached.ready- assert not cached.job_ids+ assert cached.ready+ assert set(cached.job_ids) == set(result.job_ids)@parameterized.expand([(SessionTableVersion.V2,), (SessionTableVersion.V3,)])def test_window_refreshes_after_a_long_sessions_first_pageview(self, version: SessionTableVersion) -> None:@@ -189,23 +183,3 @@ class TestMarketingSessionsPrecompute(ClickhouseTestMixin, APIBaseTest):"WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s",{"team_id": self.team.pk, "job_ids": refreshed.job_ids},) == [(uuid.UUID(session_id).int, 1)]---class TestSessionPrecomputeCoverageFailure(SimpleTestCase):- def test_query_error_does_not_prove_session_coverage(self) -> None:- with (- patch(- "products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute.create_default_modifiers_for_team",- return_value=HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2),- ),- patch(- "products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute.execute_hogql_query",- return_value=HogQLQueryResponse(results=[], error="Coverage query failed"),- ),- ):- result = ensure_marketing_sessions_precomputed(- Team(id=1), datetime(2026, 9, 1, tzinfo=UTC), datetime(2026, 9, 2, tzinfo=UTC)- )- self.assertFalse(result.ready)- self.assertEqual(result.job_ids, [])- self.assertEqual(result.errors, ["Could not verify session precompute coverage"])