Skip to content

: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.

feat(marketing-analytics): serve attribution from the session precompute (#91151)

Javier Bahamondesc2b6d80bafda
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.md
new file mode 100644
index 000000000000..04299be56704
--- /dev/null
+++ b/docs/internal/marketing-attribution-session-precompute.md
@@ -0,0 +1,19 @@
+# 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.
+
+`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.
+
+With the existing serve-stale flag, readers may use jobs expired within six hours and enqueue debounced revalidation. Only that task runs reader-initiated inserts; it takes no stale grace. Scheduled writers also require fresh jobs. Classifier expression changes and the explicit dictionary version change the shared job hash, requiring fresh materialization.
+
+The 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.
+
+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.
+
+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.
+This avoids copying timestamp casts into session filters and preserves the shared raw-session timestamp definition.
+If either date boundary falls within a repeated local hour at a daylight saving transition, the reader uses live attribution because conversion filters parse dates without a UTC offset.
+Ranges that cross a transition can still use cached dimensions when both boundaries are unambiguous.
diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambr
index 48957d99cc5a..1d8be2eb21b3 100644
--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambr
+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.ambr
@@ -2,19 +2,19 @@
# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_0_campaign
'''
WITH person_arrays AS (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_25)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_26)s), ''), 'null'), '^"|"$', ''), %(hogql_val_27)s), 0.0)), and(equals(events.event, %(hogql_val_28)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_29)s), %(hogql_val_30)s), toDateTime(%(hogql_val_31)s, %(hogql_val_32)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_33)s), %(hogql_val_34)s), toDateTime(%(hogql_val_35)s, %(hogql_val_36)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_37)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_38)s), %(hogql_val_39)s), toDateTime(%(hogql_val_40)s, %(hogql_val_41)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_42)s), %(hogql_val_43)s), toDateTime(%(hogql_val_44)s, %(hogql_val_45)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), toString(ifNull(events__session.`$entry_utm_campaign`, %(hogql_val_46)s))), and(and(equals(events.event, %(hogql_val_47)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_19)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_20)s), ''), 'null'), '^"|"$', ''), %(hogql_val_21)s), 0.0)), and(equals(events.event, %(hogql_val_22)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_23)s), toDateTime(%(hogql_val_24)s, %(hogql_val_25)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_26)s), toDateTime64(%(hogql_val_27)s, 6, %(hogql_val_28)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_29)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_30)s), toDateTime(%(hogql_val_31)s, %(hogql_val_32)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_33)s), toDateTime64(%(hogql_val_34)s, 6, %(hogql_val_35)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), toString(ifNull(events__session.`$entry_utm_campaign`, %(hogql_val_36)s))), and(and(equals(events.event, %(hogql_val_37)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
FROM events LEFT JOIN (
SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_0)s)) AS `$start_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_1)s), %(hogql_val_2)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), or(and(ifNull(greaterOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_3)s), minus(toDateTime(%(hogql_val_4)s, %(hogql_val_5)s), toIntervalDay(3))), 0), ifNull(lessOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_6)s), plus(toDateTime(%(hogql_val_7)s, %(hogql_val_8)s), toIntervalDay(3))), 0)), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_9)s, %(hogql_val_10)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_11)s, %(hogql_val_12)s), toIntervalDay(3))))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_13)s)), events__session.session_id_v7) LEFT OUTER JOIN (
+ WHERE and(equals(raw_sessions.team_id, 420), or(and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_3)s, %(hogql_val_4)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s), toIntervalDay(3)))), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_7)s, %(hogql_val_8)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_9)s, 6, %(hogql_val_10)s), toIntervalDay(3))))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_11)s)), events__session.session_id_v7) LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
WHERE equals(person_distinct_id_overrides.team_id, 420)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) INNER JOIN (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_14)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_15)s))) AS last_conversion
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_12)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_13)s))) AS last_conversion
FROM events LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
@@ -22,9 +22,9 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_16)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_17)s), %(hogql_val_18)s), toDateTime(%(hogql_val_19)s, %(hogql_val_20)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_21)s), %(hogql_val_22)s), toDateTime(%(hogql_val_23)s, %(hogql_val_24)s)))
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_14)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_15)s, %(hogql_val_16)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_17)s, 6, %(hogql_val_18)s)))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS conv_bounds ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), conv_bounds.person_id)
- WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_48)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_49)s), %(hogql_val_50)s), toDateTime(%(hogql_val_51)s, %(hogql_val_52)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_53)s), %(hogql_val_54)s), toDateTime(%(hogql_val_55)s, %(hogql_val_56)s))), and(equals(events.event, %(hogql_val_57)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_58)s, %(hogql_val_59)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_60)s, %(hogql_val_61)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_62)s)), minus(conv_bounds.first_conversion, 345600)))))
+ WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_38)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_39)s, %(hogql_val_40)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_41)s, 6, %(hogql_val_42)s))), and(equals(events.event, %(hogql_val_43)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_44)s, %(hogql_val_45)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_46)s, 6, %(hogql_val_47)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_48)s)), minus(conv_bounds.first_conversion, 345600)))))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
HAVING greater(length(conversions), 0)), per_conversion_path AS MATERIALIZED (
SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
@@ -45,19 +45,19 @@
# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_1_source
'''
WITH person_arrays AS (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_25)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_26)s), ''), 'null'), '^"|"$', ''), %(hogql_val_27)s), 0.0)), and(equals(events.event, %(hogql_val_28)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_29)s), %(hogql_val_30)s), toDateTime(%(hogql_val_31)s, %(hogql_val_32)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_33)s), %(hogql_val_34)s), toDateTime(%(hogql_val_35)s, %(hogql_val_36)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_37)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_38)s), %(hogql_val_39)s), toDateTime(%(hogql_val_40)s, %(hogql_val_41)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_42)s), %(hogql_val_43)s), toDateTime(%(hogql_val_44)s, %(hogql_val_45)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_46)s)), events__session.`$entry_utm_source`, %(hogql_val_47)s)), [%(hogql_val_48)s, %(hogql_val_49)s, %(hogql_val_50)s]), %(hogql_val_51)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_52)s)), events__session.`$entry_utm_source`, %(hogql_val_53)s)), [%(hogql_val_54)s, %(hogql_val_55)s, %(hogql_val_56)s, %(hogql_val_57)s, %(hogql_val_58)s, %(hogql_val_59)s, %(hogql_val_60)s, %(hogql_val_61)s]), %(hogql_val_62)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_63)s)), events__session.`$entry_utm_source`, %(hogql_val_64)s)), [%(hogql_val_65)s]), %(hogql_val_66)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_67)s)), events__session.`$entry_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]), %(hogql_val_78)s, if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_79)s)), events__session.`$entry_utm_source`, %(hogql_val_80)s)))))), and(and(equals(events.event, %(hogql_val_81)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_19)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_20)s), ''), 'null'), '^"|"$', ''), %(hogql_val_21)s), 0.0)), and(equals(events.event, %(hogql_val_22)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_23)s), toDateTime(%(hogql_val_24)s, %(hogql_val_25)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_26)s), toDateTime64(%(hogql_val_27)s, 6, %(hogql_val_28)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_29)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_30)s), toDateTime(%(hogql_val_31)s, %(hogql_val_32)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_33)s), toDateTime64(%(hogql_val_34)s, 6, %(hogql_val_35)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_36)s)), events__session.`$entry_utm_source`, %(hogql_val_37)s)), [%(hogql_val_38)s, %(hogql_val_39)s, %(hogql_val_40)s]), %(hogql_val_41)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_42)s)), events__session.`$entry_utm_source`, %(hogql_val_43)s)), [%(hogql_val_44)s, %(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, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_53)s)), events__session.`$entry_utm_source`, %(hogql_val_54)s)), [%(hogql_val_55)s]), %(hogql_val_56)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_57)s)), events__session.`$entry_utm_source`, %(hogql_val_58)s)), [%(hogql_val_59)s, %(hogql_val_60)s, %(hogql_val_61)s, %(hogql_val_62)s, %(hogql_val_63)s, %(hogql_val_64)s, %(hogql_val_65)s, %(hogql_val_66)s, %(hogql_val_67)s]), %(hogql_val_68)s, if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_69)s)), events__session.`$entry_utm_source`, %(hogql_val_70)s)))))), and(and(equals(events.event, %(hogql_val_71)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
FROM events LEFT JOIN (
SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_0)s)) AS `$start_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_1)s), %(hogql_val_2)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), or(and(ifNull(greaterOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_3)s), minus(toDateTime(%(hogql_val_4)s, %(hogql_val_5)s), toIntervalDay(3))), 0), ifNull(lessOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_6)s), plus(toDateTime(%(hogql_val_7)s, %(hogql_val_8)s), toIntervalDay(3))), 0)), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_9)s, %(hogql_val_10)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_11)s, %(hogql_val_12)s), toIntervalDay(3))))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_13)s)), events__session.session_id_v7) LEFT OUTER JOIN (
+ WHERE and(equals(raw_sessions.team_id, 420), or(and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_3)s, %(hogql_val_4)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s), toIntervalDay(3)))), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_7)s, %(hogql_val_8)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_9)s, 6, %(hogql_val_10)s), toIntervalDay(3))))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_11)s)), events__session.session_id_v7) LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
WHERE equals(person_distinct_id_overrides.team_id, 420)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) INNER JOIN (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_14)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_15)s))) AS last_conversion
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_12)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_13)s))) AS last_conversion
FROM events LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
@@ -65,9 +65,9 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_16)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_17)s), %(hogql_val_18)s), toDateTime(%(hogql_val_19)s, %(hogql_val_20)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_21)s), %(hogql_val_22)s), toDateTime(%(hogql_val_23)s, %(hogql_val_24)s)))
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_14)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_15)s, %(hogql_val_16)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_17)s, 6, %(hogql_val_18)s)))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS conv_bounds ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), conv_bounds.person_id)
- WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_82)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_83)s), %(hogql_val_84)s), toDateTime(%(hogql_val_85)s, %(hogql_val_86)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_87)s), %(hogql_val_88)s), toDateTime(%(hogql_val_89)s, %(hogql_val_90)s))), and(equals(events.event, %(hogql_val_91)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_92)s, %(hogql_val_93)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_94)s, %(hogql_val_95)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_96)s)), minus(conv_bounds.first_conversion, 345600)))))
+ WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_72)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_73)s, %(hogql_val_74)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_75)s, 6, %(hogql_val_76)s))), and(equals(events.event, %(hogql_val_77)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_78)s, %(hogql_val_79)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_80)s, 6, %(hogql_val_81)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_82)s)), minus(conv_bounds.first_conversion, 345600)))))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
HAVING greater(length(conversions), 0)), per_conversion_path AS MATERIALIZED (
SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
@@ -88,19 +88,19 @@
# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_2_channel
'''
WITH person_arrays AS (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_142)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_143)s), ''), 'null'), '^"|"$', ''), %(hogql_val_144)s), 0.0)), and(equals(events.event, %(hogql_val_145)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_146)s), %(hogql_val_147)s), toDateTime(%(hogql_val_148)s, %(hogql_val_149)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_150)s), %(hogql_val_151)s), toDateTime(%(hogql_val_152)s, %(hogql_val_153)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_154)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_155)s), %(hogql_val_156)s), toDateTime(%(hogql_val_157)s, %(hogql_val_158)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_159)s), %(hogql_val_160)s), toDateTime(%(hogql_val_161)s, %(hogql_val_162)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(notEmpty(ifNull(events__session.`$channel_type`, %(hogql_val_163)s)), events__session.`$channel_type`, %(hogql_val_164)s)), and(and(equals(events.event, %(hogql_val_165)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_136)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_137)s), ''), 'null'), '^"|"$', ''), %(hogql_val_138)s), 0.0)), and(equals(events.event, %(hogql_val_139)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_140)s), toDateTime(%(hogql_val_141)s, %(hogql_val_142)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_143)s), toDateTime64(%(hogql_val_144)s, 6, %(hogql_val_145)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_146)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_147)s), toDateTime(%(hogql_val_148)s, %(hogql_val_149)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_150)s), toDateTime64(%(hogql_val_151)s, 6, %(hogql_val_152)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(notEmpty(ifNull(events__session.`$channel_type`, %(hogql_val_153)s)), events__session.`$channel_type`, %(hogql_val_154)s)), and(and(equals(events.event, %(hogql_val_155)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
FROM events LEFT JOIN (
SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_0)s)) AS `$start_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_1)s), %(hogql_val_2)s), %(hogql_val_3)s), %(hogql_val_4)s)), %(hogql_val_5)s), %(hogql_val_6)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_7)s), %(hogql_val_8)s), %(hogql_val_9)s), %(hogql_val_10)s)), tuple(%(hogql_val_11)s, %(hogql_val_12)s, %(hogql_val_13)s, %(hogql_val_14)s, %(hogql_val_15)s, %(hogql_val_16)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_17)s), %(hogql_val_18)s), %(hogql_val_19)s), %(hogql_val_20)s)), %(hogql_val_21)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_22)s), %(hogql_val_23)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_24)s), %(hogql_val_25)s), %(hogql_val_26)s), %(hogql_val_27)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_28)s), %(hogql_val_29)s), %(hogql_val_30)s), %(hogql_val_31)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_28)s), %(hogql_val_29)s), %(hogql_val_30)s), %(hogql_val_31)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s), %(hogql_val_35)s)), %(hogql_val_36)s), %(hogql_val_37)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_38)s), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_42)s), %(hogql_val_43)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_42)s), %(hogql_val_43)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s), %(hogql_val_47)s), %(hogql_val_48)s), 0), %(hogql_val_49)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_50)s), %(hogql_val_51)s), %(hogql_val_52)s), %(hogql_val_53)s)), %(hogql_val_54)s), %(hogql_val_55)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_56)s), %(hogql_val_57)s)), %(hogql_val_58)s, %(hogql_val_59)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_60)s), %(hogql_val_61)s), %(hogql_val_62)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_63)s), %(hogql_val_64)s), %(hogql_val_65)s), %(hogql_val_66)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_67)s), %(hogql_val_68)s), %(hogql_val_69)s), %(hogql_val_70)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_71)s), %(hogql_val_72)s), %(hogql_val_73)s), %(hogql_val_74)s)), tuple(%(hogql_val_75)s, %(hogql_val_76)s, %(hogql_val_77)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_78)s), %(hogql_val_79)s)))), %(hogql_val_80)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_81)s), %(hogql_val_82)s), %(hogql_val_83)s), %(hogql_val_84)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_81)s), %(hogql_val_82)s), %(hogql_val_83)s), %(hogql_val_84)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_85)s), %(hogql_val_86)s), %(hogql_val_87)s), %(hogql_val_88)s)), %(hogql_val_89)s), %(hogql_val_90)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_91)s), %(hogql_val_92)s), %(hogql_val_93)s), %(hogql_val_94)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_95)s), %(hogql_val_96)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_95)s), %(hogql_val_96)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s), %(hogql_val_100)s)), %(hogql_val_101)s), %(hogql_val_102)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_103)s), %(hogql_val_104)s), %(hogql_val_105)s), %(hogql_val_106)s)), %(hogql_val_107)s), %(hogql_val_108)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_109)s), %(hogql_val_110)s)), %(hogql_val_111)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_112)s), %(hogql_val_113)s), %(hogql_val_114)s), 0), %(hogql_val_115)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_116)s), %(hogql_val_117)s)), %(hogql_val_118)s, %(hogql_val_119)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7
FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), or(and(ifNull(greaterOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_120)s), minus(toDateTime(%(hogql_val_121)s, %(hogql_val_122)s), toIntervalDay(3))), 0), ifNull(lessOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_123)s), plus(toDateTime(%(hogql_val_124)s, %(hogql_val_125)s), toIntervalDay(3))), 0)), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_126)s, %(hogql_val_127)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_128)s, %(hogql_val_129)s), toIntervalDay(3))))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_130)s)), events__session.session_id_v7) LEFT OUTER JOIN (
+ WHERE and(equals(raw_sessions.team_id, 420), or(and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_120)s, %(hogql_val_121)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_122)s, 6, %(hogql_val_123)s), toIntervalDay(3)))), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_124)s, %(hogql_val_125)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_126)s, 6, %(hogql_val_127)s), toIntervalDay(3))))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_128)s)), events__session.session_id_v7) LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
WHERE equals(person_distinct_id_overrides.team_id, 420)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) INNER JOIN (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_131)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_132)s))) AS last_conversion
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_129)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_130)s))) AS last_conversion
FROM events LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
@@ -108,9 +108,9 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_133)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_134)s), %(hogql_val_135)s), toDateTime(%(hogql_val_136)s, %(hogql_val_137)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_138)s), %(hogql_val_139)s), toDateTime(%(hogql_val_140)s, %(hogql_val_141)s)))
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_131)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_132)s, %(hogql_val_133)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_134)s, 6, %(hogql_val_135)s)))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS conv_bounds ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), conv_bounds.person_id)
- WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_166)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_167)s), %(hogql_val_168)s), toDateTime(%(hogql_val_169)s, %(hogql_val_170)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_171)s), %(hogql_val_172)s), toDateTime(%(hogql_val_173)s, %(hogql_val_174)s))), and(equals(events.event, %(hogql_val_175)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_176)s, %(hogql_val_177)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_178)s, %(hogql_val_179)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_180)s)), minus(conv_bounds.first_conversion, 345600)))))
+ WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_156)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_157)s, %(hogql_val_158)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_159)s, 6, %(hogql_val_160)s))), and(equals(events.event, %(hogql_val_161)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_162)s, %(hogql_val_163)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_164)s, 6, %(hogql_val_165)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_166)s)), minus(conv_bounds.first_conversion, 345600)))))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
HAVING greater(length(conversions), 0)), per_conversion_path AS MATERIALIZED (
SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
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.ambr
index 2496b71e17d1..8f1e15a7d8b0 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
@@ -12,23 +12,23 @@
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) LEFT JOIN (
SELECT nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_0)s), %(hogql_val_1)s) AS `$entry_utm_campaign`, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_2)s)) AS `$start_timestamp`, 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)), minus(minus(toDateTime(%(hogql_val_3)s, %(hogql_val_4)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_5)s, %(hogql_val_6)s), toIntervalDay(3))))
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_3)s, %(hogql_val_4)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s), toIntervalDay(3))))
GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)
- WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_9)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_10)s, %(hogql_val_11)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_12)s, %(hogql_val_13)s)))
+ WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_9)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_10)s, %(hogql_val_11)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_12)s, 6, %(hogql_val_13)s)))
GROUP BY breakdown_value), person_arrays AS (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_39)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_40)s), ''), 'null'), '^"|"$', ''), %(hogql_val_41)s), 0.0)), and(equals(events.event, %(hogql_val_42)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_43)s), %(hogql_val_44)s), toDateTime(%(hogql_val_45)s, %(hogql_val_46)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_47)s), %(hogql_val_48)s), toDateTime(%(hogql_val_49)s, %(hogql_val_50)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_51)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_52)s), %(hogql_val_53)s), toDateTime(%(hogql_val_54)s, %(hogql_val_55)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_56)s), %(hogql_val_57)s), toDateTime(%(hogql_val_58)s, %(hogql_val_59)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), toString(ifNull(events__session.`$entry_utm_campaign`, %(hogql_val_60)s))), and(and(equals(events.event, %(hogql_val_61)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_33)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_34)s), ''), 'null'), '^"|"$', ''), %(hogql_val_35)s), 0.0)), and(equals(events.event, %(hogql_val_36)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_37)s), toDateTime(%(hogql_val_38)s, %(hogql_val_39)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_40)s), toDateTime64(%(hogql_val_41)s, 6, %(hogql_val_42)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_43)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_44)s), toDateTime(%(hogql_val_45)s, %(hogql_val_46)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_47)s), toDateTime64(%(hogql_val_48)s, 6, %(hogql_val_49)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), toString(ifNull(events__session.`$entry_utm_campaign`, %(hogql_val_50)s))), and(and(equals(events.event, %(hogql_val_51)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
FROM events LEFT JOIN (
SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_15)s), %(hogql_val_16)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), or(and(ifNull(greaterOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_17)s), minus(toDateTime(%(hogql_val_18)s, %(hogql_val_19)s), toIntervalDay(3))), 0), ifNull(lessOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_20)s), plus(toDateTime(%(hogql_val_21)s, %(hogql_val_22)s), toIntervalDay(3))), 0)), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_23)s, %(hogql_val_24)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_25)s, %(hogql_val_26)s), toIntervalDay(3))))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_27)s)), events__session.session_id_v7) LEFT OUTER JOIN (
+ WHERE and(equals(raw_sessions.team_id, 420), or(and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_17)s, %(hogql_val_18)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_19)s, 6, %(hogql_val_20)s), toIntervalDay(3)))), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_21)s, %(hogql_val_22)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_23)s, 6, %(hogql_val_24)s), toIntervalDay(3))))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_25)s)), events__session.session_id_v7) LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
WHERE equals(person_distinct_id_overrides.team_id, 420)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) INNER JOIN (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_28)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_29)s))) AS last_conversion
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_26)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_27)s))) AS last_conversion
FROM events LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
@@ -36,12 +36,12 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_30)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_31)s), %(hogql_val_32)s), toDateTime(%(hogql_val_33)s, %(hogql_val_34)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_35)s), %(hogql_val_36)s), toDateTime(%(hogql_val_37)s, %(hogql_val_38)s)))
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_28)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_29)s, %(hogql_val_30)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_31)s, 6, %(hogql_val_32)s)))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS conv_bounds ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), conv_bounds.person_id)
- WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_62)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_63)s), %(hogql_val_64)s), toDateTime(%(hogql_val_65)s, %(hogql_val_66)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_67)s), %(hogql_val_68)s), toDateTime(%(hogql_val_69)s, %(hogql_val_70)s))), and(equals(events.event, %(hogql_val_71)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_72)s, %(hogql_val_73)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_74)s, %(hogql_val_75)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_76)s)), minus(conv_bounds.first_conversion, 345600)))))
+ WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_52)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_53)s, %(hogql_val_54)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_55)s, 6, %(hogql_val_56)s))), and(equals(events.event, %(hogql_val_57)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_58)s, %(hogql_val_59)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_60)s, 6, %(hogql_val_61)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_62)s)), minus(conv_bounds.first_conversion, 345600)))))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
HAVING greater(length(conversions), 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_77)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_78)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_79)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_63)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_64)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_65)s), 2.0), 1.0)))), touch_ts)))))) AS w_position
FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (
SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position
FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (
@@ -51,7 +51,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_value
FROM per_conversion_dim
GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (
- SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_80)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_66)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key
FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (
SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key
FROM per_conversion)
@@ -75,23 +75,23 @@
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) LEFT JOIN (
SELECT nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_0)s), %(hogql_val_1)s) AS `$entry_utm_source`, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_2)s)) AS `$start_timestamp`, 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)), minus(minus(toDateTime(%(hogql_val_3)s, %(hogql_val_4)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_5)s, %(hogql_val_6)s), toIntervalDay(3))))
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_3)s, %(hogql_val_4)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s), toIntervalDay(3))))
GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)
- WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_43)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_44)s, %(hogql_val_45)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_46)s, %(hogql_val_47)s)))
+ WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_43)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_44)s, %(hogql_val_45)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_46)s, 6, %(hogql_val_47)s)))
GROUP BY breakdown_value), person_arrays AS (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_73)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_74)s), ''), 'null'), '^"|"$', ''), %(hogql_val_75)s), 0.0)), and(equals(events.event, %(hogql_val_76)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_77)s), %(hogql_val_78)s), toDateTime(%(hogql_val_79)s, %(hogql_val_80)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_81)s), %(hogql_val_82)s), toDateTime(%(hogql_val_83)s, %(hogql_val_84)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_85)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_86)s), %(hogql_val_87)s), toDateTime(%(hogql_val_88)s, %(hogql_val_89)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_90)s), %(hogql_val_91)s), toDateTime(%(hogql_val_92)s, %(hogql_val_93)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_94)s)), events__session.`$entry_utm_source`, %(hogql_val_95)s)), [%(hogql_val_96)s, %(hogql_val_97)s, %(hogql_val_98)s]), %(hogql_val_99)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_100)s)), events__session.`$entry_utm_source`, %(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(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_111)s)), events__session.`$entry_utm_source`, %(hogql_val_112)s)), [%(hogql_val_113)s]), %(hogql_val_114)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_115)s)), events__session.`$entry_utm_source`, %(hogql_val_116)s)), [%(hogql_val_117)s, %(hogql_val_118)s, %(hogql_val_119)s, %(hogql_val_120)s, %(hogql_val_121)s, %(hogql_val_122)s, %(hogql_val_123)s, %(hogql_val_124)s, %(hogql_val_125)s]), %(hogql_val_126)s, if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_127)s)), events__session.`$entry_utm_source`, %(hogql_val_128)s)))))), and(and(equals(events.event, %(hogql_val_129)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_67)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_68)s), ''), 'null'), '^"|"$', ''), %(hogql_val_69)s), 0.0)), and(equals(events.event, %(hogql_val_70)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_71)s), toDateTime(%(hogql_val_72)s, %(hogql_val_73)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_74)s), toDateTime64(%(hogql_val_75)s, 6, %(hogql_val_76)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_77)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_78)s), toDateTime(%(hogql_val_79)s, %(hogql_val_80)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_81)s), toDateTime64(%(hogql_val_82)s, 6, %(hogql_val_83)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_84)s)), events__session.`$entry_utm_source`, %(hogql_val_85)s)), [%(hogql_val_86)s, %(hogql_val_87)s, %(hogql_val_88)s]), %(hogql_val_89)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_90)s)), events__session.`$entry_utm_source`, %(hogql_val_91)s)), [%(hogql_val_92)s, %(hogql_val_93)s, %(hogql_val_94)s, %(hogql_val_95)s, %(hogql_val_96)s, %(hogql_val_97)s, %(hogql_val_98)s, %(hogql_val_99)s]), %(hogql_val_100)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_101)s)), events__session.`$entry_utm_source`, %(hogql_val_102)s)), [%(hogql_val_103)s]), %(hogql_val_104)s, if(in(lower(if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_105)s)), events__session.`$entry_utm_source`, %(hogql_val_106)s)), [%(hogql_val_107)s, %(hogql_val_108)s, %(hogql_val_109)s, %(hogql_val_110)s, %(hogql_val_111)s, %(hogql_val_112)s, %(hogql_val_113)s, %(hogql_val_114)s, %(hogql_val_115)s]), %(hogql_val_116)s, if(notEmpty(ifNull(events__session.`$entry_utm_source`, %(hogql_val_117)s)), events__session.`$entry_utm_source`, %(hogql_val_118)s)))))), and(and(equals(events.event, %(hogql_val_119)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
FROM events LEFT JOIN (
SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_48)s)) AS `$start_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_49)s), %(hogql_val_50)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), or(and(ifNull(greaterOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_51)s), minus(toDateTime(%(hogql_val_52)s, %(hogql_val_53)s), toIntervalDay(3))), 0), ifNull(lessOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_54)s), plus(toDateTime(%(hogql_val_55)s, %(hogql_val_56)s), toIntervalDay(3))), 0)), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_57)s, %(hogql_val_58)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_59)s, %(hogql_val_60)s), toIntervalDay(3))))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_61)s)), events__session.session_id_v7) LEFT OUTER JOIN (
+ WHERE and(equals(raw_sessions.team_id, 420), or(and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_51)s, %(hogql_val_52)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_53)s, 6, %(hogql_val_54)s), toIntervalDay(3)))), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_55)s, %(hogql_val_56)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_57)s, 6, %(hogql_val_58)s), toIntervalDay(3))))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_59)s)), events__session.session_id_v7) LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
WHERE equals(person_distinct_id_overrides.team_id, 420)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) INNER JOIN (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_62)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_63)s))) AS last_conversion
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_60)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_61)s))) AS last_conversion
FROM events LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
@@ -99,12 +99,12 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_64)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_65)s), %(hogql_val_66)s), toDateTime(%(hogql_val_67)s, %(hogql_val_68)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_69)s), %(hogql_val_70)s), toDateTime(%(hogql_val_71)s, %(hogql_val_72)s)))
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_62)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_63)s, %(hogql_val_64)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_65)s, 6, %(hogql_val_66)s)))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS conv_bounds ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), conv_bounds.person_id)
- WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_130)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_131)s), %(hogql_val_132)s), toDateTime(%(hogql_val_133)s, %(hogql_val_134)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_135)s), %(hogql_val_136)s), toDateTime(%(hogql_val_137)s, %(hogql_val_138)s))), and(equals(events.event, %(hogql_val_139)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_140)s, %(hogql_val_141)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_142)s, %(hogql_val_143)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_144)s)), minus(conv_bounds.first_conversion, 345600)))))
+ WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_120)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_121)s, %(hogql_val_122)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_123)s, 6, %(hogql_val_124)s))), and(equals(events.event, %(hogql_val_125)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_126)s, %(hogql_val_127)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_128)s, 6, %(hogql_val_129)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_130)s)), minus(conv_bounds.first_conversion, 345600)))))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
HAVING greater(length(conversions), 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_145)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_146)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_147)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_131)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_132)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_133)s), 2.0), 1.0)))), touch_ts)))))) AS w_position
FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (
SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position
FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (
@@ -114,7 +114,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_value
FROM per_conversion_dim
GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (
- SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_148)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_134)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key
FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (
SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key
FROM per_conversion)
@@ -138,23 +138,23 @@
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) LEFT JOIN (
SELECT multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_0)s), %(hogql_val_1)s), %(hogql_val_2)s), %(hogql_val_3)s)), %(hogql_val_4)s), %(hogql_val_5)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_6)s), %(hogql_val_7)s), %(hogql_val_8)s), %(hogql_val_9)s)), tuple(%(hogql_val_10)s, %(hogql_val_11)s, %(hogql_val_12)s, %(hogql_val_13)s, %(hogql_val_14)s, %(hogql_val_15)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_16)s), %(hogql_val_17)s), %(hogql_val_18)s), %(hogql_val_19)s)), %(hogql_val_20)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_21)s), %(hogql_val_22)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_23)s), %(hogql_val_24)s), %(hogql_val_25)s), %(hogql_val_26)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_27)s), %(hogql_val_28)s), %(hogql_val_29)s), %(hogql_val_30)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_27)s), %(hogql_val_28)s), %(hogql_val_29)s), %(hogql_val_30)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_31)s), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s)), %(hogql_val_35)s), %(hogql_val_36)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_37)s), %(hogql_val_38)s), %(hogql_val_39)s), %(hogql_val_40)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_41)s), %(hogql_val_42)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_41)s), %(hogql_val_42)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s), %(hogql_val_47)s), 0), %(hogql_val_48)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_49)s), %(hogql_val_50)s), %(hogql_val_51)s), %(hogql_val_52)s)), %(hogql_val_53)s), %(hogql_val_54)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_55)s), %(hogql_val_56)s)), %(hogql_val_57)s, %(hogql_val_58)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_59)s), %(hogql_val_60)s), %(hogql_val_61)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_62)s), %(hogql_val_63)s), %(hogql_val_64)s), %(hogql_val_65)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_66)s), %(hogql_val_67)s), %(hogql_val_68)s), %(hogql_val_69)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_70)s), %(hogql_val_71)s), %(hogql_val_72)s), %(hogql_val_73)s)), tuple(%(hogql_val_74)s, %(hogql_val_75)s, %(hogql_val_76)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_77)s), %(hogql_val_78)s)))), %(hogql_val_79)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_80)s), %(hogql_val_81)s), %(hogql_val_82)s), %(hogql_val_83)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_80)s), %(hogql_val_81)s), %(hogql_val_82)s), %(hogql_val_83)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_84)s), %(hogql_val_85)s), %(hogql_val_86)s), %(hogql_val_87)s)), %(hogql_val_88)s), %(hogql_val_89)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_90)s), %(hogql_val_91)s), %(hogql_val_92)s), %(hogql_val_93)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_94)s), %(hogql_val_95)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_94)s), %(hogql_val_95)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), %(hogql_val_100)s), %(hogql_val_101)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_102)s), %(hogql_val_103)s), %(hogql_val_104)s), %(hogql_val_105)s)), %(hogql_val_106)s), %(hogql_val_107)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_108)s), %(hogql_val_109)s)), %(hogql_val_110)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_111)s), %(hogql_val_112)s), %(hogql_val_113)s), 0), %(hogql_val_114)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_115)s), %(hogql_val_116)s)), %(hogql_val_117)s, %(hogql_val_118)s))) AS `$channel_type`, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_119)s)) AS `$start_timestamp`, 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)), minus(minus(toDateTime(%(hogql_val_120)s, %(hogql_val_121)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_122)s, %(hogql_val_123)s), toIntervalDay(3))))
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_120)s, %(hogql_val_121)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_122)s, 6, %(hogql_val_123)s), toIntervalDay(3))))
GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_124)s)), events__session.session_id_v7)
- WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_127)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_128)s, %(hogql_val_129)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_130)s, %(hogql_val_131)s)))
+ WHERE and(equals(events.team_id, 420), and(equals(events.event, %(hogql_val_127)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_128)s, %(hogql_val_129)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_130)s, 6, %(hogql_val_131)s)))
GROUP BY breakdown_value), person_arrays AS (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_274)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_275)s), ''), 'null'), '^"|"$', ''), %(hogql_val_276)s), 0.0)), and(equals(events.event, %(hogql_val_277)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_278)s), %(hogql_val_279)s), toDateTime(%(hogql_val_280)s, %(hogql_val_281)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_282)s), %(hogql_val_283)s), toDateTime(%(hogql_val_284)s, %(hogql_val_285)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_286)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_287)s), %(hogql_val_288)s), toDateTime(%(hogql_val_289)s, %(hogql_val_290)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_291)s), %(hogql_val_292)s), toDateTime(%(hogql_val_293)s, %(hogql_val_294)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(notEmpty(ifNull(events__session.`$channel_type`, %(hogql_val_295)s)), events__session.`$channel_type`, %(hogql_val_296)s)), and(and(equals(events.event, %(hogql_val_297)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, arraySlice(arraySort(groupArrayIf(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_268)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_269)s), ''), 'null'), '^"|"$', ''), %(hogql_val_270)s), 0.0)), and(equals(events.event, %(hogql_val_271)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_272)s), toDateTime(%(hogql_val_273)s, %(hogql_val_274)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_275)s), toDateTime64(%(hogql_val_276)s, 6, %(hogql_val_277)s))))), -500) AS conversions, countIf(and(equals(events.event, %(hogql_val_278)s), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_279)s), toDateTime(%(hogql_val_280)s, %(hogql_val_281)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_282)s), toDateTime64(%(hogql_val_283)s, 6, %(hogql_val_284)s)))) AS conversion_count, arraySlice(arraySort(groupUniqArrayIf(tuple(toUnixTimestamp(events__session.`$start_timestamp`), if(notEmpty(ifNull(events__session.`$channel_type`, %(hogql_val_285)s)), events__session.`$channel_type`, %(hogql_val_286)s)), and(and(equals(events.event, %(hogql_val_287)s), notEmpty(events.`$session_id`), greater(toUnixTimestamp(events__session.`$start_timestamp`), 0)), greaterOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), minus(conv_bounds.first_conversion, 345600)), lessOrEquals(toUnixTimestamp(events__session.`$start_timestamp`), conv_bounds.last_conversion)))), -500) AS touchpoints
FROM events LEFT JOIN (
SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_132)s)) AS `$start_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_133)s), %(hogql_val_134)s), %(hogql_val_135)s), %(hogql_val_136)s)), %(hogql_val_137)s), %(hogql_val_138)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_139)s), %(hogql_val_140)s), %(hogql_val_141)s), %(hogql_val_142)s)), tuple(%(hogql_val_143)s, %(hogql_val_144)s, %(hogql_val_145)s, %(hogql_val_146)s, %(hogql_val_147)s, %(hogql_val_148)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_149)s), %(hogql_val_150)s), %(hogql_val_151)s), %(hogql_val_152)s)), %(hogql_val_153)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_154)s), %(hogql_val_155)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_156)s), %(hogql_val_157)s), %(hogql_val_158)s), %(hogql_val_159)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_160)s), %(hogql_val_161)s), %(hogql_val_162)s), %(hogql_val_163)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_160)s), %(hogql_val_161)s), %(hogql_val_162)s), %(hogql_val_163)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_164)s), %(hogql_val_165)s), %(hogql_val_166)s), %(hogql_val_167)s)), %(hogql_val_168)s), %(hogql_val_169)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_170)s), %(hogql_val_171)s), %(hogql_val_172)s), %(hogql_val_173)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_174)s), %(hogql_val_175)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_174)s), %(hogql_val_175)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_176)s), %(hogql_val_177)s), %(hogql_val_178)s), %(hogql_val_179)s), %(hogql_val_180)s), 0), %(hogql_val_181)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_182)s), %(hogql_val_183)s), %(hogql_val_184)s), %(hogql_val_185)s)), %(hogql_val_186)s), %(hogql_val_187)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_188)s), %(hogql_val_189)s)), %(hogql_val_190)s, %(hogql_val_191)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_192)s), %(hogql_val_193)s), %(hogql_val_194)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_195)s), %(hogql_val_196)s), %(hogql_val_197)s), %(hogql_val_198)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_199)s), %(hogql_val_200)s), %(hogql_val_201)s), %(hogql_val_202)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_203)s), %(hogql_val_204)s), %(hogql_val_205)s), %(hogql_val_206)s)), tuple(%(hogql_val_207)s, %(hogql_val_208)s, %(hogql_val_209)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_210)s), %(hogql_val_211)s)))), %(hogql_val_212)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_213)s), %(hogql_val_214)s), %(hogql_val_215)s), %(hogql_val_216)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_213)s), %(hogql_val_214)s), %(hogql_val_215)s), %(hogql_val_216)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_217)s), %(hogql_val_218)s), %(hogql_val_219)s), %(hogql_val_220)s)), %(hogql_val_221)s), %(hogql_val_222)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_223)s), %(hogql_val_224)s), %(hogql_val_225)s), %(hogql_val_226)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_227)s), %(hogql_val_228)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_227)s), %(hogql_val_228)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_229)s), %(hogql_val_230)s), %(hogql_val_231)s), %(hogql_val_232)s)), %(hogql_val_233)s), %(hogql_val_234)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_235)s), %(hogql_val_236)s), %(hogql_val_237)s), %(hogql_val_238)s)), %(hogql_val_239)s), %(hogql_val_240)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_241)s), %(hogql_val_242)s)), %(hogql_val_243)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_244)s), %(hogql_val_245)s), %(hogql_val_246)s), 0), %(hogql_val_247)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_248)s), %(hogql_val_249)s)), %(hogql_val_250)s, %(hogql_val_251)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7
FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), or(and(ifNull(greaterOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_252)s), minus(toDateTime(%(hogql_val_253)s, %(hogql_val_254)s), toIntervalDay(3))), 0), ifNull(lessOrEquals(toDateTime(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), %(hogql_val_255)s), plus(toDateTime(%(hogql_val_256)s, %(hogql_val_257)s), toIntervalDay(3))), 0)), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_258)s, %(hogql_val_259)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime(%(hogql_val_260)s, %(hogql_val_261)s), toIntervalDay(3))))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_262)s)), events__session.session_id_v7) LEFT OUTER JOIN (
+ WHERE and(equals(raw_sessions.team_id, 420), or(and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime(%(hogql_val_252)s, %(hogql_val_253)s), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_254)s, 6, %(hogql_val_255)s), toIntervalDay(3)))), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(minus(toDateTime(%(hogql_val_256)s, %(hogql_val_257)s), toIntervalSecond(345600)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64(%(hogql_val_258)s, 6, %(hogql_val_259)s), toIntervalDay(3))))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_260)s)), events__session.session_id_v7) LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
WHERE equals(person_distinct_id_overrides.team_id, 420)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) INNER JOIN (
- SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_263)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_264)s))) AS last_conversion
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_261)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_262)s))) AS last_conversion
FROM events LEFT OUTER JOIN (
SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
FROM person_distinct_id_overrides
@@ -162,12 +162,12 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_265)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_266)s), %(hogql_val_267)s), toDateTime(%(hogql_val_268)s, %(hogql_val_269)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_270)s), %(hogql_val_271)s), toDateTime(%(hogql_val_272)s, %(hogql_val_273)s)))
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_263)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_264)s, %(hogql_val_265)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_266)s, 6, %(hogql_val_267)s)))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS conv_bounds ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), conv_bounds.person_id)
- WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_298)s), greaterOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_299)s), %(hogql_val_300)s), toDateTime(%(hogql_val_301)s, %(hogql_val_302)s)), lessOrEquals(toDateTime(toTimeZone(events.timestamp, %(hogql_val_303)s), %(hogql_val_304)s), toDateTime(%(hogql_val_305)s, %(hogql_val_306)s))), and(equals(events.event, %(hogql_val_307)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_308)s, %(hogql_val_309)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime(%(hogql_val_310)s, %(hogql_val_311)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_312)s)), minus(conv_bounds.first_conversion, 345600)))))
+ WHERE and(equals(events.team_id, 420), or(and(equals(events.event, %(hogql_val_288)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_289)s, %(hogql_val_290)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_291)s, 6, %(hogql_val_292)s))), and(equals(events.event, %(hogql_val_293)s), greaterOrEquals(events.timestamp, minus(toDateTime(%(hogql_val_294)s, %(hogql_val_295)s), toIntervalSecond(345600))), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_296)s, 6, %(hogql_val_297)s)), greaterOrEquals(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_298)s)), minus(conv_bounds.first_conversion, 345600)))))
GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)
HAVING greater(length(conversions), 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_313)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_314)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_315)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_299)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_300)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_301)s), 2.0), 1.0)))), touch_ts)))))) AS w_position
FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (
SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position
FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (
@@ -177,7 +177,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_value
FROM per_conversion_dim
GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (
- SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_316)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_302)s), influenced_reach.breakdown_value) AS breakdown_value, ifNull(influenced_reach.visitors, 0) AS visitors, ifNull(attribution_totals.influenced_conversions, 0) AS influenced_conversions, ifNull(attribution_totals.influenced_value, 0.0) AS influenced_value, ifNull(attribution_totals.w_first_conversions, 0.0) AS w_first_conversions, ifNull(attribution_totals.w_first_value, 0.0) AS w_first_value, ifNull(attribution_totals.w_last_conversions, 0.0) AS w_last_conversions, ifNull(attribution_totals.w_last_value, 0.0) AS w_last_value, ifNull(attribution_totals.w_linear_conversions, 0.0) AS w_linear_conversions, ifNull(attribution_totals.w_linear_value, 0.0) AS w_linear_value, ifNull(attribution_totals.w_decay_conversions, 0.0) AS w_decay_conversions, ifNull(attribution_totals.w_decay_value, 0.0) AS w_decay_value, ifNull(attribution_totals.w_position_conversions, 0.0) AS w_position_conversions, ifNull(attribution_totals.w_position_value, 0.0) AS w_position_value, 1 AS footer_key
FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (
SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key
FROM per_conversion)
@@ -188,3 +188,222 @@
OFFSET 0
'''
# ---
+# 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
+ FROM events LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 420)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_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')))
+ 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
+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_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
+ FROM events LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 420)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_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)))
+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
+ FROM (
+ SELECT cached_sessions.person_id AS person_id, argMax(toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_23)s)), toTimeZone(cached_sessions.computed_at, %(hogql_val_24)s)) AS breakdown_value
+ FROM 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')))
+ GROUP BY cached_sessions.session_id_v7, person_id) AS s
+ GROUP BY s.breakdown_value), person_arrays AS (
+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
+ FROM (
+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
+ FROM cached_session_conversions) AS c LEFT JOIN (
+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
+ FROM (
+ SELECT conv.conv_person_id AS person_id, 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
+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
+ WHERE and(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')))
+ GROUP BY conv.conv_person_id, cached_sessions.session_id_v7) AS d
+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (
+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_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
+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (
+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position
+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (
+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position
+ FROM per_touchpoint
+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (
+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value
+ FROM per_conversion_dim
+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (
+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_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
+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (
+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key
+ FROM per_conversion)
+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key
+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)
+ ORDER BY influenced_conversions DESC, visitors DESC
+ LIMIT 101
+ OFFSET 0
+ SETTINGS load_balancing='in_order'
+ '''
+# ---
+# 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
+ FROM events LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 420)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_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')))
+ 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
+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_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
+ FROM events LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 420)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_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)))
+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
+ FROM (
+ SELECT cached_sessions.person_id AS person_id, 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
+ FROM 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')))
+ GROUP BY cached_sessions.session_id_v7, person_id) AS s
+ GROUP BY s.breakdown_value), person_arrays AS (
+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
+ FROM (
+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
+ FROM cached_session_conversions) AS c LEFT JOIN (
+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
+ FROM (
+ SELECT conv.conv_person_id AS person_id, 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
+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
+ WHERE and(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')))
+ GROUP BY conv.conv_person_id, cached_sessions.session_id_v7) AS d
+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (
+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_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
+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (
+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position
+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (
+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position
+ FROM per_touchpoint
+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (
+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value
+ FROM per_conversion_dim
+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (
+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_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
+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (
+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key
+ FROM per_conversion)
+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key
+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)
+ ORDER BY influenced_conversions DESC, visitors DESC
+ LIMIT 101
+ OFFSET 0
+ SETTINGS load_balancing='in_order'
+ '''
+# ---
+# 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
+ FROM events LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 420)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_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')))
+ 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
+ FROM identities AS i INNER JOIN dimensions AS d ON equals(i.session_id_v7, d.session_id_v7)), cached_session_conversions AS MATERIALIZED (
+ SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS conv_person_id, arraySlice(arraySort(groupArray(tuple(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_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
+ FROM events LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 420)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
+ SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_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)))
+ GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
+ SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
+ FROM (
+ SELECT cached_sessions.person_id AS person_id, 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
+ FROM 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')))
+ GROUP BY cached_sessions.session_id_v7, person_id) AS s
+ GROUP BY s.breakdown_value), person_arrays AS (
+ SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
+ FROM (
+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
+ FROM cached_session_conversions) AS c LEFT JOIN (
+ SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
+ FROM (
+ SELECT conv.conv_person_id AS person_id, 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
+ FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
+ SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
+ FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
+ WHERE and(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')))
+ GROUP BY conv.conv_person_id, cached_sessions.session_id_v7) AS d
+ WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
+ GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
+ WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion AS MATERIALIZED (
+ SELECT person_arrays.person_id AS person_id, i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).1 AS conversion_time, (person_arrays.conversions[i]).2 AS conversion_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, conversion_time), 0), ifNull(greaterOrEquals(t.1, minus(conversion_time, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.1, tps) AS touch_ts, arrayMap(t -> t.2, tps) AS dims, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMin(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMin(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_first, arrayMap(_j -> if(ifNull(equals(_j, indexOf(touch_ts, arrayMax(touch_ts))), isNull(_j) and isNull(indexOf(touch_ts, arrayMax(touch_ts)))), 1.0, 0.0), arrayEnumerate(touch_ts)) AS w_last, arrayMap(_x -> divide(1.0, greatest(accurateCastOrNull(length(touch_ts), %(hogql_val_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
+ FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), per_touchpoint AS (
+ SELECT per_conversion.person_id AS person_id, per_conversion.i AS i, per_conversion.conversion_value AS conversion_value, per_conversion.dims[k] AS breakdown_value, per_conversion.w_first[k] AS w_first, per_conversion.w_last[k] AS w_last, per_conversion.w_linear[k] AS w_linear, per_conversion.w_decay[k] AS w_decay, per_conversion.w_position[k] AS w_position
+ FROM per_conversion ARRAY JOIN arrayEnumerate(per_conversion.touch_ts) AS k), per_conversion_dim AS (
+ SELECT per_touchpoint.breakdown_value AS breakdown_value, per_touchpoint.person_id AS person_id, per_touchpoint.i AS i, any(per_touchpoint.conversion_value) AS conv_value, sum(per_touchpoint.w_first) AS w_first, sum(per_touchpoint.w_last) AS w_last, sum(per_touchpoint.w_linear) AS w_linear, sum(per_touchpoint.w_decay) AS w_decay, sum(per_touchpoint.w_position) AS w_position
+ FROM per_touchpoint
+ GROUP BY per_touchpoint.breakdown_value, per_touchpoint.person_id, per_touchpoint.i), attribution_totals AS (
+ SELECT per_conversion_dim.breakdown_value AS breakdown_value, count() AS influenced_conversions, sum(per_conversion_dim.conv_value) AS influenced_value, sum(per_conversion_dim.w_first) AS w_first_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_first)) AS w_first_value, sum(per_conversion_dim.w_last) AS w_last_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_last)) AS w_last_value, sum(per_conversion_dim.w_linear) AS w_linear_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_linear)) AS w_linear_value, sum(per_conversion_dim.w_decay) AS w_decay_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_decay)) AS w_decay_value, sum(per_conversion_dim.w_position) AS w_position_conversions, sum(multiply(per_conversion_dim.conv_value, per_conversion_dim.w_position)) AS w_position_value
+ FROM per_conversion_dim
+ GROUP BY per_conversion_dim.breakdown_value), attribution_rows AS (
+ SELECT coalesce(nullIf(attribution_totals.breakdown_value, %(hogql_val_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
+ FROM attribution_totals FULL OUTER JOIN influenced_reach ON equals(attribution_totals.breakdown_value, influenced_reach.breakdown_value)), attribution_footer AS (
+ SELECT sumIf(per_conversion.conversion_count, ifNull(equals(per_conversion.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(length(per_conversion.tps), 0), 0)) AS attributed_conversions, 1 AS footer_key
+ FROM per_conversion)
+ SELECT attribution_rows.breakdown_value AS breakdown_value, attribution_rows.visitors AS visitors, attribution_rows.influenced_conversions AS influenced_conversions, attribution_rows.influenced_value AS influenced_value, attribution_rows.w_first_conversions AS w_first_conversions, attribution_rows.w_first_value AS w_first_value, attribution_rows.w_last_conversions AS w_last_conversions, attribution_rows.w_last_value AS w_last_value, attribution_rows.w_linear_conversions AS w_linear_conversions, attribution_rows.w_linear_value AS w_linear_value, attribution_rows.w_decay_conversions AS w_decay_conversions, attribution_rows.w_decay_value AS w_decay_value, attribution_rows.w_position_conversions AS w_position_conversions, attribution_rows.w_position_value AS w_position_value, attribution_footer.total_conversions AS total_conversions, attribution_footer.attributed_conversions AS attributed_conversions, attribution_rows.footer_key AS footer_key
+ FROM attribution_footer LEFT JOIN attribution_rows ON equals(attribution_footer.footer_key, attribution_rows.footer_key)
+ ORDER BY influenced_conversions DESC, visitors DESC
+ LIMIT 101
+ OFFSET 0
+ SETTINGS load_balancing='in_order'
+ '''
+# ---
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
index e41931ff564d..2918f2be1bcd 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_base.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
@@ -165,26 +165,36 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
return self.query.allowMultipleConversionsPerVisitor
return self.goal.math not in [BaseMathType.DAU, "dau"]
- def _lookback_date_conditions(self, date_range: QueryDateRange) -> list[ast.Expr]:
- """Pageview bounds extended back by the attribution window, so touches that predate the
- display range can still be credited for a conversion inside it."""
+ def _event_date_conditions(self, date_range: QueryDateRange, *, lookback_seconds: int = 0) -> list[ast.Expr]:
+ start: ast.Expr = ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_from_str)])
+ if lookback_seconds:
+ start = ast.ArithmeticOperation(
+ left=start,
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Call(name="toIntervalSecond", args=[ast.Constant(value=lookback_seconds)]),
+ )
+ # A cast on the event field propagates to raw sessions, where HogQL treats the timestamp as untyped.
+ # A microsecond-precision end includes the full final second without casting the indexed column.
return [
ast.CompareOperation(
left=ast.Field(chain=["events", "timestamp"]),
op=ast.CompareOperationOp.GtEq,
- right=ast.ArithmeticOperation(
- left=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_from_str)]),
- op=ast.ArithmeticOperationOp.Sub,
- right=ast.Call(name="toIntervalSecond", args=[ast.Constant(value=self.attribution_window_seconds)]),
- ),
+ right=start,
),
ast.CompareOperation(
left=ast.Field(chain=["events", "timestamp"]),
op=ast.CompareOperationOp.LtEq,
- right=ast.Call(name="toDateTime", args=[ast.Constant(value=date_range.date_to_str)]),
+ right=ast.Call(name="toDateTime", args=[ast.Constant(value=f"{date_range.date_to_str}.999999")]),
),
]
+ def _lookback_date_conditions(self, date_range: QueryDateRange) -> list[ast.Expr]:
+ """Pageview bounds extended back by the attribution window, so touches that predate the
+ display range can still be credited for a conversion inside it.
+ The inclusive final second matches the conversion date filters.
+ """
+ return self._event_date_conditions(date_range, lookback_seconds=self.attribution_window_seconds)
+
def _build_converters_select(self, date_range: QueryDateRange, *, with_bounds: bool = False) -> ast.SelectQuery:
"""Persons who converted in the window.
@@ -223,13 +233,25 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
where=ast.And(
exprs=[
self.conversion_condition,
- *self._get_where_conditions(date_range, date_field="events.timestamp"),
+ *self._event_date_conditions(date_range),
*self._test_account_conditions(),
]
),
group_by=[ast.Field(chain=["events", "person_id"])],
)
+ def _person_arrays_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
+ """The credit side, served from the precompute when it can."""
+ if self.config.sessions_precomputation_enabled:
+ from .attribution_sessions_read import build_person_arrays # noqa: PLC0415 (import cycle)
+
+ with self.timings.measure("attribution_sessions_precompute_credit"):
+ precomputed = build_person_arrays(self, date_range)
+ if precomputed is not None:
+ self._sessions_precompute_used = True
+ return precomputed
+ return self._build_person_arrays_select(date_range)
+
def _build_person_arrays_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
"""One row per converting person: its conversions, plus a deduped touchpoint set.
@@ -258,7 +280,7 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
ast.And(
exprs=[
self.conversion_condition,
- *self._get_where_conditions(date_range, date_field="events.timestamp"),
+ *self._event_date_conditions(date_range),
]
),
],
@@ -346,7 +368,7 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
ast.And(
exprs=[
self.conversion_condition,
- *self._get_where_conditions(date_range, date_field="events.timestamp"),
+ *self._event_date_conditions(date_range),
]
)
],
@@ -389,7 +411,7 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
ast.And(
exprs=[
self.conversion_condition,
- *self._get_where_conditions(date_range, date_field="events.timestamp"),
+ *self._event_date_conditions(date_range),
]
),
ast.And(
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py
index 62e74327d03f..a209bb4a99e8 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_paths_query_runner.py
@@ -26,6 +26,7 @@ from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.query import execute_hogql_query
from .attribution_base import PERSON_ARRAYS_CTE, PERSON_CONVERSION_COUNT, AttributionQueryRunnerBase
+from .attribution_sessions_read import session_ctes
from .constants import MARKETING_SPILL_AFTER_BYTES, PAGINATION_EXTRA
# Paths longer than this are grouped on their most recent steps — the same truncation direction as
@@ -262,11 +263,11 @@ class MarketingAnalyticsAttributionPathsQueryRunner(
def to_query(self) -> ast.SelectQuery:
date_range = self.query_date_range
- ctes: dict[str, ast.CTE] = {}
+ ctes: dict[str, ast.CTE] = session_ctes(self, date_range)
with self.timings.measure("attribution_paths_person_arrays_cte"):
ctes[PERSON_ARRAYS_CTE] = ast.CTE(
name=PERSON_ARRAYS_CTE,
- expr=self._build_person_arrays_select(date_range),
+ expr=self._person_arrays_select(date_range),
cte_type="subquery",
)
# Materialized because two CTEs read it, and ClickHouse otherwise re-evaluates a CTE at each
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
new file mode 100644
index 000000000000..baf24912a53a
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
@@ -0,0 +1,599 @@
+"""Read cached session dimensions with the same event identity resolution as live attribution.
+
+Stored person IDs can outlive a merge, so only session dimensions come from the cache.
+"""
+
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING, Optional
+
+import structlog
+
+from posthog.schema import MarketingAnalyticsAttributionBreakdown, SessionTableVersion
+
+from posthog.hogql import ast
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
+
+from posthog.clickhouse.query_tagging import get_query_tag_value
+from posthog.dataclasses import frozen
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+
+from products.access_control.backend.facade.api import team_has_property_access_rules
+from products.analytics_platform.backend.lazy_computation.stale_policy import resolve_stale_while_revalidate_seconds
+from products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute import (
+ SESSION_READ_REACHBACK_DAYS,
+ ensure_marketing_sessions_precomputed,
+ precompute_window_days,
+)
+
+from .attribution_base import MAX_CONVERSIONS_PER_PERSON, MAX_TOUCHPOINTS_PER_PERSON, PERSON_CONVERSION_COUNT
+from .constants import UNKNOWN_CHANNEL
+from .marketing_lazy_precompute import (
+ BACKGROUND_WARMING_TRIGGERS,
+ REVALIDATION_TRIGGER,
+ STALE_WHILE_REVALIDATE_SECONDS,
+ handle_stale_served,
+ serve_stale_enabled,
+)
+from .session_breakdown_base import UNATTRIBUTED_SESSION_VALUES
+
+if TYPE_CHECKING:
+ from posthog.schema import HogQLQueryModifiers
+
+ from .attribution_base import AttributionQueryRunnerBase
+
+logger = structlog.get_logger(__name__)
+
+_SESSIONS_CTE = "resolved_cached_sessions"
+_CONVERSIONS_CTE = "cached_session_conversions"
+
+BREAKDOWN_COLUMNS: dict[MarketingAnalyticsAttributionBreakdown, str] = {
+ MarketingAnalyticsAttributionBreakdown.CHANNEL: "channel_type",
+ MarketingAnalyticsAttributionBreakdown.SOURCE: "utm_source",
+ MarketingAnalyticsAttributionBreakdown.CAMPAIGN: "utm_campaign",
+ MarketingAnalyticsAttributionBreakdown.MEDIUM: "utm_medium",
+ MarketingAnalyticsAttributionBreakdown.CONTENT: "utm_content",
+ MarketingAnalyticsAttributionBreakdown.TERM: "utm_term",
+ MarketingAnalyticsAttributionBreakdown.REFERRING_DOMAIN: "referring_domain",
+ MarketingAnalyticsAttributionBreakdown.LANDING_PAGE: "entry_pathname",
+}
+
+
+def _field(name: str) -> ast.Expr:
+ return ast.Field(chain=[name])
+
+
+def _session_table_version(modifiers: "HogQLQueryModifiers") -> SessionTableVersion:
+ version = modifiers.sessionTableVersion
+ return SessionTableVersion.V2 if version is None or version == SessionTableVersion.AUTO else version
+
+
+def _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.convertToProjectTimezone is False:
+ return "project_timezone_disabled"
+ version = _session_table_version(modifiers)
+ if version == SessionTableVersion.V1 or version != _session_table_version(writer_modifiers):
+ return "session_table_version_mismatch"
+ if version == SessionTableVersion.V2 and modifiers.sessionsV2JoinMode != writer_modifiers.sessionsV2JoinMode:
+ return "session_join_mode_mismatch"
+ return None
+
+
+def ineligible_reason(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[str]:
+ """Why this query cannot read from the precompute, or None if it can.
+
+ A reason string rather than a bool, so the caller can label the fallback counter: these carry very
+ different weight, and an unlabeled counter would blur permanent and transient apart.
+ """
+ if reason := _session_modifiers_reason(runner):
+ return reason
+
+ if not is_integer_timezone(runner.team.timezone):
+ # `period_bucket` is an hourly UTC bucket, so a half-hour-offset team's midnight lands
+ # mid-bucket and moves sessions across each edge.
+ return "non_integer_timezone"
+
+ # Live date filters omit the UTC offset, so repeated local hours can resolve to another instant.
+ if any(
+ bound.replace(fold=0).utcoffset() != bound.replace(fold=1).utcoffset()
+ for bound in (date_range.date_from(), date_range.date_to())
+ ):
+ return "ambiguous_date_boundary"
+
+ if team_has_property_access_rules(team_id=runner.team.id):
+ # The rows are userless and shared, so they cannot honor per-user property restrictions.
+ return "property_access_controlled"
+
+ if runner._test_account_conditions():
+ # Shared dimensions include test traffic; use the live path to apply the full filter semantics.
+ return "test_account_filters"
+
+ read = window(runner, date_range)
+ if (read.end - read.start).total_seconds() > (
+ precompute_window_days(runner.team) - SESSION_READ_REACHBACK_DAYS
+ ) * 86400:
+ return "window_over_max"
+
+ return None
+
+
+@frozen
+class ReadWindow:
+ """The span of session activity a query reads: its display range extended back by the attribution
+ window, in UTC. Bounds include whole seconds to match conversion date filters."""
+
+ start: datetime
+ end: datetime
+
+
+def window(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> ReadWindow:
+ """Converted before subtracting: subtracting from a team-local aware datetime is wall-clock
+ arithmetic, which lands an hour away from the credit side across a DST transition.
+ """
+ return ReadWindow(
+ start=date_range.date_from().astimezone(UTC).replace(microsecond=0)
+ - timedelta(seconds=runner.attribution_window_seconds),
+ end=date_range.date_to().astimezone(UTC).replace(microsecond=999999),
+ )
+
+
+def _ensure(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[list[str]]:
+ """The job set backing this query, or None to fall back. Resolved once and cached on the runner:
+ reach and credit both call this, and a pair served from different sources reports rates above
+ 100%, which is the bug the shared window exists to prevent.
+ """
+ if runner._sessions_precompute_resolved:
+ return runner._sessions_precompute_jobs
+
+ runner._sessions_precompute_jobs = _resolve(runner, date_range)
+ runner._sessions_precompute_resolved = True
+ return runner._sessions_precompute_jobs
+
+
+def _resolve(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[list[str]]:
+ try:
+ # Inside the try: the gates read team configuration and access rules, so a failure there has
+ # to fall back like any other, not surface as a query error.
+ reason = ineligible_reason(runner, date_range)
+ if reason is not None:
+ logger.info("attribution_sessions_precompute_ineligible", team_id=runner.team.pk, reason=reason)
+ return None
+
+ read = window(runner, date_range)
+ # Materialize from a session's length before the window: the writer files a session under the
+ # chunk holding its start, so a session that opened earlier and ran into the window lives in
+ # the preceding chunk. Reading the window alone leaves that row unwritten, and bounding by
+ # event time cannot recover a row that was never built.
+ ensure_start = read.start - timedelta(days=SESSION_READ_REACHBACK_DAYS)
+ revalidating = get_query_tag_value("trigger") == REVALIDATION_TRIGGER
+ grace = (
+ resolve_stale_while_revalidate_seconds(STALE_WHILE_REVALIDATE_SECONDS, BACKGROUND_WARMING_TRIGGERS)
+ if serve_stale_enabled(runner.team)
+ else None
+ )
+ # Only the dedicated revalidation task may rebuild; cold user reads keep the live fallback.
+ result = ensure_marketing_sessions_precomputed(
+ runner.team,
+ ensure_start,
+ read.end,
+ run_inserts=revalidating,
+ stale_while_revalidate_seconds=grace,
+ )
+ 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 None
+ except Exception:
+ logger.exception("attribution_sessions_precompute_failed", team_id=runner.team.pk)
+ return None
+ if result.stale:
+ handle_stale_served(team=runner.team, query=runner.query)
+ return [str(j) for j in result.job_ids]
+
+
+def _read_sessions(job_ids: list[str], 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 (
+ 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,
+ count() AS pageview_count
+ FROM events
+ WHERE events.event = '$pageview'
+ AND events.timestamp >= {start} AND events.timestamp <= {end}
+ GROUP BY session_id_v7, person_id
+ )
+ SELECT i.session_id_v7, i.person_id, i.min_event_timestamp, i.max_event_timestamp, i.pageview_count,
+ d.latest.1 AS period_bucket, d.latest.2 AS start_timestamp, d.latest.3 AS channel_type,
+ d.latest.4 AS utm_source, d.latest.5 AS utm_medium, d.latest.6 AS utm_campaign,
+ 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
+ FROM identities AS i
+ INNER 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]),
+ "start": ast.Constant(value=start),
+ "end": ast.Constant(value=end),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+
+def _scope(job_ids: list[str], read: ReadWindow) -> list[ast.Expr]:
+ """Scope to the job set and the window, bounding by event time.
+
+ The live path keeps a session whose events fall in the window and then reports its start as the
+ touchpoint time, so a session that opened before the window still counts. Bounding by
+ `start_timestamp` dropped exactly those, which moved first-touch credit and shrank the reach
+ 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)
+ ),
+ ast.CompareOperation(
+ left=_field("min_event_timestamp"), op=ast.CompareOperationOp.LtEq, right=ast.Constant(value=read.end)
+ ),
+ ]
+
+
+_EXCLUDED_CHANNEL = "excl_channel_type"
+_EXCLUDED_BREAKDOWN = "excl_breakdown"
+
+
+def _exclusion_columns(runner: "AttributionQueryRunnerBase") -> list[ast.Expr]:
+ """The columns the exclusions read, collapsed per session by `computed_at`.
+
+ A session can hold rows under two job_ids, and a re-materialized row can carry different
+ dimensions. Filtering the raw rows would drop the current version and leave the superseded one
+ standing, so the exclusions have to judge what the collapse decided, not what any row says.
+ """
+ columns: list[ast.Expr] = []
+ if runner.query.excludeDirectTraffic:
+ columns.append(
+ ast.Alias(
+ alias=_EXCLUDED_CHANNEL,
+ expr=ast.Call(name="argMax", args=[_field("channel_type"), _field("computed_at")]),
+ )
+ )
+ if runner.query.excludeUnattributed:
+ columns.append(
+ ast.Alias(
+ alias=_EXCLUDED_BREAKDOWN,
+ expr=ast.Call(name="argMax", args=[_field(BREAKDOWN_COLUMNS[runner.breakdown]), _field("computed_at")]),
+ )
+ )
+ return columns
+
+
+def _exclusions(runner: "AttributionQueryRunnerBase", table_alias: Optional[str] = None) -> list[ast.Expr]:
+ """Mirror of the exclusion half of `_touchpoint_condition`, against the collapsed columns."""
+
+ def resolved(alias: str) -> ast.Field:
+ return ast.Field(chain=[table_alias, alias] if table_alias else [alias])
+
+ conditions: list[ast.Expr] = []
+ if runner.query.excludeDirectTraffic:
+ conditions.append(
+ ast.CompareOperation(
+ left=resolved(_EXCLUDED_CHANNEL),
+ op=ast.CompareOperationOp.NotEq,
+ right=ast.Constant(value="Direct"),
+ )
+ )
+ if runner.query.excludeUnattributed:
+ # Judged on the raw column rather than the display expression, so a friendly fallback label
+ # cannot smuggle an empty value back in.
+ field = resolved(_EXCLUDED_BREAKDOWN)
+ conditions.append(
+ ast.Call(name="notEmpty", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])])
+ )
+ for sentinel in UNATTRIBUTED_SESSION_VALUES.get(runner.breakdown, ()):
+ conditions.append(
+ ast.CompareOperation(left=field, op=ast.CompareOperationOp.NotEq, right=ast.Constant(value=sentinel))
+ )
+ return conditions
+
+
+def _breakdown_expr(runner: "AttributionQueryRunnerBase") -> ast.Expr:
+ column = _field(BREAKDOWN_COLUMNS[runner.breakdown])
+ if runner.breakdown == MarketingAnalyticsAttributionBreakdown.CHANNEL:
+ return runner._non_empty_or(column, UNKNOWN_CHANNEL)
+ if runner.breakdown == MarketingAnalyticsAttributionBreakdown.SOURCE:
+ return runner._normalized_source_expr(column)
+ if runner.breakdown == MarketingAnalyticsAttributionBreakdown.CAMPAIGN:
+ return runner._normalized_campaign_expr(column, source_field=_field("utm_source"))
+ return ast.Call(name="toString", args=[ast.Call(name="ifNull", args=[column, ast.Constant(value="")])])
+
+
+def build_reach(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[ast.SelectQuery]:
+ job_ids = _ensure(runner, date_range)
+ if job_ids is None:
+ return None
+ read = window(runner, date_range)
+ # Collapsed per session first, for the reason in `build_person_arrays`. `uniq` already keeps a
+ # duplicated session from counting its person twice, but two rows can carry different dimensions,
+ # which puts one visitor in two breakdown rows.
+ per_session = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="person_id", expr=_field("person_id")),
+ ast.Alias(
+ alias="breakdown_value",
+ expr=ast.Call(name="argMax", args=[_breakdown_expr(runner), _field("computed_at")]),
+ ),
+ *_exclusion_columns(runner),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[_SESSIONS_CTE]), alias="cached_sessions"),
+ where=ast.And(exprs=_scope(job_ids, read)),
+ group_by=[_field("session_id_v7"), _field("person_id")],
+ )
+ exclusions = _exclusions(runner, table_alias="s")
+ return ast.SelectQuery(
+ select=[
+ ast.Field(chain=["s", "breakdown_value"]),
+ ast.Alias(alias="visitors", expr=ast.Call(name="uniq", args=[ast.Field(chain=["s", "person_id"])])),
+ ],
+ select_from=ast.JoinExpr(table=per_session, alias="s"),
+ where=ast.And(exprs=exclusions) if exclusions else None,
+ group_by=[ast.Field(chain=["s", "breakdown_value"])],
+ )
+
+
+def _conversions_per_person(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> ast.SelectQuery:
+ """Conversions per converting person, straight off events. Conversions are events, not sessions,
+ so this side stays on `events`; what the precompute replaces is the touchpoint side."""
+ conversions: ast.Expr = ast.Call(
+ name="groupArray",
+ args=[
+ ast.Tuple(
+ exprs=[
+ ast.Call(name="toUnixTimestamp", args=[ast.Field(chain=["events", "timestamp"])]),
+ runner._conversion_value_expr(),
+ ]
+ )
+ ],
+ )
+ # Counted before the array is capped: the footer reports "N of M" exactly, so a conversion the cap
+ # drops has to show up as unattributed rather than vanish from M.
+ conversion_count: ast.Expr = ast.Call(name="count", args=[])
+ if not runner.allows_multiple_conversions_per_visitor:
+ conversions = ast.Call(
+ name="arraySlice",
+ args=[ast.Call(name="arraySort", args=[conversions]), ast.Constant(value=1), ast.Constant(value=1)],
+ )
+ conversion_count = ast.Constant(value=1)
+ else:
+ # The same ceiling the live path applies. Without it the two downstream ARRAY JOINs multiply
+ # without bound, which is the shape this precompute exists to keep out of memory.
+ conversions = ast.Call(
+ name="arraySlice",
+ args=[
+ ast.Call(name="arraySort", args=[conversions]),
+ ast.Constant(value=-MAX_CONVERSIONS_PER_PERSON),
+ ],
+ )
+
+ def bound(fn: str) -> ast.Expr:
+ return ast.Call(
+ name=fn, args=[ast.Call(name="toUnixTimestamp", args=[ast.Field(chain=["events", "timestamp"])])]
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias="conv_person_id", expr=ast.Field(chain=["events", "person_id"])),
+ ast.Alias(alias="conversions", expr=conversions),
+ ast.Alias(alias=PERSON_CONVERSION_COUNT, expr=conversion_count),
+ ast.Alias(alias="first_conversion", expr=bound("min")),
+ ast.Alias(alias="last_conversion", expr=bound("max")),
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(
+ exprs=[
+ runner.conversion_condition,
+ *runner._event_date_conditions(date_range),
+ ]
+ ),
+ group_by=[ast.Field(chain=["events", "person_id"])],
+ )
+
+
+def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> dict[str, ast.CTE]:
+ if not runner.config.sessions_precomputation_enabled:
+ return {}
+ job_ids = _ensure(runner, date_range)
+ if job_ids is None:
+ return {}
+ read = window(runner, date_range)
+ # 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),
+ cte_type="subquery",
+ materialized=True,
+ ),
+ _CONVERSIONS_CTE: ast.CTE(
+ name=_CONVERSIONS_CTE,
+ expr=_conversions_per_person(runner, date_range),
+ cte_type="subquery",
+ materialized=True,
+ ),
+ }
+
+
+def build_person_arrays(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[ast.SelectQuery]:
+ """One row per converting person: its conversions, plus its touchpoints read from the precompute.
+
+ Session dimensions stay cached while both touchpoints and conversions resolve identity from events.
+ """
+ job_ids = _ensure(runner, date_range)
+ if job_ids is None:
+ return None
+ read = window(runner, date_range)
+
+ conv = parse_select("SELECT * FROM cached_session_conversions")
+ converters = parse_select(
+ "SELECT conv_person_id, first_conversion, last_conversion FROM cached_session_conversions"
+ )
+ session_start = ast.Call(name="toUnixTimestamp", args=[_field("start_timestamp")])
+ # A touchpoint outside [first conversion - window, last conversion] cannot be credited by any of
+ # this person's conversions. In single-conversion mode only the first one is kept, so nothing
+ # after it is creditable either.
+ upper = "last_conversion" if runner.allows_multiple_conversions_per_visitor else "first_conversion"
+
+ # One row per session before the array is built. A session can hold rows under two job_ids: its
+ # stored start is the earliest event seen so far, and a later event that predates it moves the
+ # start, which files the session under a different chunk while the first chunk's row survives.
+ # Both job_ids are in the read set, so without this collapse one session becomes two touchpoints
+ # and over-credits the person. The sibling conversion precompute deduplicates for the same reason.
+ per_session = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="person_id", expr=ast.Field(chain=["conv", "conv_person_id"])),
+ ast.Alias(alias="session_ts", expr=ast.Call(name="argMax", args=[session_start, _field("computed_at")])),
+ ast.Alias(
+ alias="session_dim",
+ expr=ast.Call(name="argMax", args=[_breakdown_expr(runner), _field("computed_at")]),
+ ),
+ ast.Alias(
+ alias="first_conversion",
+ expr=ast.Call(name="any", args=[ast.Field(chain=["conv", "first_conversion"])]),
+ ),
+ ast.Alias(alias="upper_bound", expr=ast.Call(name="any", args=[ast.Field(chain=["conv", upper])])),
+ *_exclusion_columns(runner),
+ ],
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=[_SESSIONS_CTE]),
+ alias="cached_sessions",
+ next_join=ast.JoinExpr(
+ join_type="INNER JOIN",
+ table=converters,
+ alias="conv",
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(
+ left=_field("person_id"),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=["conv", "conv_person_id"]),
+ ),
+ constraint_type="ON",
+ ),
+ ),
+ ),
+ where=ast.And(exprs=_scope(job_ids, read)),
+ group_by=[ast.Field(chain=["conv", "conv_person_id"]), _field("session_id_v7")],
+ )
+
+ # Creditability is judged on the collapsed start, so a superseded row cannot decide it.
+ touchpoints = ast.SelectQuery(
+ select=[
+ ast.Alias(alias="person_id", expr=ast.Field(chain=["d", "person_id"])),
+ ast.Alias(
+ alias="touchpoints",
+ expr=ast.Call(
+ name="arraySlice",
+ args=[
+ ast.Call(
+ name="arraySort",
+ args=[
+ ast.Call(
+ name="groupUniqArray",
+ args=[
+ ast.Tuple(
+ exprs=[
+ ast.Field(chain=["d", "session_ts"]),
+ ast.Field(chain=["d", "session_dim"]),
+ ]
+ )
+ ],
+ )
+ ],
+ ),
+ ast.Constant(value=-MAX_TOUCHPOINTS_PER_PERSON),
+ ],
+ ),
+ ),
+ ],
+ select_from=ast.JoinExpr(table=per_session, alias="d"),
+ where=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=["d", "session_ts"]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.ArithmeticOperation(
+ left=ast.Field(chain=["d", "first_conversion"]),
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Constant(value=runner.attribution_window_seconds),
+ ),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=["d", "session_ts"]),
+ op=ast.CompareOperationOp.LtEq,
+ right=ast.Field(chain=["d", "upper_bound"]),
+ ),
+ *_exclusions(runner, table_alias="d"),
+ ]
+ ),
+ group_by=[ast.Field(chain=["d", "person_id"])],
+ )
+
+ return ast.SelectQuery(
+ select=[
+ ast.Alias(alias="person_id", expr=ast.Field(chain=["c", "conv_person_id"])),
+ ast.Field(chain=["c", "conversions"]),
+ ast.Field(chain=["c", PERSON_CONVERSION_COUNT]),
+ ast.Alias(alias="touchpoints", expr=ast.Field(chain=["t", "touchpoints"])),
+ ],
+ select_from=ast.JoinExpr(
+ table=conv,
+ alias="c",
+ next_join=ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=touchpoints,
+ alias="t",
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(
+ left=ast.Field(chain=["c", "conv_person_id"]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Field(chain=["t", "person_id"]),
+ ),
+ constraint_type="ON",
+ ),
+ ),
+ ),
+ where=ast.CompareOperation(
+ left=ast.Call(name="length", args=[ast.Field(chain=["c", "conversions"])]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=0),
+ ),
+ )
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
index 5247455023fe..590a32a9362f 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
@@ -35,6 +35,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from .attribution_base import PERSON_ARRAYS_CTE, PERSON_CONVERSION_COUNT, AttributionQueryRunnerBase
+from .attribution_sessions_read import build_reach, session_ctes
from .attribution_weights import (
build_first_touch_weights,
build_last_touch_weights,
@@ -103,6 +104,13 @@ class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[Market
visitors to the display window instead let a conversion be credited to a touch from before the
range while its person was missing from the denominator, reporting rates above 100%.
"""
+ if self.config.sessions_precomputation_enabled:
+ with self.timings.measure("attribution_sessions_precompute"):
+ precomputed = build_reach(self, date_range)
+ if precomputed is not None:
+ self._sessions_precompute_used = True
+ return precomputed
+
breakdown = self._breakdown_expr()
return ast.SelectQuery(
select=[
@@ -284,13 +292,13 @@ class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[Market
def to_query(self) -> ast.SelectQuery:
date_range = self.query_date_range
- ctes: dict[str, ast.CTE] = {}
+ ctes: dict[str, ast.CTE] = session_ctes(self, date_range)
with self.timings.measure("attribution_reach_cte"):
ctes[_REACH_CTE] = ast.CTE(name=_REACH_CTE, expr=self._build_reach_select(date_range), cte_type="subquery")
with self.timings.measure("attribution_person_arrays_cte"):
ctes[PERSON_ARRAYS_CTE] = ast.CTE(
name=PERSON_ARRAYS_CTE,
- expr=self._build_person_arrays_select(date_range),
+ expr=self._person_arrays_select(date_range),
cte_type="subquery",
)
# Materialized because two CTEs read it, and ClickHouse otherwise re-evaluates a CTE at each
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index d426162d8de8..3afe6297b0e7 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -173,6 +173,13 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
self._costs_precompute_used: bool = False
self._costs_sources_materialized: int = 0
self._costs_grain: Optional[str] = None
+ # Without this, a rollout where every query falls back to the live path looks identical to
+ # one that works.
+ self._sessions_precompute_used: bool = False
+ # The job set backing this query, resolved once and shared by the reach and credit sides.
+ # `resolved` separates "not looked up yet" from "looked up, cannot use the precompute".
+ self._sessions_precompute_resolved: bool = False
+ self._sessions_precompute_jobs: list[str] | None = None
# Set when any read-path ensure (costs, touchpoints, conversions) was served from
# expired-within-grace rows rather than rebuilt inline. Reset on each to_query.
self._precompute_stale: bool = False
@@ -221,6 +228,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
"costs_precompute_used": self._costs_precompute_used,
"costs_sources_materialized": self._costs_sources_materialized,
"costs_grain": self._costs_grain,
+ "sessions_precompute_used": self._sessions_precompute_used,
}
if error is None:
props["timings"] = [{"k": t.k, "t": t.t} for t in self.timings.to_list()]
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
index 99edf8addc82..e229a27907c0 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
@@ -108,6 +108,7 @@ class MarketingAnalyticsConfig:
conversion_goal_precomputation_enabled: bool = False
costs_precomputation_enabled: bool = False
+ sessions_precomputation_enabled: bool = False
@staticmethod
def _precompute_flags(team: "Team") -> dict[str, bool]:
@@ -143,6 +144,12 @@ class MarketingAnalyticsConfig:
groups=groups,
group_properties=group_properties,
),
+ "sessions": feature_enabled_or_false(
+ "marketing-analytics-sessions-precomputation",
+ str(team.uuid),
+ groups=groups,
+ group_properties=group_properties,
+ ),
}
team._ma_precompute_flags = flags # type: ignore[attr-defined]
return flags
@@ -179,6 +186,7 @@ class MarketingAnalyticsConfig:
flags = cls._precompute_flags(team)
config.conversion_goal_precomputation_enabled = flags["conversion"]
config.costs_precomputation_enabled = flags["costs"]
+ config.sessions_precomputation_enabled = flags["sessions"]
# Gate multi-touch attribution behind its flag; fall back to last-touch when disabled. Evaluated
# only for multi-touch modes so single-touch never triggers the flag call.
diff --git a/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py b/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py
index b8b600d4b4c7..16f7b136190d 100644
--- a/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py
+++ b/products/marketing_analytics/backend/hogql_queries/session_breakdown_base.py
@@ -88,7 +88,7 @@ class MarketingSessionBreakdownQueryRunnerBase(MarketingAnalyticsBaseQueryRunner
source_mappings,
)
- def _normalized_campaign_expr(self, field: ast.Expr) -> ast.Expr:
+ def _normalized_campaign_expr(self, field: ast.Expr, source_field: ast.Expr | None = None) -> ast.Expr:
"""Collapse the team's dirty utm_campaign spellings onto the clean name they're mapped to.
Without this a campaign whose UTMs vary lands as one row per spelling, and because the models
@@ -101,7 +101,7 @@ class MarketingSessionBreakdownQueryRunnerBase(MarketingAnalyticsBaseQueryRunner
raw_campaign = ast.Call(name="toString", args=[ast.Call(name="ifNull", args=[field, ast.Constant(value="")])])
return build_campaign_display_normalization_expr(
raw_campaign,
- ast.Field(chain=["events", "session", "$entry_utm_source"]),
+ source_field if source_field is not None else ast.Field(chain=["events", "session", "$entry_utm_source"]),
self.team.marketing_analytics_config,
)
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.py
new file mode 100644
index 000000000000..f3df10c5fc92
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py
@@ -0,0 +1,694 @@
+from datetime import UTC, datetime, timedelta
+from typing import Optional
+from uuid import UUID
+
+import time_machine
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ ConversionGoalFilter1,
+ DateRange,
+ HogQLQueryModifiers,
+ MarketingAnalyticsAttributionBreakdown,
+ MarketingAnalyticsAttributionPathsQuery,
+ MarketingAnalyticsAttributionQuery,
+ MarketingAnalyticsAttributionQueryResponse,
+ PersonsOnEventsMode,
+ PropertyMathType,
+ SessionTableVersion,
+)
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import tags_context
+from posthog.dataclasses import frozen
+from posthog.models.utils import uuid7
+from posthog.test.persons import add_distinct_id, create_person
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
+from products.analytics_platform.backend.models import PreaggregationJob
+from products.marketing_analytics.backend.hogql_queries import attribution_sessions_read
+from products.marketing_analytics.backend.hogql_queries.attribution_paths_query_runner import (
+ MarketingAnalyticsAttributionPathsQueryRunner,
+)
+from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
+ MarketingAnalyticsAttributionQueryRunner,
+)
+from products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute import (
+ SESSION_READ_REACHBACK_DAYS,
+ ensure_marketing_sessions_precomputed,
+)
+from products.marketing_analytics.backend.tasks.lazy_precompute_revalidation import (
+ revalidate_marketing_analytics_precompute,
+)
+
+GOAL_ID = "goal-1"
+CONVERSION_EVENT = "purchase"
+WINDOW_DAYS = 4
+
+DATE_FROM = "2023-01-10"
+DATE_TO = "2023-01-20"
+# The read extends the display range back by the attribution window, so this is its lower edge.
+WINDOW_START = datetime(2023, 1, 10, tzinfo=UTC) - timedelta(days=WINDOW_DAYS)
+
+
+@frozen
+class _AttributionCounts:
+ visitors: int
+ conversions: int
+
+
+class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
+ """The precomputed read must agree with the live scan, including at the window edge.
+
+ The generated fixture data elsewhere gives every session a single timestamp, so a session's
+ start and its last event coincide and the two paths cannot disagree. These sessions span real
+ time, which is what makes the bound observable.
+ """
+
+ maxDiff = None
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ config = self.team.marketing_analytics_config
+ config.attribution_window_days = WINDOW_DAYS
+ config.conversion_goals = [
+ ConversionGoalFilter1(
+ kind="EventsNode",
+ event=CONVERSION_EVENT,
+ name="Purchases",
+ conversion_goal_id=GOAL_ID,
+ conversion_goal_name="Purchases",
+ schema_map={},
+ math=PropertyMathType.SUM,
+ math_property="revenue",
+ counts_as_revenue=True,
+ ).model_dump()
+ ]
+ config.save()
+
+ def _session(
+ self,
+ distinct_id: str,
+ opened_at: datetime,
+ *,
+ campaign: str,
+ event_offsets_minutes: list[int],
+ source: Optional[str] = None,
+ ) -> None:
+ """A session opening at `opened_at` with a pageview at each offset after it."""
+ session_id = str(uuid7(opened_at.strftime("%Y-%m-%dT%H:%M:%SZ")))
+ for offset in event_offsets_minutes:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=(opened_at + timedelta(minutes=offset)).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ properties={
+ "$session_id": session_id,
+ "$current_url": "https://example.com/",
+ "$pathname": "/",
+ "$referring_domain": "$direct" if source is None else "www.google.com",
+ "utm_campaign": campaign,
+ **({"utm_source": source, "utm_medium": "cpc"} if source else {}),
+ },
+ )
+
+ def _conversion(self, distinct_id: str, at: datetime) -> None:
+ _create_event(
+ team=self.team,
+ event=CONVERSION_EVENT,
+ distinct_id=distinct_id,
+ timestamp=at.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ properties={"revenue": 100.0},
+ )
+
+ def _run(
+ self,
+ breakdown: MarketingAnalyticsAttributionBreakdown,
+ *,
+ precomputed: bool,
+ exclude_direct: bool = False,
+ allow_multiple_conversions: bool | None = None,
+ modifiers: HogQLQueryModifiers | None = None,
+ ) -> tuple[dict[str, _AttributionCounts], bool]:
+ query = MarketingAnalyticsAttributionQuery(
+ dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ breakdownBy=breakdown,
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ excludeDirectTraffic=exclude_direct,
+ allowMultipleConversionsPerVisitor=allow_multiple_conversions,
+ modifiers=modifiers,
+ )
+ runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)
+ runner.config.sessions_precomputation_enabled = precomputed
+ response = runner.calculate()
+ rows = {
+ row.breakdownValue: _AttributionCounts(visitors=row.visitors, conversions=row.influencedConversions)
+ for row in (response.results or [])
+ }
+ return rows, runner._sessions_precompute_used
+
+ def _materialize(self) -> LazyComputationResult:
+ # Same extended lower edge the reader asks for, so a session that opened before the window
+ # has its chunk built.
+ result = ensure_marketing_sessions_precomputed(
+ self.team,
+ WINDOW_START - timedelta(days=SESSION_READ_REACHBACK_DAYS),
+ datetime(2023, 1, 20, 23, 59, 59, tzinfo=UTC),
+ )
+ assert result.ready, result.errors
+ return result
+
+ @parameterized.expand(
+ [
+ ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN),
+ ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL),
+ ]
+ )
+ def test_session_open_before_the_window_with_events_inside_it_counts_in_both_paths(
+ self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown
+ ) -> None:
+ # The live scan keeps a session whose events land in the window and reports its start as the
+ # 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"])
+ self._session(
+ "straddler", WINDOW_START - timedelta(minutes=30), campaign="straddle", event_offsets_minutes=[0, 60]
+ )
+ 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]
+ )
+ self._conversion("inside", datetime(2023, 1, 12, 12, 0, tzinfo=UTC))
+ flush_persons_and_events()
+
+ live, live_used = self._run(breakdown, precomputed=False)
+ self._materialize()
+ pre, pre_used = self._run(breakdown, precomputed=True)
+
+ assert not live_used
+ assert pre_used, "the precomputed path was not used, so this proves nothing"
+ assert pre == live, f"precomputed={pre} live={live}"
+
+ def test_a_session_stored_under_two_jobs_is_one_touchpoint(self) -> None:
+ # A session's stored start is the earliest event seen when its chunk ran. A later event that
+ # predates it moves the start, filing the session under a different chunk while the first
+ # chunk's row survives. Both jobs are read, and without a collapse the person is credited
+ # twice for one session.
+ create_person(team=self.team, distinct_ids=["dup"])
+ self._session("dup", datetime(2023, 1, 11, 9, 0, tzinfo=UTC), campaign="dup", event_offsets_minutes=[0, 20])
+ self._conversion("dup", datetime(2023, 1, 12, 12, 0, tzinfo=UTC))
+ flush_persons_and_events()
+
+ result = self._materialize()
+ rows = sync_execute(
+ "SELECT session_id_v7, person_id, start_timestamp, job_id, computed_at, channel_type, utm_campaign, "
+ "utm_source, utm_medium, utm_term, utm_content, referring_domain, entry_pathname, period_bucket, "
+ "min_event_timestamp, max_event_timestamp, expires_at "
+ "FROM web_sessions_dimensional_preaggregated WHERE team_id = %(team)s AND utm_campaign = 'dup'",
+ {"team": self.team.pk},
+ )
+ assert len(rows) == 1, rows
+ original = rows[0]
+
+ # A second row for the same session under another job in the ready set. A backdated event moves
+ # the session start, and the entry properties are argMin by timestamp, so the re-materialized
+ # row can carry a different campaign. That is the damaging shape: one session landing in two
+ # campaigns, splitting the person across rows that should be one.
+ second_job = next(iter(result.job_ids))
+ sync_execute(
+ """
+ INSERT INTO web_sessions_dimensional_preaggregated
+ (team_id, job_id, period_bucket, session_id_v7, person_id, start_timestamp, min_event_timestamp,
+ max_event_timestamp, channel_type, utm_source, utm_medium, utm_campaign, utm_term, utm_content,
+ referring_domain, entry_pathname, computed_at, expires_at)
+ VALUES (%(team)s, %(job)s, %(bucket)s, %(sid)s, %(pid)s, %(start)s, %(min_ev)s, %(max_ev)s,
+ %(chan)s, %(src)s, %(med)s, %(camp)s, %(term)s, %(content)s, %(ref)s, %(path)s,
+ %(computed)s, %(expires)s)
+ """,
+ {
+ "team": self.team.pk,
+ "job": str(second_job),
+ "bucket": original[13],
+ "sid": str(original[0]),
+ "pid": original[1],
+ # earlier start, as a backdated event would produce
+ "start": original[2] - timedelta(minutes=45),
+ "min_ev": original[14] - timedelta(minutes=45),
+ "max_ev": original[15],
+ "chan": original[5],
+ "src": original[7],
+ "med": original[8],
+ "camp": "dup_superseded",
+ "term": original[9],
+ "content": original[10],
+ "ref": original[11],
+ "path": original[12],
+ "computed": original[4] + timedelta(minutes=1),
+ "expires": original[16],
+ },
+ )
+ stored = sync_execute(
+ "SELECT count() FROM web_sessions_dimensional_preaggregated "
+ "WHERE team_id = %(team)s AND session_id_v7 = toUInt128(%(sid)s)",
+ {"team": self.team.pk, "sid": str(original[0])},
+ )[0][0]
+ assert stored == 2, "the fixture must leave two rows for one session, or it proves nothing"
+
+ rows_out, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
+ assert used
+ # The newer row supersedes the older one, so the person sits in exactly one campaign.
+ assert "dup" not in rows_out, f"the superseded campaign is still credited: {rows_out}"
+ assert rows_out.get("dup_superseded") == _AttributionCounts(visitors=1, conversions=1), rows_out
+
+ # Both paths hold their own reference to the ceiling, so both have to be lowered for the fixture
+ # to stay small enough to read.
+ @parameterized.expand([("repeat", True), ("first_only", False)])
+ @patch("products.marketing_analytics.backend.hogql_queries.attribution_base.MAX_CONVERSIONS_PER_PERSON", 2)
+ @patch("products.marketing_analytics.backend.hogql_queries.attribution_sessions_read.MAX_CONVERSIONS_PER_PERSON", 2)
+ def test_a_person_over_the_conversion_ceiling_is_attributed_the_same_on_both_paths(
+ self, _name: str, allow_multiple_conversions: bool
+ ) -> None:
+ # The live path caps how many of one person's conversions can earn credit, because the two
+ # downstream ARRAY JOINs multiply without bound otherwise. A precomputed read that skipped the
+ # cap would both diverge here and reopen that growth.
+ create_person(team=self.team, distinct_ids=["heavy"])
+ self._session("heavy", datetime(2023, 1, 11, 9, 0, tzinfo=UTC), campaign="heavy", event_offsets_minutes=[0])
+ for hour in (10, 11, 12):
+ self._conversion("heavy", datetime(2023, 1, 12, hour, 0, tzinfo=UTC))
+ flush_persons_and_events()
+
+ live, live_used = self._run(
+ MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
+ precomputed=False,
+ allow_multiple_conversions=allow_multiple_conversions,
+ )
+ self._materialize()
+ pre, pre_used = self._run(
+ MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
+ precomputed=True,
+ allow_multiple_conversions=allow_multiple_conversions,
+ )
+
+ assert not live_used
+ assert pre_used, "the precomputed path was not used, so this proves nothing"
+ assert pre == live, f"precomputed={pre} live={live}"
+
+ def test_a_test_account_filter_falls_back_to_the_live_scan(self) -> None:
+ # The stored rows hold internal and external traffic together, and the touchpoint side never
+ # scans `events`, so the filter has nothing to apply to. Reading them anyway counted the
+ # internal visitor in the denominator and credited their conversion.
+ self.team.test_account_filters = [
+ {"key": "email", "value": "@internal.example.com", "operator": "not_icontains", "type": "person"}
+ ]
+ self.team.save()
+ self.team.marketing_analytics_config.filter_test_accounts = True
+ self.team.marketing_analytics_config.save()
+ create_person(team=self.team, distinct_ids=["buyer"], properties={"email": "[email protected]"})
+ create_person(team=self.team, distinct_ids=["staff"], properties={"email": "[email protected]"})
+ for distinct_id in ("buyer", "staff"):
+ self._session(
+ distinct_id,
+ datetime(2023, 1, 11, 9, 0, tzinfo=UTC),
+ campaign="shared",
+ event_offsets_minutes=[0],
+ source="google",
+ )
+ self._conversion(distinct_id, datetime(2023, 1, 12, 12, 0, tzinfo=UTC))
+ flush_persons_and_events()
+
+ live, live_used = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, precomputed=False)
+ self._materialize()
+ pre, pre_used = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, precomputed=True)
+
+ # Pinned, so the fixture proves the internal person was dropped rather than never seeded.
+ assert live == {"google": _AttributionCounts(visitors=1, conversions=1)}, live
+ assert not pre_used, "the precompute answered a query whose filter it cannot honor"
+ assert pre == live, f"precomputed={pre} live={live}"
+
+ def test_an_exclusion_judges_the_current_version_of_a_session(self) -> None:
+ # A session's rows can disagree: the stored start moves when a backdated event arrives, and the
+ # re-materialized row can carry different dimensions. Filtering the raw rows drops the current
+ # version and leaves the superseded one standing, so a session that is Direct today would keep
+ # earning credit under the campaign it used to carry.
+ create_person(team=self.team, distinct_ids=["flipped"])
+ self._session(
+ "flipped",
+ datetime(2023, 1, 11, 9, 0, tzinfo=UTC),
+ campaign="was_a_campaign",
+ event_offsets_minutes=[0],
+ source="google",
+ )
+ self._conversion("flipped", datetime(2023, 1, 12, 12, 0, tzinfo=UTC))
+ flush_persons_and_events()
+ self._materialize()
+
+ original = sync_execute(
+ "SELECT session_id_v7, person_id, start_timestamp, job_id, computed_at, period_bucket, "
+ "min_event_timestamp, max_event_timestamp, expires_at "
+ "FROM web_sessions_dimensional_preaggregated WHERE team_id = %(team)s AND utm_campaign = 'was_a_campaign'",
+ {"team": self.team.pk},
+ )[0]
+ sync_execute(
+ """
+ INSERT INTO web_sessions_dimensional_preaggregated
+ (team_id, job_id, period_bucket, session_id_v7, person_id, start_timestamp, min_event_timestamp,
+ max_event_timestamp, channel_type, utm_source, utm_medium, utm_campaign, utm_term, utm_content,
+ referring_domain, entry_pathname, computed_at, expires_at)
+ VALUES (%(team)s, %(job)s, %(bucket)s, %(sid)s, %(pid)s, %(start)s, %(min_ev)s, %(max_ev)s,
+ 'Direct', '', '', '', '', '', '', '/', %(computed)s, %(expires)s)
+ """,
+ {
+ "team": self.team.pk,
+ "job": str(original[3]),
+ "bucket": original[5],
+ "sid": str(original[0]),
+ "pid": original[1],
+ "start": original[2],
+ "min_ev": original[6],
+ "max_ev": original[7],
+ "computed": original[4] + timedelta(minutes=1),
+ "expires": original[8],
+ },
+ )
+
+ rows, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True, exclude_direct=True)
+ 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:
+ 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]
+ )
+ self._conversion("long-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 pre == live
+
+ @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"])
+ self._session(
+ "stale-session", datetime(2023, 1, 11, 9, tzinfo=UTC), campaign="stale", event_offsets_minutes=[0]
+ )
+ self._conversion("stale-session", datetime(2023, 1, 12, 12, tzinfo=UTC))
+ flush_persons_and_events()
+ original = self._materialize()
+ PreaggregationJob.objects.filter(team=self.team, id__in=original.job_ids).update(
+ expires_at=timezone.now() - timedelta(hours=1)
+ )
+ with patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=False):
+ live, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
+ assert not used
+ with (
+ patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=True),
+ patch.object(attribution_sessions_read, "handle_stale_served") as enqueue,
+ ):
+ stale, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
+ assert used
+ assert stale == live
+ enqueue.assert_called_once()
+ query = enqueue.call_args.kwargs["query"]
+ runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)
+ runner.config.sessions_precomputation_enabled = True
+ with (
+ tags_context(),
+ patch(
+ "products.marketing_analytics.backend.tasks.lazy_precompute_revalidation.get_query_runner",
+ return_value=runner,
+ ),
+ ):
+ revalidate_marketing_analytics_precompute(self.team.pk, query.model_dump())
+ assert runner._sessions_precompute_used
+ assert set(runner._sessions_precompute_jobs or []).isdisjoint(map(str, original.job_ids))
+ enqueue.assert_called_once()
+ with patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=False):
+ fresh, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
+ assert used
+ assert fresh == live
+
+ @parameterized.expand(
+ [
+ (state, version)
+ for state in ("merged", "override_first", "mapping_first", "split", "squashed")
+ for version in (SessionTableVersion.V2, SessionTableVersion.V3)
+ ]
+ )
+ def test_cached_dimensions_follow_current_event_identity(self, state: str, version: SessionTableVersion) -> None:
+ self.team.modifiers = {
+ "sessionTableVersion": version,
+ "personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,
+ }
+ create_person(team=self.team, distinct_ids=["anonymous", "second-device"])
+ identified = create_person(team=self.team, distinct_ids=["identified"])
+ self._session(
+ "anonymous", datetime(2023, 1, 11, 9, tzinfo=UTC), campaign="first", event_offsets_minutes=[0, 10]
+ )
+ self._session(
+ "second-device", datetime(2023, 1, 11, 10, tzinfo=UTC), campaign="second", event_offsets_minutes=[0, 10]
+ )
+ self._conversion("identified", datetime(2023, 1, 12, 12, tzinfo=UTC))
+ flush_persons_and_events()
+ result = self._materialize()
+ stored_before = sync_execute(
+ "SELECT * FROM web_sessions_dimensional_preaggregated WHERE team_id = %(team)s ORDER BY session_id_v7",
+ {"team": self.team.pk},
+ )
+ self.assertTrue(stored_before)
+
+ def override(distinct_id: str, person_id: UUID, version: int, deleted: bool = False) -> None:
+ sync_execute(
+ "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version, is_deleted) VALUES",
+ [(self.team.pk, distinct_id, person_id, version, int(deleted))],
+ )
+
+ moving_ids = ["anonymous"] if state == "split" else ["anonymous", "second-device"]
+ for distinct_id in moving_ids:
+ if state != "override_first":
+ add_distinct_id(person=identified, distinct_id=distinct_id, version=1)
+ if state != "mapping_first":
+ override(distinct_id, identified.uuid, 1)
+ if state == "squashed":
+ sync_execute(
+ "ALTER TABLE sharded_events UPDATE person_id = %(person)s "
+ "WHERE team_id = %(team)s AND distinct_id = %(distinct)s SETTINGS mutations_sync = 2",
+ {"person": identified.uuid, "team": self.team.pk, "distinct": distinct_id},
+ )
+ override(distinct_id, identified.uuid, 2, deleted=True)
+
+ query_args = {
+ "dateRange": DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ "breakdownBy": MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
+ "conversionGoalId": GOAL_ID,
+ "properties": [],
+ }
+ for query_type, runner_type in (
+ (MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),
+ (MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),
+ ):
+ responses = []
+ for precomputed in (False, True):
+ runner = runner_type(query=query_type(**query_args), team=self.team)
+ runner.config.sessions_precomputation_enabled = precomputed
+ response = runner.calculate()
+ self.assertEqual(runner._sessions_precompute_used, precomputed)
+ responses.append(response.results)
+ if isinstance(response, MarketingAnalyticsAttributionQueryResponse):
+ self.assertEqual(response.totalConversions, 1)
+ self.assertEqual(response.unattributedConversions, 1 if state == "mapping_first" else 0)
+ else:
+ self.assertEqual(response.attributedConversions, 0 if state == "mapping_first" else 1)
+ self.assertCountEqual(responses[0], responses[1])
+
+ stored_after = sync_execute(
+ "SELECT * FROM web_sessions_dimensional_preaggregated WHERE team_id = %(team)s ORDER BY session_id_v7",
+ {"team": self.team.pk},
+ )
+ self.assertEqual(stored_after, stored_before)
+ hit = ensure_marketing_sessions_precomputed(
+ self.team,
+ WINDOW_START - timedelta(days=SESSION_READ_REACHBACK_DAYS),
+ datetime(2023, 1, 20, 23, 59, 59, tzinfo=UTC),
+ run_inserts=False,
+ )
+ self.assertTrue(hit.ready)
+ self.assertEqual(set(hit.job_ids), set(result.job_ids))
+
+ @parameterized.expand(
+ [
+ (SessionTableVersion.V2, SessionTableVersion.V3, False, "google"),
+ (SessionTableVersion.V3, SessionTableVersion.V2, False, "old"),
+ (SessionTableVersion.AUTO, SessionTableVersion.V2, True, "old"),
+ (SessionTableVersion.V2, SessionTableVersion.AUTO, True, "old"),
+ (SessionTableVersion.V3, SessionTableVersion.V3, True, "google"),
+ ]
+ )
+ def test_query_session_version_matches_cached_dimensions(
+ self, team_version: SessionTableVersion, query_version: SessionTableVersion, expected_cached: bool, source: str
+ ) -> None:
+ self.team.modifiers = {"sessionTableVersion": team_version}
+ opened_at = datetime(2023, 1, 11, 9, tzinfo=UTC)
+ session_id = str(uuid7(opened_at.strftime("%Y-%m-%dT%H:%M:%SZ")))
+ create_person(team=self.team, distinct_ids=["version-override"])
+ for event, offset, utm_source in [("$autocapture", 0, "old"), ("$pageview", 1, "google")]:
+ _create_event(
+ team=self.team,
+ distinct_id="version-override",
+ event=event,
+ timestamp=opened_at + timedelta(minutes=offset),
+ properties={"$session_id": session_id, "utm_source": utm_source, "utm_medium": "cpc"},
+ )
+ self._conversion("version-override", datetime(2023, 1, 12, 12, tzinfo=UTC))
+ flush_persons_and_events()
+ self._materialize()
+ modifiers = HogQLQueryModifiers(sessionTableVersion=query_version)
+ live, _ = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, precomputed=False, modifiers=modifiers)
+ cached, used = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, precomputed=True, modifiers=modifiers)
+ assert used is expected_cached
+ assert cached == live == {source: _AttributionCounts(visitors=1, conversions=1)}
+
+ @parameterized.expand(["start", "end"])
+ def test_ambiguous_date_boundary_preserves_live_attribution(self, boundary: str) -> None:
+ self.team.timezone = "America/New_York"
+ date_range = DateRange(
+ date_from="2025-11-02T01:30:00-05:00" if boundary == "start" else "2025-11-01T00:00:00-04:00",
+ date_to="2025-11-02T01:30:00-05:00" if boundary == "end" else "2025-11-03T00:00:00-05:00",
+ explicitDate=True,
+ )
+ create_person(team=self.team, distinct_ids=["ambiguous-boundary"])
+ pageview_at = (
+ datetime(2025, 10, 29, 6, tzinfo=UTC) if boundary == "start" else datetime(2025, 11, 2, 6, tzinfo=UTC)
+ )
+ session_id = str(uuid7(pageview_at.strftime("%Y-%m-%dT%H:%M:%SZ")))
+ _create_event(
+ team=self.team,
+ distinct_id="ambiguous-boundary",
+ event="$pageview",
+ timestamp=pageview_at,
+ properties={"$session_id": session_id, "utm_campaign": "boundary"},
+ )
+ if boundary == "end":
+ _create_event(
+ team=self.team,
+ distinct_id="ambiguous-boundary",
+ event="$autocapture",
+ timestamp=datetime(2025, 11, 2, 4, tzinfo=UTC),
+ properties={"$session_id": session_id, "utm_campaign": "boundary"},
+ )
+ self._conversion("ambiguous-boundary", datetime(2025, 11, 2, 5, 40 if boundary == "start" else 0, tzinfo=UTC))
+ flush_persons_and_events()
+ materialized = ensure_marketing_sessions_precomputed(
+ self.team, datetime(2025, 10, 27, tzinfo=UTC), datetime(2025, 11, 4, tzinfo=UTC)
+ )
+ assert materialized.ready, materialized.errors
+ for query_type, runner_type in (
+ (MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),
+ (MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),
+ ):
+ responses = []
+ for precomputed in (False, True):
+ runner = runner_type(
+ query=query_type(
+ dateRange=date_range,
+ breakdownBy=MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ ),
+ team=self.team,
+ )
+ runner.config.sessions_precomputation_enabled = precomputed
+ response = runner.calculate()
+ assert not runner._sessions_precompute_used
+ assert response.totalConversions == 1
+ responses.append(response.results)
+ self.assertCountEqual(responses[0], responses[1])
+
+ @parameterized.expand(
+ [
+ (goal, explicit, version)
+ for goal in ("purchase", "$pageview")
+ for explicit in (False, True)
+ for version in (SessionTableVersion.V2, SessionTableVersion.V3)
+ ]
+ )
+ def test_fractional_boundary_events_match_conversion_date_precision(
+ self, goal: str, explicit: bool, version: SessionTableVersion
+ ) -> None:
+ self.team.modifiers = {"sessionTableVersion": version}
+ config = self.team.marketing_analytics_config
+ config.conversion_goals[0]["event"] = goal
+ config.save()
+ end = datetime(2023, 1, 20, 23, 59, 59, tzinfo=UTC)
+ for distinct_id, at, converts in [
+ ("reach-only", end + timedelta(microseconds=500000), False),
+ ("boundary", end + timedelta(microseconds=500000), True),
+ ("start", datetime(2023, 1, 10, 0, 0, 0, 250000, tzinfo=UTC), True),
+ ("excluded", end + timedelta(seconds=1), True),
+ ]:
+ create_person(team=self.team, distinct_ids=[distinct_id])
+ _create_event(
+ team=self.team,
+ distinct_id=distinct_id,
+ event="$pageview",
+ timestamp=at,
+ properties={
+ "$session_id": str(uuid7(at.strftime("%Y-%m-%dT%H:%M:%SZ"))),
+ "utm_campaign": distinct_id,
+ "revenue": 100,
+ },
+ )
+ if converts and goal == "purchase":
+ _create_event(
+ team=self.team,
+ distinct_id=distinct_id,
+ event=goal,
+ timestamp=at + timedelta(microseconds=100000),
+ properties={"revenue": 100},
+ )
+ flush_persons_and_events()
+ self._materialize()
+ date_range = DateRange(
+ date_from="2023-01-10T00:00:00.750000Z" if explicit else DATE_FROM,
+ date_to="2023-01-20T23:59:59.250000Z" if explicit else DATE_TO,
+ explicitDate=explicit,
+ )
+ expected_conversions = 3 if goal == "$pageview" else 2
+ for query_type, runner_type in (
+ (MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),
+ (MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),
+ ):
+ results = []
+ for precomputed in (False, True):
+ query = query_type(
+ dateRange=date_range,
+ breakdownBy=MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
+ conversionGoalId=GOAL_ID,
+ properties=[],
+ )
+ runner = runner_type(query=query, team=self.team)
+ runner.config.sessions_precomputation_enabled = precomputed
+ response = runner.calculate()
+ assert runner._sessions_precompute_used is precomputed
+ assert response.totalConversions == expected_conversions
+ if isinstance(response, MarketingAnalyticsAttributionQueryResponse):
+ assert response.unattributedConversions == 0
+ rows = {row.breakdownValue: row.visitors for row in response.results or []}
+ assert rows == {"reach-only": 1, "boundary": 1, "start": 1}, (precomputed, rows)
+ else:
+ assert response.attributedConversions == expected_conversions
+ results.append(response.results)
+ self.assertCountEqual(results[0], results[1])
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
new file mode 100644
index 000000000000..75f260f5e05b
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
@@ -0,0 +1,317 @@
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from uuid import UUID
+
+from unittest.mock import PropertyMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ ConversionGoalFilter1,
+ CustomChannelRule,
+ DateRange,
+ HogQLQueryModifiers,
+ MarketingAnalyticsAttributionQuery,
+ PropertyMathType,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+
+from posthog.clickhouse.query_tagging import Feature, tags_context
+from posthog.models import Organization, Team
+from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationQuery,
+ LazyComputationResult,
+ LazyComputationTable,
+ compute_query_hash,
+)
+from products.marketing_analytics.backend.hogql_queries import attribution_sessions_read, marketing_sessions_precompute
+from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
+ MarketingAnalyticsAttributionQueryRunner,
+)
+from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (
+ REVALIDATION_TRIGGER,
+ STALE_WHILE_REVALIDATE_SECONDS,
+)
+
+
+class TestAttributionSessionsRead(SimpleTestCase):
+ def setUp(self) -> None:
+ self.enterContext(
+ patch.object(
+ 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)
+ )
+ )
+ self.enterContext(patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=False))
+ self.team = Team(id=1, organization=Organization(id=UUID(int=1)))
+ self.team.modifiers = {"personsOnEventsMode": "person_id_override_properties_on_events"}
+ config = TeamMarketingAnalyticsConfig(team=self.team)
+ config.conversion_goals = [
+ ConversionGoalFilter1(
+ event="purchase",
+ name="Purchases",
+ conversion_goal_id="goal",
+ conversion_goal_name="Purchases",
+ schema_map={},
+ math=PropertyMathType.SUM,
+ math_property="revenue",
+ ).model_dump()
+ ]
+ self.enterContext(
+ patch.object(Team, "marketing_analytics_config", new_callable=PropertyMock, return_value=config)
+ )
+ self.enterContext(
+ patch(
+ "products.marketing_analytics.backend.hogql_queries.marketing_analytics_config.feature_enabled_or_false",
+ return_value=False,
+ )
+ )
+ self.enterContext(patch.object(attribution_sessions_read, "team_has_property_access_rules", return_value=False))
+
+ @parameterized.expand([("repeat", True), ("first_only", False)])
+ def test_session_join_does_not_repeat_revenue_aggregation(self, _name: str, repeat: bool) -> None:
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),
+ lookbackWindowDays=4,
+ allowMultipleConversionsPerVisitor=repeat,
+ ),
+ )
+ with patch.object(
+ attribution_sessions_read,
+ "ensure_marketing_sessions_precomputed",
+ return_value=LazyComputationResult(ready=True, job_ids=[UUID(int=1)]),
+ ):
+ runner.config.sessions_precomputation_enabled = True
+ query = attribution_sessions_read.build_person_arrays(runner, runner.query_date_range)
+ assert query is not None
+ query.ctes = attribution_sessions_read.session_ctes(runner, runner.query_date_range)
+ assert query is not None
+ sql = query.to_hogql()
+ assert sql.count("groupArray(") == 1
+ assert sql.count("events.properties.revenue") == 1
+ assert "AS first_conversion" in sql
+ assert ("conv.last_conversion" in sql) is repeat
+
+ def test_default_lookback_and_ninety_display_days_fit_writer_coverage(self) -> None:
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-03-31"),
+ ),
+ )
+ assert runner.lookback_window_days == 90
+ assert marketing_sessions_precompute.precompute_window_days(self.team) == 181
+ assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) is None
+ with patch.object(
+ attribution_sessions_read,
+ "window",
+ return_value=attribution_sessions_read.ReadWindow(
+ start=datetime(2023, 1, 1, tzinfo=UTC), end=datetime(2023, 7, 1, tzinfo=UTC)
+ ),
+ ):
+ assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) == "window_over_max"
+
+ @parameterized.expand(
+ [
+ ("stale_user", True, False, True, True),
+ ("flag_off", False, False, False, False),
+ ("revalidation", True, True, False, True),
+ ("cold_user", True, False, False, False),
+ ]
+ )
+ def test_stale_policy_and_revalidation(
+ self, _name: str, flag: bool, refreshing: bool, stale: bool, ready: bool
+ ) -> None:
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ lookbackWindowDays=4,
+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),
+ ),
+ )
+ 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
+ ),
+ patch.object(attribution_sessions_read, "serve_stale_enabled", return_value=flag),
+ patch.object(attribution_sessions_read, "handle_stale_served") as revalidate,
+ patch.object(
+ marketing_sessions_precompute,
+ "ensure_precomputed",
+ return_value=LazyComputationResult(ready=ready, stale=stale, job_ids=[UUID(int=1)] if ready else []),
+ ) as ensure,
+ ):
+ result = attribution_sessions_read._ensure(runner, runner.query_date_range)
+ assert (result is not None) is ready
+ assert attribution_sessions_read._ensure(runner, runner.query_date_range) == result
+ ensure.assert_called_once()
+ assert ensure.call_args.kwargs["run_inserts"] is refreshing
+ assert ensure.call_args.kwargs["stale_while_revalidate_seconds"] == (
+ 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:
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ lookbackWindowDays=4,
+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),
+ ),
+ )
+ self.coverage.return_value.results = rows
+ self.coverage.return_value.error = error
+ with patch.object(
+ attribution_sessions_read,
+ "ensure_marketing_sessions_precomputed",
+ return_value=LazyComputationResult(ready=True, job_ids=[UUID(int=1)]),
+ ) as ensure:
+ assert attribution_sessions_read.build_person_arrays(runner, runner.query_date_range) is None
+ ensure.assert_called_once()
+
+ @parameterized.expand(
+ [
+ (HogQLQueryModifiers(), HogQLQueryModifiers(sessionTableVersion="v1"), "session_table_version_mismatch"),
+ (HogQLQueryModifiers(), HogQLQueryModifiers(sessionsV2JoinMode="string"), "session_join_mode_mismatch"),
+ (HogQLQueryModifiers(), HogQLQueryModifiers(convertToProjectTimezone=False), "project_timezone_disabled"),
+ (HogQLQueryModifiers(convertToProjectTimezone=False), HogQLQueryModifiers(), "project_timezone_disabled"),
+ (
+ HogQLQueryModifiers(
+ customChannelTypeRules=[
+ CustomChannelRule(id="custom", channel_type="Custom", combiner="AND", items=[])
+ ]
+ ),
+ HogQLQueryModifiers(customChannelTypeRules=[]),
+ "custom_channel_rules",
+ ),
+ ]
+ )
+ def test_incompatible_dimension_modifiers_fall_back(
+ self, team_modifiers: HogQLQueryModifiers, query_modifiers: HogQLQueryModifiers, reason: str
+ ) -> None:
+ self.team.modifiers.update(team_modifiers.model_dump(exclude_none=True))
+ self.team.timezone = "America/New_York"
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ lookbackWindowDays=4,
+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),
+ modifiers=query_modifiers,
+ ),
+ )
+ assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) == reason
+ 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 None
+ ensure.assert_not_called()
+ self.coverage.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("America/New_York", "2025-11-02T01:30:00-04:00", "2025-11-03", True, True),
+ ("America/New_York", "2025-11-02T01:30:00-05:00", "2025-11-03", True, True),
+ ("America/New_York", "2025-11-01", "2025-11-02T01:30:00-04:00", True, True),
+ ("America/New_York", "2025-11-01", "2025-11-02T01:30:00-05:00", True, True),
+ ("America/New_York", "2025-11-01", "2025-11-03", False, False),
+ ("America/Santiago", "2025-04-04", "2025-04-05", False, True),
+ ("America/Santiago", "2025-04-04", "2025-04-06", False, False),
+ ]
+ )
+ def test_ambiguous_date_boundaries_fall_back(
+ self, timezone: str, date_from: str, date_to: str, explicit: bool, ambiguous: bool
+ ) -> None:
+ self.team.timezone = timezone
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ lookbackWindowDays=4,
+ dateRange=DateRange(date_from=date_from, date_to=date_to, explicitDate=explicit),
+ ),
+ )
+ assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) == (
+ "ambiguous_date_boundary" if ambiguous else None
+ )
+
+ def test_classifier_changes_invalidate_shared_query_identity(self) -> None:
+ def identity() -> str:
+ query = parse_select(
+ marketing_sessions_precompute.SESSIONS_INSERT_TEMPLATE,
+ placeholders={
+ **marketing_sessions_precompute.base_placeholders(),
+ "time_window_min": ast.Constant(value="MIN"),
+ "time_window_max": ast.Constant(value="MAX"),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return compute_query_hash(
+ LazyComputationQuery(
+ query=query,
+ table=LazyComputationTable.WEB_SESSIONS_DIMENSIONAL_PREAGGREGATED,
+ )
+ )
+
+ original = identity()
+ assert identity() == original
+ with patch.object(marketing_sessions_precompute, "SESSION_CHANNEL_CLASSIFIER_VERSION", 2):
+ assert identity() != original
+ with patch.object(
+ marketing_sessions_precompute,
+ "expand_default_channel_type_call",
+ return_value=ast.Constant(value="Changed"),
+ ):
+ assert identity() != original
+
+ def test_disabled_reader_does_not_check_jobs_or_session_coverage(self) -> None:
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ lookbackWindowDays=4,
+ dateRange=DateRange(date_from="2023-01-10", date_to="2023-01-11"),
+ ),
+ )
+ runner.config.sessions_precomputation_enabled = False
+ 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.py
index 5a92e9177fd5..a6d8e91150cd 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
@@ -1,3 +1,5 @@
+from uuid import UUID
+
import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -21,6 +23,7 @@ from posthog.hogql import ast
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.property_access_types import RestrictedProperty
from posthog.hogql.test.utils import pretty_print_in_tests
+from posthog.hogql.visitor import TraversingVisitor
from posthog.models import PropertyDefinition
from posthog.models.team.team_marketing_analytics_config import MAX_ATTRIBUTION_WINDOW_DAYS
@@ -28,6 +31,7 @@ from posthog.models.utils import uuid7
from posthog.test.persons import create_person
from products.actions.backend.models.action import Action
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.cohorts.backend.models.cohort import Cohort
from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
MarketingAnalyticsAttributionQueryRunner,
@@ -770,17 +774,28 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
person_arrays = ctes["person_arrays"].expr
assert isinstance(person_arrays, ast.SelectQuery)
- # The restriction is a join against the converters subquery. Asserting on the join rather than
- # on a bare `IN` keeps the test about the property (only converters are scanned) instead of the
- # operator that happens to express it.
- join = person_arrays.select_from
- assert join is not None
- restrictions = []
- while join is not None:
- if isinstance(join.table, ast.SelectQuery):
- restrictions.append(join)
- join = join.next_join
- self.assertTrue(restrictions, "person_arrays must restrict the events scan to converting persons")
+ # Asserts the restriction exists, not the shape it takes: a semi-join in the WHERE and a join
+ # against the converters subquery both pay for the scan, and which one is used is free to change.
+ class FindConverterSubquery(TraversingVisitor):
+ def __init__(self) -> None:
+ self.found = False
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ if node is not person_arrays and _selects_person_id(node):
+ self.found = True
+ super().visit_select_query(node)
+
+ def _selects_person_id(node: ast.SelectQuery) -> bool:
+ for column in node.select:
+ expr = column.expr if isinstance(column, ast.Alias) else column
+ if isinstance(expr, ast.Field) and expr.chain[-1] == "person_id":
+ return True
+ return False
+
+ finder = FindConverterSubquery()
+ finder.visit(person_arrays.select_from)
+ finder.visit(person_arrays.where)
+ self.assertTrue(finder.found, "person_arrays must restrict the events scan to converting persons")
def test_action_goals_credit_the_events_the_action_matches(self):
# The action branch resolves the goal through Postgres and `action_to_expr` rather than a plain
@@ -1038,7 +1053,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
with self.assertRaises(ValueError):
MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team).to_query()
- def _printed_sql(self, breakdown: MarketingAnalyticsAttributionBreakdown) -> str:
+ def _printed_sql(self, breakdown: MarketingAnalyticsAttributionBreakdown, *, precomputed: bool = False) -> str:
query = MarketingAnalyticsAttributionQuery(
dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
breakdownBy=breakdown,
@@ -1046,10 +1061,17 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
properties=[],
)
runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)
+ runner.config.sessions_precomputation_enabled = precomputed
context = runner._shared_hogql_context
# execute_hogql_query flips this on the context it is handed; do the same to print the real query.
context.enable_select_queries = True
- printed = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
+ ready = LazyComputationResult(ready=True, job_ids=[UUID(int=1)])
+ with patch(
+ "products.marketing_analytics.backend.hogql_queries.attribution_sessions_read.ensure_marketing_sessions_precomputed",
+ return_value=ready,
+ ):
+ printed = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
+ assert runner._sessions_precompute_used == precomputed
return pretty_print_in_tests(printed[0] if isinstance(printed, tuple) else printed, self.team.pk)
# One breakdown per SQL shape. Campaign reads a stored property, and the five breakdowns not listed
@@ -1065,3 +1087,16 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
@pytest.mark.usefixtures("unittest_snapshot")
def 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.
+ @parameterized.expand(
+ [
+ ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN),
+ ("source", MarketingAnalyticsAttributionBreakdown.SOURCE),
+ ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL),
+ ]
+ )
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_precomputed_sessions_sql(self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown):
+ assert self._printed_sql(breakdown, precomputed=True) == self.snapshot