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.

chore(marketing): retire the precomputed attribution reader (#110293)

Javier Bahamondesdfd8f45f2ad7
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.md
index 0e6cd3996334..35624b36c583 100644
--- a/docs/internal/marketing-attribution-session-precompute.md
+++ b/docs/internal/marketing-attribution-session-precompute.md
@@ -1,79 +1,52 @@
-# Attribution session precompute
+# Attribution session resolution
-The sessions-precomputation flag enables the attribution table and paths reader. Cold, ineligible, or failed job lookups fall back to live queries. Sessions that started before the one-day reachback or exceed the three-day writer scan budget read their dimensions live, while other sessions use the cache. These exceptions do not disable the cache for the entire query.
+The `marketing-analytics-live-session-resolution` flag enables shared live session resolution for attribution tables and paths.
+Eligible queries read current events and raw sessions without a Marketing session precompute job.
+The sessions-precomputation reader is retired.
+Marketing attribution no longer reads `web_sessions_dimensional_preaggregated` or queues session-cache refreshes.
+The independent writer, Dagster job and schedule definitions, table, and schema remain in place.
-The writer excludes sessions longer than its scan budget. The reader also replaces dimensions of cached sessions that later grow beyond that budget, including growth after the report end. It first selects conservative candidates from raw timestamp rows, then checks their exact start/end after aggregation. This avoids holding aggregate state for ordinary sessions. It filters candidate IDs before merging entry properties and joins both dimension sources to current pageview identities. Session IDs and dimensions remain inside ClickHouse, so the SQL size does not grow with the exception count. Both raw-session reads retain the timestamp bounds used by live attribution. Sessions whose ID timestamp is more than three days before the extended attribution read window remain outside both lookups. Their source events remain stored. Expanding this coverage requires changing and validating live and cached attribution together.
+## Query behavior
-The writer query change invalidates existing job hashes. Deploy both writer and reader before warming the new jobs; keep the reader flag off until the controlled rollout validates coverage and query cost.
+A materialized CTE selects pageview session IDs and current person IDs once per query.
+The raw-session lookup filters to those IDs before merging entry properties and classifying channels.
+Reach and credit share the resolved session rows and conversion aggregation within the query.
+Table and paths reports execute separate queries.
-`MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS` covers calendar display days in the project timezone.
-The warmer starts at local midnight that many days before the run's local date, then subtracts the team's attribution lookback and one reachback day in UTC.
-It warms through the end of that local day so reports that include today have complete UTC daily-window coverage.
-For projects west of UTC, this can warm a UTC window before it starts.
-A job computed before its window starts stops being eligible at that start, including for stale reads.
-The reader falls back to live calculation until the window is refreshed after it starts, so the earlier snapshot cannot hide new sessions.
-The reader uses the same calendar boundary to check its maximum range.
-This includes the complete starting day for relative ranges such as `-90d`, even across daylight saving changes.
-Query overrides that extend before that boundary remain ineligible.
+Touchpoints and conversions resolve identity through `events.person_id`, so merges, splits, and delayed identity mappings follow the legacy live query without rebuilding session jobs.
+Late-arriving events and session updates do not depend on a stored dimension snapshot.
+Missing precompute coverage at a calendar boundary cannot switch this route back to the legacy query.
+The report's date range and project timezone remain unchanged.
-Calendar alignment does not change the writer query or existing job hashes.
-Run the updated warmer to populate missing daily windows at either end before testing the full display range.
-Existing ready jobs remain reusable if they satisfy the freshness policy, and missing coverage still falls back to live calculation.
-The allowlist, daily chunk size, and query execution limits are unchanged.
+Eligible queries use 16 ClickHouse threads and aggregation in storage order where the grouping keys permit it.
+The spill threshold and timeout stay unchanged.
+These settings limit partial aggregation states and temporary spill files; they do not guarantee that every query will be faster.
-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.
+## Eligibility and fallback
-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.
+The shared route retains its existing eligibility checks.
+It falls back to legacy live attribution for non-integer timezone offsets, ambiguous date boundaries, property access rules, test-account filters, incompatible session modifiers, or ranges beyond its configured limit.
+Conversion goals that depend on session fields or deferred action expressions also use legacy attribution, preserving its wider session-ID lookup window.
+Custom channel rules can use shared resolution when they match the project's rules.
+AUTO and v2 have the same session semantics.
-Materialized CTEs share the pageview identity scan between reach and credit, and share the conversion aggregation with the timestamp bounds. Event scans remain necessary for identity and conversions; cached dimensions avoid merging entry properties and classifying channels for ordinary sessions. A narrow timestamp scan and selective dimension lookup handle exceptional sessions. This uses the existing `web_sessions_dimensional_preaggregated` schema and does not require a migration.
-
-The shared sessions CTE selects one dimension row per session, then joins it to unique session/person pairs from current pageviews.
-Reach and credit use these resolved rows directly, without grouping by session again.
-Exclusions and conversion bounds apply after dimension resolution, so superseded cached rows cannot survive a filter or add a touchpoint.
-This reader optimization does not change writer hashes or require rebuilding existing jobs.
-
-Queries that override the session table version or v2 join mode fall back to live attribution when they differ from the writer. AUTO and v2 share the same session semantics. Custom channel rules can use cached dimensions when they match the writer's project rules, including rules that depend on the full entry URL. The writer classifies the channel before storing it and includes the rules in the job hash, so rule changes require fresh jobs. Queries with different rules, or disabled project-timezone conversion, use the live path. Identity and execution-only modifiers do not invalidate cached dimensions.
-
-The shared job hash excludes `cookielessTrafficIsRegular` because the writer does not classify traffic types.
-Different evaluations of that rollout flag in background workers and query workers do not require new session jobs.
-
-For the cache-key transition, an old job with an unset `cookielessTrafficIsRegular` keeps the same key because serialization already omitted null values.
-An old job with an explicit `true` or `false` has a different key and needs replacement before cached reads resume.
-There is no compatibility lookup for those old keys.
-Use the updated writer to prepare valid jobs for the full attribution read window before enabling cached reads.
-Keep cached reads disabled until a read-only job lookup confirms complete, fresh coverage.
-Missing coverage falls back to live calculation, so changing the key alone does not guarantee faster queries.
-
-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.
-
-## Live session resolution
-
-The independent `marketing-analytics-live-session-resolution` flag opts attribution tables and paths into shared live session resolution.
-It takes precedence over the sessions-precomputation flag for eligible queries and does not require precomputed jobs.
-The default remains off.
-Attribution result cache keys distinguish the flag state, so enabling or disabling it cannot reuse results computed with the opposite setting.
+Raw-session lookups retain the legacy path's session-ID timestamp bounds, including its three-day buffer.
+This does not extend coverage for older session IDs or guarantee that independently replicated events and sessions arrive together.
+Pageview scans include the full final second of the selected range, matching conversion filters, including explicit fractional bounds.
-This route materializes pageview session IDs and current person IDs once, then resolves current dimensions from the matching raw sessions.
-Reach and credit share those rows and the conversion aggregation.
-Late-arriving events and session updates therefore do not depend on a cached dimension snapshot or its recorded ingestion time.
-A missing cache window at a calendar boundary does not switch this route back to the legacy live query.
-The report's date range and timezone remain unchanged.
+`MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS` retains its existing name and default of `90` for configuration compatibility.
+It limits the display history eligible for shared live resolution and still configures the independent writer's coverage.
+The lower limit starts at project-local midnight that many calendar days before the end date, then subtracts the project's attribution lookback in UTC.
+Query lookback overrides that extend before that limit remain ineligible.
-Eligible live-session queries limit ClickHouse execution to 16 threads and enable aggregation in storage order where the grouping keys permit it.
-This limits partial aggregation states and temporary spill files while preserving the existing spill threshold and timeout.
-Cached reads and ineligible queries keep the default execution settings.
+## Rollout and rollback
-The initial rollout keeps the cached reader's eligibility restrictions, including date-boundary, access-control, test-account, range, and session-modifier checks.
-Conversion goals that depend on session fields or deferred action expressions also use legacy live attribution, preserving its wider session-ID lookup window.
-Ineligible queries continue to use legacy live attribution.
-Raw session lookups retain that path's session-ID timestamp bounds, including its three-day buffer.
-This does not extend coverage for older session IDs or guarantee that independently replicated events and sessions arrive together.
+The flag remains independent of other Marketing precomputation flags.
+Attribution result cache keys distinguish its enabled and disabled states.
+The query telemetry property `live_session_resolution_used` identifies the shared route.
+Disabling the flag uses legacy live attribution.
+Cost and conversion precomputation remain unchanged.
-Validate result parity and query cost before enabling this flag: current dimensions require more source reads than a warm dimension cache.
-The query telemetry property `live_session_resolution_used` identifies this route; `sessions_precompute_used` remains false for it.
-Disabling the new flag restores the existing selection between cached and legacy live attribution.
-The writer, schedule, existing jobs, TTLs, and job hashes are unchanged.
+Validate result parity and query cost before extending the rollout.
+A session backfill, session writer schedule, and session-cache TTL changes are not required.
+See [Session precompute writer](marketing-sessions-precompute.md) for the independent writer's deployment configuration.
diff --git a/docs/internal/marketing-sessions-precompute.md b/docs/internal/marketing-sessions-precompute.md
index c05456d8c6b9..18dfe1874b19 100644
--- a/docs/internal/marketing-sessions-precompute.md
+++ b/docs/internal/marketing-sessions-precompute.md
@@ -1,11 +1,15 @@
# Marketing session precompute writer
+Marketing attribution tables and paths no longer read this cache or queue its refreshes.
+Their shared live session resolution does not require the writer to run; see [Attribution session resolution](marketing-attribution-session-precompute.md).
+The writer, Dagster job and schedule definitions, and physical table remain available for independent consumers.
+
The writer partitions sessions by the UTC hour of their start in `web_sessions_dimensional_preaggregated`.
Window membership uses the exact start timestamp; hourly buckets are rounded explicitly in UTC, including for projects with half-hour or quarter-hour timezone offsets.
It writes `session_id_v7` as the numeric UUID representation from `events.$session_id_uuid` and stores the first and last pageview timestamps.
Each insert covers at most one day of session starts and scans events through three days after that window ends.
Before writing or accepting cached jobs, it checks the corresponding daily windows for sessions longer than three days.
-If it finds one, it returns `ready=False` so the reader can use live attribution without truncating that session.
+If it finds one, it returns `ready=False` so callers cannot accept a truncated session snapshot.
A failed coverage query also returns `ready=False`; an empty result accompanied by an error does not prove coverage.
Sessions lasting more than one day, including 49-hour sessions, remain supported by the cache.
@@ -13,11 +17,11 @@ Results are snapshots subject to the configured freshness schedule.
A start-day window settles three days after it ends, matching the maximum supported session duration.
Snapshots computed before that point expire at the settling boundary even when their stored TTL is longer, so a later first pageview cannot leave the window empty for 90 days.
Before settlement, the normal freshness schedule still applies; session dimensions are not updated on every event.
-The writer respects the team's session table version: v3 when configured, otherwise v2; v1 requests fall back to live attribution.
+The writer respects the team's session table version: v3 when configured, otherwise v2; v1 requests return `ready=False`.
Resolved query modifiers are part of the cache identity, so different source versions and channel rules cannot reuse the same jobs.
Stored person IDs are snapshots too: a merge after materialization can leave a touchpoint under its previous person ID until refresh.
-The reader must resolve current identity before enabling this path for merged-person attribution.
+Any consumer that attributes events to people must resolve current identity before using these snapshots.
## Deployment configuration
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 8e7b1dc74d79..6f77f24c2f31 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
@@ -128,232 +128,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_3_cached_campaign
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, web_sessions_dimensional_preaggregated.utm_campaign, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_11)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_12)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_21)s)), `$start_timestamp`, %(hogql_val_22)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_23)s)), %(hogql_val_24)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_25)s)), %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s) AS dimensions, now64(6, %(hogql_val_30)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_13)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_14)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_15)s), %(hogql_val_16)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_17)s), %(hogql_val_18)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_19)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_20)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_31)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_32)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_33)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_34)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_35)s), ''), 'null'), '^"|"$', ''), %(hogql_val_36)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_37)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_38)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_39)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_40)s, %(hogql_val_41)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_42)s, 6, %(hogql_val_43)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_44)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS d
- WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
- GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
- WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (
- SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
- FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (
- SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key
- FROM per_conversion_path
- WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)
- GROUP BY per_conversion_path.path), paths_footer AS (
- SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key
- FROM per_conversion_path)
- SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key
- FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)
- ORDER BY conversions DESC, path ASC
- LIMIT 51
- OFFSET 0
- SETTINGS load_balancing='in_order'
- '''
-# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_4_cached_source
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_20)s)), `$start_timestamp`, %(hogql_val_21)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_22)s)), %(hogql_val_23)s, %(hogql_val_24)s, %(hogql_val_25)s, %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s) AS dimensions, now64(6, %(hogql_val_29)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_16)s), %(hogql_val_17)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_18)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_19)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_30)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_31)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_32)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_33)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_34)s), ''), 'null'), '^"|"$', ''), %(hogql_val_35)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_36)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_37)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_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)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_43)s)), cached_sessions.utm_source, %(hogql_val_44)s)), [%(hogql_val_45)s, %(hogql_val_46)s, %(hogql_val_47)s]), %(hogql_val_48)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_49)s)), cached_sessions.utm_source, %(hogql_val_50)s)), [%(hogql_val_51)s, %(hogql_val_52)s, %(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, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_60)s)), cached_sessions.utm_source, %(hogql_val_61)s)), [%(hogql_val_62)s]), %(hogql_val_63)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_64)s)), cached_sessions.utm_source, %(hogql_val_65)s)), [%(hogql_val_66)s, %(hogql_val_67)s, %(hogql_val_68)s, %(hogql_val_69)s, %(hogql_val_70)s, %(hogql_val_71)s, %(hogql_val_72)s, %(hogql_val_73)s, %(hogql_val_74)s]), %(hogql_val_75)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_76)s)), cached_sessions.utm_source, %(hogql_val_77)s)), [%(hogql_val_78)s]), %(hogql_val_79)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_80)s)), cached_sessions.utm_source, %(hogql_val_81)s)), [%(hogql_val_82)s, %(hogql_val_83)s]), %(hogql_val_84)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_85)s)), cached_sessions.utm_source, %(hogql_val_86)s)), [%(hogql_val_87)s, %(hogql_val_88)s, %(hogql_val_89)s]), %(hogql_val_90)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_91)s)), cached_sessions.utm_source, %(hogql_val_92)s)), [%(hogql_val_93)s]), %(hogql_val_94)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_95)s)), cached_sessions.utm_source, %(hogql_val_96)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS d
- WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
- GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
- WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (
- SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
- FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (
- SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key
- FROM per_conversion_path
- WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)
- GROUP BY per_conversion_path.path), paths_footer AS (
- SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key
- FROM per_conversion_path)
- SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key
- FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)
- ORDER BY conversions DESC, path ASC
- LIMIT 51
- OFFSET 0
- SETTINGS load_balancing='in_order'
- '''
-# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_5_cached_channel
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), web_sessions_dimensional_preaggregated.channel_type, %(hogql_val_5)s, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_137)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_138)s)), `$channel_type`, %(hogql_val_139)s), %(hogql_val_140)s, %(hogql_val_141)s, %(hogql_val_142)s, %(hogql_val_143)s, %(hogql_val_144)s, %(hogql_val_145)s, %(hogql_val_146)s) AS dimensions, now64(6, %(hogql_val_147)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_16)s), %(hogql_val_17)s), %(hogql_val_18)s), %(hogql_val_19)s)), %(hogql_val_20)s), %(hogql_val_21)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_22)s), %(hogql_val_23)s), %(hogql_val_24)s), %(hogql_val_25)s)), tuple(%(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s, %(hogql_val_30)s, %(hogql_val_31)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s), %(hogql_val_35)s)), %(hogql_val_36)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_37)s), %(hogql_val_38)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_47)s), %(hogql_val_48)s), %(hogql_val_49)s), %(hogql_val_50)s)), %(hogql_val_51)s), %(hogql_val_52)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), %(hogql_val_56)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_59)s), %(hogql_val_60)s), %(hogql_val_61)s), %(hogql_val_62)s), %(hogql_val_63)s), 0), %(hogql_val_64)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_65)s), %(hogql_val_66)s), %(hogql_val_67)s), %(hogql_val_68)s)), %(hogql_val_69)s), %(hogql_val_70)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_71)s), %(hogql_val_72)s)), %(hogql_val_73)s, %(hogql_val_74)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_82)s), %(hogql_val_83)s), %(hogql_val_84)s), %(hogql_val_85)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_86)s), %(hogql_val_87)s), %(hogql_val_88)s), %(hogql_val_89)s)), tuple(%(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_93)s), %(hogql_val_94)s)))), %(hogql_val_95)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_100)s), %(hogql_val_101)s), %(hogql_val_102)s), %(hogql_val_103)s)), %(hogql_val_104)s), %(hogql_val_105)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_106)s), %(hogql_val_107)s), %(hogql_val_108)s), %(hogql_val_109)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_112)s), %(hogql_val_113)s), %(hogql_val_114)s), %(hogql_val_115)s)), %(hogql_val_116)s), %(hogql_val_117)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_118)s), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s)), %(hogql_val_122)s), %(hogql_val_123)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_124)s), %(hogql_val_125)s)), %(hogql_val_126)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_127)s), %(hogql_val_128)s), %(hogql_val_129)s), 0), %(hogql_val_130)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_131)s), %(hogql_val_132)s)), %(hogql_val_133)s, %(hogql_val_134)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_135)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_136)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_148)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_149)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_150)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_151)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_152)s), ''), 'null'), '^"|"$', ''), %(hogql_val_153)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_154)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_155)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_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)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_161)s)), cached_sessions.channel_type, %(hogql_val_162)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS d
- WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
- GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
- WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (
- SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
- FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (
- SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key
- FROM per_conversion_path
- WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)
- GROUP BY per_conversion_path.path), paths_footer AS (
- SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key
- FROM per_conversion_path)
- SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key
- FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)
- ORDER BY conversions DESC, path ASC
- LIMIT 51
- OFFSET 0
- SETTINGS load_balancing='in_order'
- '''
-# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_6_shared_campaign
+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_3_shared_campaign
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -422,7 +197,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_7_shared_source
+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_4_shared_source
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -491,7 +266,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_8_shared_channel
+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_5_shared_channel
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambr
index 74484741104d..156c59a9a61e 100644
--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambr
+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_paths_query_runner.new_events_schema.ambr
@@ -128,232 +128,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_3_cached_campaign[new_events_schema]
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, web_sessions_dimensional_preaggregated.utm_campaign, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_11)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_12)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_21)s)), `$start_timestamp`, %(hogql_val_22)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_23)s)), %(hogql_val_24)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_25)s)), %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s) AS dimensions, now64(6, %(hogql_val_30)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_13)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_14)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_15)s), %(hogql_val_16)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_17)s), %(hogql_val_18)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_19)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_20)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_31)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_32)s)) AS max_event_timestamp, count() AS pageview_count
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_33)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_34)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_35)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_36)s))) AS last_conversion
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_37)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_38)s, %(hogql_val_39)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_40)s, 6, %(hogql_val_41)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_42)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS d
- WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
- GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
- WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (
- SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
- FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (
- SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key
- FROM per_conversion_path
- WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)
- GROUP BY per_conversion_path.path), paths_footer AS (
- SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key
- FROM per_conversion_path)
- SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key
- FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)
- ORDER BY conversions DESC, path ASC
- LIMIT 51
- OFFSET 0
- SETTINGS load_balancing='in_order'
- '''
-# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_4_cached_source[new_events_schema]
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_20)s)), `$start_timestamp`, %(hogql_val_21)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_22)s)), %(hogql_val_23)s, %(hogql_val_24)s, %(hogql_val_25)s, %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s) AS dimensions, now64(6, %(hogql_val_29)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_16)s), %(hogql_val_17)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_18)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_19)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_30)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_31)s)) AS max_event_timestamp, count() AS pageview_count
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_32)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_33)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_34)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_35)s))) AS last_conversion
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_36)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_37)s, %(hogql_val_38)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_39)s, 6, %(hogql_val_40)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_41)s)), cached_sessions.utm_source, %(hogql_val_42)s)), [%(hogql_val_43)s, %(hogql_val_44)s, %(hogql_val_45)s]), %(hogql_val_46)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_47)s)), cached_sessions.utm_source, %(hogql_val_48)s)), [%(hogql_val_49)s, %(hogql_val_50)s, %(hogql_val_51)s, %(hogql_val_52)s, %(hogql_val_53)s, %(hogql_val_54)s, %(hogql_val_55)s, %(hogql_val_56)s]), %(hogql_val_57)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_58)s)), cached_sessions.utm_source, %(hogql_val_59)s)), [%(hogql_val_60)s]), %(hogql_val_61)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_62)s)), cached_sessions.utm_source, %(hogql_val_63)s)), [%(hogql_val_64)s, %(hogql_val_65)s, %(hogql_val_66)s, %(hogql_val_67)s, %(hogql_val_68)s, %(hogql_val_69)s, %(hogql_val_70)s, %(hogql_val_71)s, %(hogql_val_72)s]), %(hogql_val_73)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_74)s)), cached_sessions.utm_source, %(hogql_val_75)s)), [%(hogql_val_76)s]), %(hogql_val_77)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_78)s)), cached_sessions.utm_source, %(hogql_val_79)s)), [%(hogql_val_80)s, %(hogql_val_81)s]), %(hogql_val_82)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_83)s)), cached_sessions.utm_source, %(hogql_val_84)s)), [%(hogql_val_85)s, %(hogql_val_86)s, %(hogql_val_87)s]), %(hogql_val_88)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_89)s)), cached_sessions.utm_source, %(hogql_val_90)s)), [%(hogql_val_91)s]), %(hogql_val_92)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_93)s)), cached_sessions.utm_source, %(hogql_val_94)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS d
- WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
- GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
- WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (
- SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
- FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (
- SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key
- FROM per_conversion_path
- WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)
- GROUP BY per_conversion_path.path), paths_footer AS (
- SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key
- FROM per_conversion_path)
- SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key
- FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)
- ORDER BY conversions DESC, path ASC
- LIMIT 51
- OFFSET 0
- SETTINGS load_balancing='in_order'
- '''
-# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_5_cached_channel[new_events_schema]
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), web_sessions_dimensional_preaggregated.channel_type, %(hogql_val_5)s, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_137)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_138)s)), `$channel_type`, %(hogql_val_139)s), %(hogql_val_140)s, %(hogql_val_141)s, %(hogql_val_142)s, %(hogql_val_143)s, %(hogql_val_144)s, %(hogql_val_145)s, %(hogql_val_146)s) AS dimensions, now64(6, %(hogql_val_147)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_16)s), %(hogql_val_17)s), %(hogql_val_18)s), %(hogql_val_19)s)), %(hogql_val_20)s), %(hogql_val_21)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_22)s), %(hogql_val_23)s), %(hogql_val_24)s), %(hogql_val_25)s)), tuple(%(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s, %(hogql_val_30)s, %(hogql_val_31)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s), %(hogql_val_35)s)), %(hogql_val_36)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_37)s), %(hogql_val_38)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_47)s), %(hogql_val_48)s), %(hogql_val_49)s), %(hogql_val_50)s)), %(hogql_val_51)s), %(hogql_val_52)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), %(hogql_val_56)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_59)s), %(hogql_val_60)s), %(hogql_val_61)s), %(hogql_val_62)s), %(hogql_val_63)s), 0), %(hogql_val_64)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_65)s), %(hogql_val_66)s), %(hogql_val_67)s), %(hogql_val_68)s)), %(hogql_val_69)s), %(hogql_val_70)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_71)s), %(hogql_val_72)s)), %(hogql_val_73)s, %(hogql_val_74)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_82)s), %(hogql_val_83)s), %(hogql_val_84)s), %(hogql_val_85)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_86)s), %(hogql_val_87)s), %(hogql_val_88)s), %(hogql_val_89)s)), tuple(%(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_93)s), %(hogql_val_94)s)))), %(hogql_val_95)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_100)s), %(hogql_val_101)s), %(hogql_val_102)s), %(hogql_val_103)s)), %(hogql_val_104)s), %(hogql_val_105)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_106)s), %(hogql_val_107)s), %(hogql_val_108)s), %(hogql_val_109)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_112)s), %(hogql_val_113)s), %(hogql_val_114)s), %(hogql_val_115)s)), %(hogql_val_116)s), %(hogql_val_117)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_118)s), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s)), %(hogql_val_122)s), %(hogql_val_123)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_124)s), %(hogql_val_125)s)), %(hogql_val_126)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_127)s), %(hogql_val_128)s), %(hogql_val_129)s), 0), %(hogql_val_130)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_131)s), %(hogql_val_132)s)), %(hogql_val_133)s, %(hogql_val_134)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_135)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_136)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_148)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_149)s)) AS max_event_timestamp, count() AS pageview_count
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_150)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_151)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_152)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_153)s))) AS last_conversion
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_154)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_155)s, %(hogql_val_156)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_157)s, 6, %(hogql_val_158)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_159)s)), cached_sessions.channel_type, %(hogql_val_160)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS d
- WHERE and(ifNull(greaterOrEquals(d.session_ts, minus(d.first_conversion, 345600)), 0), ifNull(lessOrEquals(d.session_ts, d.upper_bound), 0))
- GROUP BY d.person_id) AS t ON equals(c.conv_person_id, t.person_id)
- WHERE ifNull(greater(length(c.conversions), 0), 0)), per_conversion_path AS MATERIALIZED (
- SELECT i, person_arrays.conversion_count AS conversion_count, (person_arrays.conversions[i]).2 AS conv_value, arrayFilter(t -> and(ifNull(lessOrEquals(t.1, (person_arrays.conversions[i]).1), 0), ifNull(greaterOrEquals(t.1, minus((person_arrays.conversions[i]).1, 345600)), 0)), person_arrays.touchpoints) AS tps, arrayMap(t -> t.2, tps) AS path_full, length(path_full) AS orig_len, arraySlice(path_full, -10) AS path, ifNull(greater(orig_len, 10), 0) AS truncated
- FROM person_arrays ARRAY JOIN arrayEnumerate(person_arrays.conversions) AS i), path_rows AS (
- SELECT per_conversion_path.path AS path, count() AS conversions, sum(per_conversion_path.conv_value) AS conversion_value, max(per_conversion_path.truncated) AS path_truncated, 1 AS footer_key
- FROM per_conversion_path
- WHERE ifNull(greater(per_conversion_path.orig_len, 0), 0)
- GROUP BY per_conversion_path.path), paths_footer AS (
- SELECT sumIf(per_conversion_path.conversion_count, ifNull(equals(per_conversion_path.i, 1), 0)) AS total_conversions, countIf(ifNull(greater(per_conversion_path.orig_len, 0), 0)) AS attributed_conversions, 1 AS footer_key
- FROM per_conversion_path)
- SELECT path_rows.path AS path, path_rows.conversions AS conversions, path_rows.conversion_value AS conversion_value, path_rows.path_truncated AS path_truncated, paths_footer.total_conversions AS total_conversions, paths_footer.attributed_conversions AS attributed_conversions, path_rows.footer_key AS footer_key
- FROM paths_footer LEFT JOIN path_rows ON equals(paths_footer.footer_key, path_rows.footer_key)
- ORDER BY conversions DESC, path ASC
- LIMIT 51
- OFFSET 0
- SETTINGS load_balancing='in_order'
- '''
-# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_6_shared_campaign[new_events_schema]
+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_3_shared_campaign[new_events_schema]
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -422,7 +197,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_7_shared_source[new_events_schema]
+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_4_shared_source[new_events_schema]
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -491,7 +266,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_8_shared_channel[new_events_schema]
+# name: TestMarketingAnalyticsAttributionPathsQueryRunner.test_attribution_paths_sql_5_shared_channel[new_events_schema]
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
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 b0915710a85e..d209e3b1abbe 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
@@ -188,268 +188,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_0_campaign
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, web_sessions_dimensional_preaggregated.utm_campaign, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_11)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_12)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_21)s)), `$start_timestamp`, %(hogql_val_22)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_23)s)), %(hogql_val_24)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_25)s)), %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s) AS dimensions, now64(6, %(hogql_val_30)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_13)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_14)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_15)s), %(hogql_val_16)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_17)s), %(hogql_val_18)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_19)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_20)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_31)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_32)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_33)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_34)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_35)s), ''), 'null'), '^"|"$', ''), %(hogql_val_36)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_37)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_38)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_39)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_40)s, %(hogql_val_41)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_42)s, 6, %(hogql_val_43)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
- SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
- FROM (
- SELECT cached_sessions.person_id AS person_id, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_44)s)) AS breakdown_value
- FROM resolved_cached_sessions AS cached_sessions
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s
- GROUP BY s.breakdown_value), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_45)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) 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_46)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_47)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_48)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_49)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 session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_20)s)), `$start_timestamp`, %(hogql_val_21)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_22)s)), %(hogql_val_23)s, %(hogql_val_24)s, %(hogql_val_25)s, %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s) AS dimensions, now64(6, %(hogql_val_29)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_16)s), %(hogql_val_17)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_18)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_19)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_30)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_31)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_32)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_33)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_34)s), ''), 'null'), '^"|"$', ''), %(hogql_val_35)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_36)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_37)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_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)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
- SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
- FROM (
- SELECT cached_sessions.person_id AS person_id, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_43)s)), cached_sessions.utm_source, %(hogql_val_44)s)), [%(hogql_val_45)s, %(hogql_val_46)s, %(hogql_val_47)s]), %(hogql_val_48)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_49)s)), cached_sessions.utm_source, %(hogql_val_50)s)), [%(hogql_val_51)s, %(hogql_val_52)s, %(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, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_60)s)), cached_sessions.utm_source, %(hogql_val_61)s)), [%(hogql_val_62)s]), %(hogql_val_63)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_64)s)), cached_sessions.utm_source, %(hogql_val_65)s)), [%(hogql_val_66)s, %(hogql_val_67)s, %(hogql_val_68)s, %(hogql_val_69)s, %(hogql_val_70)s, %(hogql_val_71)s, %(hogql_val_72)s, %(hogql_val_73)s, %(hogql_val_74)s]), %(hogql_val_75)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_76)s)), cached_sessions.utm_source, %(hogql_val_77)s)), [%(hogql_val_78)s]), %(hogql_val_79)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_80)s)), cached_sessions.utm_source, %(hogql_val_81)s)), [%(hogql_val_82)s, %(hogql_val_83)s]), %(hogql_val_84)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_85)s)), cached_sessions.utm_source, %(hogql_val_86)s)), [%(hogql_val_87)s, %(hogql_val_88)s, %(hogql_val_89)s]), %(hogql_val_90)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_91)s)), cached_sessions.utm_source, %(hogql_val_92)s)), [%(hogql_val_93)s]), %(hogql_val_94)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_95)s)), cached_sessions.utm_source, %(hogql_val_96)s))))))))) AS breakdown_value
- FROM resolved_cached_sessions AS cached_sessions
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s
- GROUP BY s.breakdown_value), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_97)s)), cached_sessions.utm_source, %(hogql_val_98)s)), [%(hogql_val_99)s, %(hogql_val_100)s, %(hogql_val_101)s]), %(hogql_val_102)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_103)s)), cached_sessions.utm_source, %(hogql_val_104)s)), [%(hogql_val_105)s, %(hogql_val_106)s, %(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, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_114)s)), cached_sessions.utm_source, %(hogql_val_115)s)), [%(hogql_val_116)s]), %(hogql_val_117)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_118)s)), cached_sessions.utm_source, %(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, %(hogql_val_127)s, %(hogql_val_128)s]), %(hogql_val_129)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_130)s)), cached_sessions.utm_source, %(hogql_val_131)s)), [%(hogql_val_132)s]), %(hogql_val_133)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_134)s)), cached_sessions.utm_source, %(hogql_val_135)s)), [%(hogql_val_136)s, %(hogql_val_137)s]), %(hogql_val_138)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_139)s)), cached_sessions.utm_source, %(hogql_val_140)s)), [%(hogql_val_141)s, %(hogql_val_142)s, %(hogql_val_143)s]), %(hogql_val_144)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_145)s)), cached_sessions.utm_source, %(hogql_val_146)s)), [%(hogql_val_147)s]), %(hogql_val_148)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_149)s)), cached_sessions.utm_source, %(hogql_val_150)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) 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_151)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_152)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_153)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_154)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 session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), web_sessions_dimensional_preaggregated.channel_type, %(hogql_val_5)s, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_137)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_138)s)), `$channel_type`, %(hogql_val_139)s), %(hogql_val_140)s, %(hogql_val_141)s, %(hogql_val_142)s, %(hogql_val_143)s, %(hogql_val_144)s, %(hogql_val_145)s, %(hogql_val_146)s) AS dimensions, now64(6, %(hogql_val_147)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_16)s), %(hogql_val_17)s), %(hogql_val_18)s), %(hogql_val_19)s)), %(hogql_val_20)s), %(hogql_val_21)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_22)s), %(hogql_val_23)s), %(hogql_val_24)s), %(hogql_val_25)s)), tuple(%(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s, %(hogql_val_30)s, %(hogql_val_31)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s), %(hogql_val_35)s)), %(hogql_val_36)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_37)s), %(hogql_val_38)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_47)s), %(hogql_val_48)s), %(hogql_val_49)s), %(hogql_val_50)s)), %(hogql_val_51)s), %(hogql_val_52)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), %(hogql_val_56)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_59)s), %(hogql_val_60)s), %(hogql_val_61)s), %(hogql_val_62)s), %(hogql_val_63)s), 0), %(hogql_val_64)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_65)s), %(hogql_val_66)s), %(hogql_val_67)s), %(hogql_val_68)s)), %(hogql_val_69)s), %(hogql_val_70)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_71)s), %(hogql_val_72)s)), %(hogql_val_73)s, %(hogql_val_74)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_82)s), %(hogql_val_83)s), %(hogql_val_84)s), %(hogql_val_85)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_86)s), %(hogql_val_87)s), %(hogql_val_88)s), %(hogql_val_89)s)), tuple(%(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_93)s), %(hogql_val_94)s)))), %(hogql_val_95)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_100)s), %(hogql_val_101)s), %(hogql_val_102)s), %(hogql_val_103)s)), %(hogql_val_104)s), %(hogql_val_105)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_106)s), %(hogql_val_107)s), %(hogql_val_108)s), %(hogql_val_109)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_112)s), %(hogql_val_113)s), %(hogql_val_114)s), %(hogql_val_115)s)), %(hogql_val_116)s), %(hogql_val_117)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_118)s), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s)), %(hogql_val_122)s), %(hogql_val_123)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_124)s), %(hogql_val_125)s)), %(hogql_val_126)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_127)s), %(hogql_val_128)s), %(hogql_val_129)s), 0), %(hogql_val_130)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_131)s), %(hogql_val_132)s)), %(hogql_val_133)s, %(hogql_val_134)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_135)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_136)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_148)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_149)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_150)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_151)s)), coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_152)s), ''), 'null'), '^"|"$', ''), %(hogql_val_153)s), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_154)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_155)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_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)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
- SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
- FROM (
- SELECT cached_sessions.person_id AS person_id, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_161)s)), cached_sessions.channel_type, %(hogql_val_162)s) AS breakdown_value
- FROM resolved_cached_sessions AS cached_sessions
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s
- GROUP BY s.breakdown_value), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_163)s)), cached_sessions.channel_type, %(hogql_val_164)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) 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_165)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_166)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_167)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_168)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_3_live_campaign
+# name: TestMarketingAnalyticsAttributionQueryRunner.test_shared_live_sessions_sql_0_live_campaign
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -530,7 +269,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_4_live_source
+# name: TestMarketingAnalyticsAttributionQueryRunner.test_shared_live_sessions_sql_1_live_source
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -611,7 +350,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_5_live_channel
+# name: TestMarketingAnalyticsAttributionQueryRunner.test_shared_live_sessions_sql_2_live_channel
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT events.`$session_id_uuid` AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambr
index c7ca33a330ed..824ed31ddb51 100644
--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambr
+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_attribution_table_query_runner.new_events_schema.ambr
@@ -188,268 +188,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_0_campaign[new_events_schema]
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, web_sessions_dimensional_preaggregated.utm_campaign, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_11)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_12)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_21)s)), `$start_timestamp`, %(hogql_val_22)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_23)s)), %(hogql_val_24)s, toString(ifNull(`$entry_utm_campaign`, %(hogql_val_25)s)), %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s) AS dimensions, now64(6, %(hogql_val_30)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_13)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_14)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_15)s), %(hogql_val_16)s) AS `$entry_utm_source`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_17)s), %(hogql_val_18)s) AS `$entry_utm_campaign`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_19)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_20)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_31)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_32)s)) AS max_event_timestamp, count() AS pageview_count
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_33)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_34)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_35)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_36)s))) AS last_conversion
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_37)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_38)s, %(hogql_val_39)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_40)s, 6, %(hogql_val_41)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
- SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
- FROM (
- SELECT cached_sessions.person_id AS person_id, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_42)s)) AS breakdown_value
- FROM resolved_cached_sessions AS cached_sessions
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s
- GROUP BY s.breakdown_value), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, toString(ifNull(cached_sessions.utm_campaign, %(hogql_val_43)s)) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) 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_44)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_45)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_46)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_47)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[new_events_schema]
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), %(hogql_val_5)s, web_sessions_dimensional_preaggregated.utm_source, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_20)s)), `$start_timestamp`, %(hogql_val_21)s, toString(ifNull(`$entry_utm_source`, %(hogql_val_22)s)), %(hogql_val_23)s, %(hogql_val_24)s, %(hogql_val_25)s, %(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s) AS dimensions, now64(6, %(hogql_val_29)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_16)s), %(hogql_val_17)s) AS `$entry_utm_source`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_18)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_19)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_30)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_31)s)) AS max_event_timestamp, count() AS pageview_count
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_32)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_33)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_34)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_35)s))) AS last_conversion
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_36)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_37)s, %(hogql_val_38)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_39)s, 6, %(hogql_val_40)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
- SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
- FROM (
- SELECT cached_sessions.person_id AS person_id, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_41)s)), cached_sessions.utm_source, %(hogql_val_42)s)), [%(hogql_val_43)s, %(hogql_val_44)s, %(hogql_val_45)s]), %(hogql_val_46)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_47)s)), cached_sessions.utm_source, %(hogql_val_48)s)), [%(hogql_val_49)s, %(hogql_val_50)s, %(hogql_val_51)s, %(hogql_val_52)s, %(hogql_val_53)s, %(hogql_val_54)s, %(hogql_val_55)s, %(hogql_val_56)s]), %(hogql_val_57)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_58)s)), cached_sessions.utm_source, %(hogql_val_59)s)), [%(hogql_val_60)s]), %(hogql_val_61)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_62)s)), cached_sessions.utm_source, %(hogql_val_63)s)), [%(hogql_val_64)s, %(hogql_val_65)s, %(hogql_val_66)s, %(hogql_val_67)s, %(hogql_val_68)s, %(hogql_val_69)s, %(hogql_val_70)s, %(hogql_val_71)s, %(hogql_val_72)s]), %(hogql_val_73)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_74)s)), cached_sessions.utm_source, %(hogql_val_75)s)), [%(hogql_val_76)s]), %(hogql_val_77)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_78)s)), cached_sessions.utm_source, %(hogql_val_79)s)), [%(hogql_val_80)s, %(hogql_val_81)s]), %(hogql_val_82)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_83)s)), cached_sessions.utm_source, %(hogql_val_84)s)), [%(hogql_val_85)s, %(hogql_val_86)s, %(hogql_val_87)s]), %(hogql_val_88)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_89)s)), cached_sessions.utm_source, %(hogql_val_90)s)), [%(hogql_val_91)s]), %(hogql_val_92)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_93)s)), cached_sessions.utm_source, %(hogql_val_94)s))))))))) AS breakdown_value
- FROM resolved_cached_sessions AS cached_sessions
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s
- GROUP BY s.breakdown_value), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_95)s)), cached_sessions.utm_source, %(hogql_val_96)s)), [%(hogql_val_97)s, %(hogql_val_98)s, %(hogql_val_99)s]), %(hogql_val_100)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_101)s)), cached_sessions.utm_source, %(hogql_val_102)s)), [%(hogql_val_103)s, %(hogql_val_104)s, %(hogql_val_105)s, %(hogql_val_106)s, %(hogql_val_107)s, %(hogql_val_108)s, %(hogql_val_109)s, %(hogql_val_110)s]), %(hogql_val_111)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_112)s)), cached_sessions.utm_source, %(hogql_val_113)s)), [%(hogql_val_114)s]), %(hogql_val_115)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_116)s)), cached_sessions.utm_source, %(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]), %(hogql_val_127)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_128)s)), cached_sessions.utm_source, %(hogql_val_129)s)), [%(hogql_val_130)s]), %(hogql_val_131)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_132)s)), cached_sessions.utm_source, %(hogql_val_133)s)), [%(hogql_val_134)s, %(hogql_val_135)s]), %(hogql_val_136)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_137)s)), cached_sessions.utm_source, %(hogql_val_138)s)), [%(hogql_val_139)s, %(hogql_val_140)s, %(hogql_val_141)s]), %(hogql_val_142)s, if(in(lower(if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_143)s)), cached_sessions.utm_source, %(hogql_val_144)s)), [%(hogql_val_145)s]), %(hogql_val_146)s, if(notEmpty(ifNull(cached_sessions.utm_source, %(hogql_val_147)s)), cached_sessions.utm_source, %(hogql_val_148)s))))))))) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) 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_149)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_150)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_151)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_152)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[new_events_schema]
- '''
- WITH resolved_cached_sessions AS MATERIALIZED (WITH dimensions AS (
- SELECT session_id_v7 AS session_id_v7, latest AS latest, computed_at AS computed_at
- FROM (
- SELECT d.session_id_v7 AS session_id_v7, argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest, max(d.computed_at) AS computed_at
- FROM (
- SELECT web_sessions_dimensional_preaggregated.session_id_v7 AS session_id_v7, tuple(toTimeZone(web_sessions_dimensional_preaggregated.period_bucket, %(hogql_val_3)s), toTimeZone(web_sessions_dimensional_preaggregated.start_timestamp, %(hogql_val_4)s), web_sessions_dimensional_preaggregated.channel_type, %(hogql_val_5)s, %(hogql_val_6)s, %(hogql_val_7)s, %(hogql_val_8)s, %(hogql_val_9)s, %(hogql_val_10)s, %(hogql_val_11)s) AS dimensions, toTimeZone(web_sessions_dimensional_preaggregated.computed_at, %(hogql_val_12)s) AS computed_at, 0 AS source_priority
- FROM web_sessions_dimensional_preaggregated
- WHERE and(equals(web_sessions_dimensional_preaggregated.team_id, 420), in(web_sessions_dimensional_preaggregated.job_id, tuple(%(hogql_val_13)s))) UNION ALL
- SELECT session_id_v7 AS session_id_v7, dimensions AS dimensions, computed_at AS computed_at, source_priority AS source_priority
- FROM (
- SELECT session_id_v7 AS session_id_v7, tuple(toStartOfHour(toTimeZone(`$start_timestamp`, %(hogql_val_137)s)), `$start_timestamp`, if(notEmpty(ifNull(`$channel_type`, %(hogql_val_138)s)), `$channel_type`, %(hogql_val_139)s), %(hogql_val_140)s, %(hogql_val_141)s, %(hogql_val_142)s, %(hogql_val_143)s, %(hogql_val_144)s, %(hogql_val_145)s, %(hogql_val_146)s) AS dimensions, now64(6, %(hogql_val_147)s) AS computed_at, 1 AS source_priority
- FROM (
- SELECT min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_14)s)) AS `$start_timestamp`, max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_15)s)) AS `$end_timestamp`, multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_16)s), %(hogql_val_17)s), %(hogql_val_18)s), %(hogql_val_19)s)), %(hogql_val_20)s), %(hogql_val_21)s, or(in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_22)s), %(hogql_val_23)s), %(hogql_val_24)s), %(hogql_val_25)s)), tuple(%(hogql_val_26)s, %(hogql_val_27)s, %(hogql_val_28)s, %(hogql_val_29)s, %(hogql_val_30)s, %(hogql_val_31)s)), startsWith(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_32)s), %(hogql_val_33)s), %(hogql_val_34)s), %(hogql_val_35)s)), %(hogql_val_36)s), isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_gclid), %(hogql_val_37)s), %(hogql_val_38)s)), isNotNull(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_39)s), %(hogql_val_40)s), %(hogql_val_41)s), %(hogql_val_42)s))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_43)s), %(hogql_val_44)s), %(hogql_val_45)s), %(hogql_val_46)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_47)s), %(hogql_val_48)s), %(hogql_val_49)s), %(hogql_val_50)s)), %(hogql_val_51)s), %(hogql_val_52)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_53)s), %(hogql_val_54)s), %(hogql_val_55)s), %(hogql_val_56)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), ''), 'source')) , dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_57)s), %(hogql_val_58)s), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_gad_source), %(hogql_val_59)s), %(hogql_val_60)s), %(hogql_val_61)s), %(hogql_val_62)s), %(hogql_val_63)s), 0), %(hogql_val_64)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_65)s), %(hogql_val_66)s), %(hogql_val_67)s), %(hogql_val_68)s)), %(hogql_val_69)s), %(hogql_val_70)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_71)s), %(hogql_val_72)s)), %(hogql_val_73)s, %(hogql_val_74)s)), and(ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_75)s), %(hogql_val_76)s), %(hogql_val_77)s), 0), isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_78)s), %(hogql_val_79)s), %(hogql_val_80)s), %(hogql_val_81)s))), or(isNull(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_82)s), %(hogql_val_83)s), %(hogql_val_84)s), %(hogql_val_85)s))), in(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_86)s), %(hogql_val_87)s), %(hogql_val_88)s), %(hogql_val_89)s)), tuple(%(hogql_val_90)s, %(hogql_val_91)s, %(hogql_val_92)s))), not(isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_93)s), %(hogql_val_94)s)))), %(hogql_val_95)s, coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_source), %(hogql_val_96)s), %(hogql_val_97)s), %(hogql_val_98)s), %(hogql_val_99)s)), '')), 'source'))), if(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_100)s), %(hogql_val_101)s), %(hogql_val_102)s), %(hogql_val_103)s)), %(hogql_val_104)s), %(hogql_val_105)s, NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_106)s), %(hogql_val_107)s), %(hogql_val_108)s), %(hogql_val_109)s)), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_110)s), %(hogql_val_111)s), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_campaign), %(hogql_val_112)s), %(hogql_val_113)s), %(hogql_val_114)s), %(hogql_val_115)s)), %(hogql_val_116)s), %(hogql_val_117)s, match(lower(nullIf(nullIf(nullIf(nullIf(argMinMerge(raw_sessions.initial_utm_medium), %(hogql_val_118)s), %(hogql_val_119)s), %(hogql_val_120)s), %(hogql_val_121)s)), %(hogql_val_122)s), %(hogql_val_123)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_fbclid), %(hogql_val_124)s), %(hogql_val_125)s)), %(hogql_val_126)s, ifNull(equals(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_127)s), %(hogql_val_128)s), %(hogql_val_129)s), 0), %(hogql_val_130)s, isNotNull(nullIf(nullIf(argMinMerge(raw_sessions.initial_referring_domain), %(hogql_val_131)s), %(hogql_val_132)s)), %(hogql_val_133)s, %(hogql_val_134)s))) AS `$channel_type`, raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), globalIn(raw_sessions.session_id_v7, (
- SELECT DISTINCT raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')), or(and(greaterOrEquals(raw_sessions.max_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), less(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC'))), less(raw_sessions.min_timestamp, toDateTime64(minus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalDay(1)), 6, %(hogql_val_135)s)), greater(raw_sessions.max_timestamp, toDateTime64(plus(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toIntervalSecond(172800)), 6, %(hogql_val_136)s)))))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2022-12-25 00:00:00.000000', 6, 'UTC')), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), toDateTime64('2023-02-03 23:59:59.999999', 6, 'UTC')))
- GROUP BY raw_sessions.session_id_v7
- HAVING and(greaterOrEquals(`$end_timestamp`, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(`$start_timestamp`, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')), or(less(`$start_timestamp`, toDateTime64('2022-12-27 00:00:00.000000', 6, 'UTC')), greater(`$end_timestamp`, plus(`$start_timestamp`, toIntervalSecond(259200)))))))) AS d
- GROUP BY d.session_id_v7)), identities AS (
- SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_148)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_149)s)) AS max_event_timestamp, count() AS pageview_count
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_150)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_0)s) AS min_event_timestamp, toTimeZone(i.max_event_timestamp, %(hogql_val_1)s) AS max_event_timestamp, i.pageview_count AS pageview_count, (d.latest).1 AS period_bucket, (d.latest).2 AS start_timestamp, (d.latest).3 AS channel_type, (d.latest).4 AS utm_source, (d.latest).5 AS utm_medium, (d.latest).6 AS utm_campaign, (d.latest).7 AS utm_term, (d.latest).8 AS utm_content, (d.latest).9 AS referring_domain, (d.latest).10 AS entry_pathname, toTimeZone(d.computed_at, %(hogql_val_2)s) AS computed_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_151)s)), coalesce(accurateCastOrNull(events.properties.revenue, 'Float64'), 0.0)))), -500) AS conversions, count() AS conversion_count, min(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_152)s))) AS first_conversion, max(toUnixTimestamp(toTimeZone(events.timestamp, %(hogql_val_153)s))) AS last_conversion
- FROM events_json AS events LEFT OUTER JOIN (
- SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 420)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0)
- SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 420), equals(events.event, %(hogql_val_154)s), greaterOrEquals(events.timestamp, toDateTime(%(hogql_val_155)s, %(hogql_val_156)s)), lessOrEquals(events.timestamp, toDateTime64(%(hogql_val_157)s, 6, %(hogql_val_158)s)))
- GROUP BY if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)), influenced_reach AS (
- SELECT s.breakdown_value AS breakdown_value, uniq(s.person_id) AS visitors
- FROM (
- SELECT cached_sessions.person_id AS person_id, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_159)s)), cached_sessions.channel_type, %(hogql_val_160)s) AS breakdown_value
- FROM resolved_cached_sessions AS cached_sessions
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) AS s
- GROUP BY s.breakdown_value), person_arrays AS (
- SELECT c.conv_person_id AS person_id, c.conversions AS conversions, c.conversion_count AS conversion_count, t.touchpoints AS touchpoints
- FROM (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.conversions AS conversions, cached_session_conversions.conversion_count AS conversion_count, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS c LEFT JOIN (
- SELECT d.person_id AS person_id, arraySlice(arraySort(groupUniqArray(tuple(d.session_ts, d.session_dim))), -500) AS touchpoints
- FROM (
- SELECT conv.conv_person_id AS person_id, toUnixTimestamp(cached_sessions.start_timestamp) AS session_ts, if(notEmpty(ifNull(cached_sessions.channel_type, %(hogql_val_161)s)), cached_sessions.channel_type, %(hogql_val_162)s) AS session_dim, conv.first_conversion AS first_conversion, conv.last_conversion AS upper_bound
- FROM resolved_cached_sessions AS cached_sessions INNER JOIN (
- SELECT cached_session_conversions.conv_person_id AS conv_person_id, cached_session_conversions.first_conversion AS first_conversion, cached_session_conversions.last_conversion AS last_conversion
- FROM cached_session_conversions) AS conv ON equals(cached_sessions.person_id, conv.conv_person_id)
- WHERE and(greaterOrEquals(cached_sessions.max_event_timestamp, toDateTime64('2022-12-28 00:00:00.000000', 6, 'UTC')), lessOrEquals(cached_sessions.min_event_timestamp, toDateTime64('2023-01-31 23:59:59.999999', 6, 'UTC')))) 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_163)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_164)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_165)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_166)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_3_live_campaign[new_events_schema]
+# name: TestMarketingAnalyticsAttributionQueryRunner.test_shared_live_sessions_sql_0_live_campaign[new_events_schema]
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -530,7 +269,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_4_live_source[new_events_schema]
+# name: TestMarketingAnalyticsAttributionQueryRunner.test_shared_live_sessions_sql_1_live_source[new_events_schema]
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
@@ -611,7 +350,7 @@
OFFSET 0
'''
# ---
-# name: TestMarketingAnalyticsAttributionQueryRunner.test_precomputed_sessions_sql_5_live_channel[new_events_schema]
+# name: TestMarketingAnalyticsAttributionQueryRunner.test_shared_live_sessions_sql_2_live_channel[new_events_schema]
'''
WITH attribution_session_identities AS MATERIALIZED (
SELECT toUInt128(toUUIDOrNull(events.properties.`$session_id`)) AS session_id_v7, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, min(toTimeZone(events.timestamp, %(hogql_val_0)s)) AS min_event_timestamp, max(toTimeZone(events.timestamp, %(hogql_val_1)s)) AS max_event_timestamp, count() AS pageview_count
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
index a1ab660ce19d..e9aae6b4176a 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_base.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py
@@ -258,19 +258,14 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon
def _person_arrays_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
"""The credit side, using shared session resolution when eligible."""
- if self.config.sessions_precomputation_enabled or self.config.live_session_resolution_enabled:
+ if self.config.live_session_resolution_enabled:
from .attribution_sessions_read import build_person_arrays # noqa: PLC0415 (import cycle)
- with self.timings.measure(
- "attribution_live_session_resolution"
- if self.config.live_session_resolution_enabled
- else "attribution_sessions_precompute_credit"
- ):
- precomputed = build_person_arrays(self, date_range)
- if precomputed is not None:
- self._sessions_precompute_used = not self.config.live_session_resolution_enabled
- self._live_session_resolution_used = self.config.live_session_resolution_enabled
- return precomputed
+ with self.timings.measure("attribution_live_session_resolution"):
+ resolved = build_person_arrays(self, date_range)
+ if resolved is not None:
+ self._live_session_resolution_used = True
+ return resolved
return self._build_person_arrays_select(date_range)
def _build_person_arrays_select(self, date_range: QueryDateRange) -> ast.SelectQuery:
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py
index 46cc2a19e411..4ece6b5aaab3 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py
@@ -13,8 +13,6 @@ from posthog.hogql.database.schema.util.uuid import uuid_uint128_expr_to_timesta
from posthog.hogql.database.schema.util.where_clause_extractor import SESSION_BUFFER_DAYS
from posthog.hogql.parser import parse_expr, parse_select
-from .marketing_sessions_precompute import MAX_PRECOMPUTED_SESSION_SECONDS, SESSION_READ_REACHBACK_DAYS
-
if TYPE_CHECKING:
from posthog.schema import HogQLQueryModifiers
@@ -48,9 +46,6 @@ def _raw_dimensions(
start: datetime,
end: datetime,
candidates: ast.SelectQuery,
- *,
- having: ast.Expr | None = None,
- require_valid_start: bool = False,
) -> ast.SelectQuery:
table, timestamp = _raw_session_source(modifiers)
fields = [
@@ -87,7 +82,6 @@ def _raw_dimensions(
),
]
)
- source.having = having
# Empty slots preserve tuple positions without reading unused entry properties.
dimensions: list[ast.Expr] = [
parse_expr("toStartOfHour(toTimeZone($start_timestamp, 'UTC'))"),
@@ -110,111 +104,27 @@ def _raw_dimensions(
placeholders={"source": source, "dimensions": ast.Tuple(exprs=dimensions)},
)
assert isinstance(query, ast.SelectQuery)
- if require_valid_start:
- query.where = parse_expr("toUnixTimestamp($start_timestamp) > 0")
+ query.where = parse_expr("toUnixTimestamp($start_timestamp) > 0")
return query
-def _exceptional_dimensions(
- modifiers: HogQLQueryModifiers, columns: set[str], start: datetime, end: datetime
-) -> ast.SelectQuery:
- table, timestamp = _raw_session_source(modifiers)
- # Use the live join's ID timestamp window so both paths count the same sessions.
- bounds: dict[str, ast.Expr] = {
- "start": ast.Constant(value=start),
- "end": ast.Constant(value=end),
- "reachback": ast.Constant(value=start - timedelta(days=SESSION_READ_REACHBACK_DAYS)),
- "max_seconds": ast.Constant(value=MAX_PRECOMPUTED_SESSION_SECONDS),
- }
- # Split the duration budget around the ID timestamp to keep long sessions even when IDs and first events disagree.
- # An earlier start either has an older ID with overlapping activity or crosses the earlier limit.
- candidates = parse_select(
- """
- SELECT DISTINCT session_id_v7 FROM {table}
- WHERE {timestamp} >= {lower} AND {timestamp} <= {upper}
- AND ((max_timestamp >= {start} AND {timestamp} < {start})
- OR min_timestamp < {timestamp} - toIntervalDay({reachback_days})
- OR max_timestamp > {timestamp} + toIntervalSecond({remaining_budget}))
- """,
- placeholders={
- "table": ast.Field(chain=[table]),
- "timestamp": timestamp,
- "lower": ast.Constant(value=start - timedelta(days=SESSION_BUFFER_DAYS)),
- "upper": ast.Constant(value=end + timedelta(days=SESSION_BUFFER_DAYS)),
- "start": bounds["start"],
- "reachback_days": ast.Constant(value=SESSION_READ_REACHBACK_DAYS),
- "remaining_budget": ast.Constant(
- value=MAX_PRECOMPUTED_SESSION_SECONDS - int(timedelta(days=SESSION_READ_REACHBACK_DAYS).total_seconds())
- ),
- },
- )
- assert isinstance(candidates, ast.SelectQuery)
- having = parse_expr(
- """
- $end_timestamp >= {start} AND $start_timestamp <= {end}
- AND ($start_timestamp < {reachback}
- OR $end_timestamp > $start_timestamp + toIntervalSecond({max_seconds}))
- """,
- placeholders=bounds,
- )
- return _raw_dimensions(modifiers, columns, start, end, candidates, having=having)
-
-
def _live_dimensions(
modifiers: HogQLQueryModifiers, columns: set[str], start: datetime, end: datetime
) -> ast.SelectQuery:
candidates = parse_select("SELECT DISTINCT session_id_v7 FROM attribution_session_identities")
assert isinstance(candidates, ast.SelectQuery)
- return _raw_dimensions(modifiers, columns, start, end, candidates, require_valid_start=True)
+ return _raw_dimensions(modifiers, columns, start, end, candidates)
def session_dimensions(
modifiers: HogQLQueryModifiers,
columns: set[str],
- job_ids: list[str],
start: datetime,
end: datetime,
- *,
- live: bool = False,
) -> ast.SelectQuery:
- if live:
- query = parse_select(
- "SELECT session_id_v7, dimensions AS latest, computed_at FROM {live}",
- placeholders={"live": _live_dimensions(modifiers, columns, start, end)},
- )
- assert isinstance(query, ast.SelectQuery)
- return query
- # A cached session can grow after materialization, so live exceptions must replace its old dimensions.
query = parse_select(
- """
- SELECT d.session_id_v7,
- argMax(d.dimensions, tuple(d.source_priority, d.computed_at)) AS latest,
- max(d.computed_at) AS computed_at
- FROM (
- SELECT session_id_v7,
- {cached_dimensions} AS dimensions,
- computed_at, 0 AS source_priority
- FROM posthog.web_sessions_dimensional_preaggregated
- WHERE job_id IN {jobs}
- UNION ALL
- SELECT * FROM {live}
- ) AS d
- GROUP BY d.session_id_v7
- """,
- placeholders={
- "jobs": ast.Tuple(exprs=[ast.Constant(value=job) for job in job_ids]),
- "cached_dimensions": ast.Tuple(
- exprs=[
- ast.Field(chain=["period_bucket"]),
- ast.Field(chain=["start_timestamp"]),
- *[
- ast.Field(chain=[column]) if column in columns else ast.Constant(value="")
- for column in _DIMENSION_FIELDS
- ],
- ]
- ),
- "live": _exceptional_dimensions(modifiers, columns, start, end),
- },
+ "SELECT session_id_v7, dimensions AS latest, computed_at FROM {live}",
+ placeholders={"live": _live_dimensions(modifiers, columns, start, end)},
)
assert isinstance(query, ast.SelectQuery)
return query
diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
index 867911c0a9f9..9eb29481b727 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
@@ -3,6 +3,7 @@
Stored person IDs can outlive a merge, so identity always comes from events.
"""
+import os
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Optional
@@ -16,38 +17,28 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
from posthog.hogql.visitor import TraversingVisitor
-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_start,
-)
from .attribution_base import MAX_CONVERSIONS_PER_PERSON, MAX_TOUCHPOINTS_PER_PERSON, PERSON_CONVERSION_COUNT
from .attribution_session_dimensions import session_dimensions
from .constants import UNKNOWN_CHANNEL
-from .marketing_lazy_precompute import (
- BACKGROUND_WARMING_TRIGGERS,
- PRECOMPUTE_ONLY_MAX_STALE_SECONDS,
- REVALIDATION_TRIGGER,
- handle_stale_served,
-)
from .session_breakdown_base import UNATTRIBUTED_SESSION_VALUES
if TYPE_CHECKING:
from posthog.schema import HogQLQueryModifiers
+ from posthog.models.team import Team
+
from .attribution_base import AttributionQueryRunnerBase
logger = structlog.get_logger(__name__)
_SESSIONS_CTE = "resolved_cached_sessions"
_CONVERSIONS_CTE = "cached_session_conversions"
+MAX_DISPLAY_DAYS = int(os.getenv("MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS", "90"))
BREAKDOWN_COLUMNS: dict[MarketingAnalyticsAttributionBreakdown, str] = {
MarketingAnalyticsAttributionBreakdown.CHANNEL: "channel_type",
@@ -71,16 +62,16 @@ def _session_table_version(modifiers: "HogQLQueryModifiers") -> SessionTableVers
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 or []):
+ default_modifiers = create_default_modifiers_for_team(runner.team)
+ modifiers = runner.modifiers or default_modifiers
+ if (modifiers.customChannelTypeRules or []) != (default_modifiers.customChannelTypeRules or []):
return "custom_channel_rules_mismatch"
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):
+ if version == SessionTableVersion.V1 or version != _session_table_version(default_modifiers):
return "session_table_version_mismatch"
- if version == SessionTableVersion.V2 and modifiers.sessionsV2JoinMode != writer_modifiers.sessionsV2JoinMode:
+ if version == SessionTableVersion.V2 and modifiers.sessionsV2JoinMode != default_modifiers.sessionsV2JoinMode:
return "session_join_mode_mismatch"
return None
@@ -102,8 +93,16 @@ class _SessionConversionVisitor(TraversingVisitor):
super().visit_call(node)
+def earliest_session_start(team: "Team", end: datetime) -> datetime:
+ # Relative display ranges start at local midnight; attribution lookback uses elapsed UTC seconds.
+ display_start = end.astimezone(team.timezone_info).replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(
+ days=MAX_DISPLAY_DAYS
+ )
+ return display_start.astimezone(UTC) - timedelta(days=team.marketing_analytics_config.attribution_window_days)
+
+
def ineligible_reason(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[str]:
- """Why this query cannot read from the precompute, or None if it can.
+ """Why this query cannot use shared live session resolution, 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.
@@ -111,12 +110,11 @@ def ineligible_reason(runner: "AttributionQueryRunnerBase", date_range: QueryDat
if reason := _session_modifiers_reason(runner):
return reason
- if runner.config.live_session_resolution_enabled:
- conversion = _SessionConversionVisitor()
- conversion.visit(runner.conversion_condition)
- if conversion.depends_on_sessions:
- # The separate conversion scan has narrower session-ID bounds than the legacy combined scan.
- return "session_filtered_conversion_goal"
+ conversion = _SessionConversionVisitor()
+ conversion.visit(runner.conversion_condition)
+ if conversion.depends_on_sessions:
+ # The separate conversion scan has narrower session-ID bounds than the legacy combined scan.
+ return "session_filtered_conversion_goal"
if not is_integer_timezone(runner.team.timezone):
# `period_bucket` is an hourly UTC bucket, so a half-hour-offset team's midnight lands
@@ -131,15 +129,14 @@ def ineligible_reason(runner: "AttributionQueryRunnerBase", date_range: QueryDat
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.
+ # Shared session dimensions 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.start - timedelta(days=SESSION_READ_REACHBACK_DAYS) < precompute_window_start(runner.team, read.end):
+ if read.start < earliest_session_start(runner.team, read.end):
return "window_over_max"
return None
@@ -165,54 +162,18 @@ def window(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) ->
)
-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
-
- if runner.config.live_session_resolution_enabled:
- return []
- read = window(runner, date_range)
- # Materialize from a session's length before the window: the writer files a session under the
- # chunk holding its start, so a session that opened earlier and ran into the window lives in
- # 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(PRECOMPUTE_ONLY_MAX_STALE_SECONDS, BACKGROUND_WARMING_TRIGGERS)
- # 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
- 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 _eligible(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> bool:
+ # Reach and credit must share a source so their conversion-rate denominator stays consistent.
+ if runner._live_session_resolution_eligible is None:
+ try:
+ reason = ineligible_reason(runner, date_range)
+ runner._live_session_resolution_eligible = reason is None
+ if reason is not None:
+ logger.info("attribution_live_session_resolution_ineligible", team_id=runner.team.pk, reason=reason)
+ except Exception:
+ logger.exception("attribution_live_session_resolution_failed", team_id=runner.team.pk)
+ runner._live_session_resolution_eligible = False
+ return runner._live_session_resolution_eligible
def _session_identities(start: datetime, end: datetime) -> ast.SelectQuery:
@@ -233,9 +194,7 @@ def _session_identities(start: datetime, end: datetime) -> ast.SelectQuery:
return query
-def _read_sessions(
- dimensions: ast.SelectQuery, start: datetime, end: datetime, *, live: bool = False
-) -> ast.SelectQuery:
+def _read_sessions(dimensions: ast.SelectQuery) -> ast.SelectQuery:
query = parse_select(
"""
WITH dimensions AS (SELECT * FROM {dimensions}), identities AS ({identities})
@@ -249,11 +208,7 @@ def _read_sessions(
""",
placeholders={
"dimensions": dimensions,
- "identities": (
- parse_select("SELECT * FROM attribution_session_identities")
- if live
- else _session_identities(start, end)
- ),
+ "identities": parse_select("SELECT * FROM attribution_session_identities"),
},
)
assert isinstance(query, ast.SelectQuery)
@@ -261,7 +216,7 @@ def _read_sessions(
def _scope(read: ReadWindow) -> list[ast.Expr]:
- """Scope to the window by event time; cached dimensions already select the ready job set.
+ """Scope to the window 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
@@ -343,11 +298,9 @@ def _breakdown_expr(runner: "AttributionQueryRunnerBase") -> ast.Expr:
def build_reach(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[ast.SelectQuery]:
- job_ids = _ensure(runner, date_range)
- if job_ids is None:
+ if not _eligible(runner, date_range):
return None
read = window(runner, date_range)
- # The shared CTE has one row per session and current person, including across overlapping jobs.
per_session = ast.SelectQuery(
select=[
ast.Alias(alias="person_id", expr=_field("person_id")),
@@ -374,7 +327,7 @@ def build_reach(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange
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."""
+ so this side stays on `events` while the touchpoint side resolves session dimensions."""
conversions: ast.Expr = ast.Call(
name="groupArray",
args=[
@@ -396,8 +349,7 @@ def _conversions_per_person(runner: "AttributionQueryRunnerBase", date_range: Qu
)
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.
+ # The same ceiling the legacy path applies; otherwise the downstream ARRAY JOINs multiply without bound.
conversions = ast.Call(
name="arraySlice",
args=[
@@ -431,10 +383,9 @@ def _conversions_per_person(runner: "AttributionQueryRunnerBase", date_range: Qu
def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> dict[str, ast.CTE]:
- if not (runner.config.sessions_precomputation_enabled or runner.config.live_session_resolution_enabled):
+ if not runner.config.live_session_resolution_enabled:
return {}
- job_ids = _ensure(runner, date_range)
- if job_ids is None:
+ if not _eligible(runner, date_range):
return {}
read = window(runner, date_range)
columns = {BREAKDOWN_COLUMNS[runner.breakdown]}
@@ -445,20 +396,17 @@ def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRang
dimensions = session_dimensions(
runner.modifiers or create_default_modifiers_for_team(runner.team),
columns,
- job_ids,
read.start,
read.end,
- live=runner.config.live_session_resolution_enabled,
)
- sessions = _read_sessions(dimensions, read.start, read.end, live=runner.config.live_session_resolution_enabled)
+ sessions = _read_sessions(dimensions)
ctes: dict[str, ast.CTE] = {}
- if runner.config.live_session_resolution_enabled:
- ctes["attribution_session_identities"] = ast.CTE(
- name="attribution_session_identities",
- expr=_session_identities(read.start, read.end),
- cte_type="subquery",
- materialized=True,
- )
+ ctes["attribution_session_identities"] = ast.CTE(
+ name="attribution_session_identities",
+ expr=_session_identities(read.start, read.end),
+ cte_type="subquery",
+ materialized=True,
+ )
# Reach and credit share the event scan; conversion bounds share the revenue aggregation.
ctes[_SESSIONS_CTE] = ast.CTE(
name=_SESSIONS_CTE,
@@ -477,8 +425,7 @@ def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRang
def build_person_arrays(runner: "AttributionQueryRunnerBase", date_range: QueryDateRange) -> Optional[ast.SelectQuery]:
"""One row per converting person, with touchpoints from the shared session resolution."""
- job_ids = _ensure(runner, date_range)
- if job_ids is None:
+ if not _eligible(runner, date_range):
return None
read = window(runner, date_range)
@@ -493,19 +440,18 @@ def build_person_arrays(runner: "AttributionQueryRunnerBase", date_range: QueryD
upper = "last_conversion" if runner.allows_multiple_conversions_per_visitor else "first_conversion"
conditions = _scope(read)
- if runner.config.live_session_resolution_enabled:
- # Event and session replicas can lag independently; credit still requires a pageview in the person's window.
- conditions.append(
- ast.CompareOperation(
- left=ast.Call(name="toUnixTimestamp", args=[_field("max_event_timestamp")]),
- op=ast.CompareOperationOp.GtEq,
- right=ast.ArithmeticOperation(
- left=ast.Field(chain=["conv", "first_conversion"]),
- op=ast.ArithmeticOperationOp.Sub,
- right=ast.Constant(value=runner.attribution_window_seconds),
- ),
- )
+ # Event and session replicas can lag independently; credit still requires a pageview in the person's window.
+ conditions.append(
+ ast.CompareOperation(
+ left=ast.Call(name="toUnixTimestamp", args=[_field("max_event_timestamp")]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.ArithmeticOperation(
+ left=ast.Field(chain=["conv", "first_conversion"]),
+ op=ast.ArithmeticOperationOp.Sub,
+ right=ast.Constant(value=runner.attribution_window_seconds),
+ ),
)
+ )
# One conversion-bounds row per person preserves the CTE's unique session/person pairs.
per_session = ast.SelectQuery(
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 5825995dd633..60e5e5f10306 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py
@@ -104,17 +104,12 @@ 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 or self.config.live_session_resolution_enabled:
- with self.timings.measure(
- "attribution_live_session_resolution"
- if self.config.live_session_resolution_enabled
- else "attribution_sessions_precompute"
- ):
- precomputed = build_reach(self, date_range)
- if precomputed is not None:
- self._sessions_precompute_used = not self.config.live_session_resolution_enabled
- self._live_session_resolution_used = self.config.live_session_resolution_enabled
- return precomputed
+ if self.config.live_session_resolution_enabled:
+ with self.timings.measure("attribution_live_session_resolution"):
+ resolved = build_reach(self, date_range)
+ if resolved is not None:
+ self._live_session_resolution_used = True
+ return resolved
breakdown = self._breakdown_expr()
return ast.SelectQuery(
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 876b83b75bd5..0c94dad04304 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
@@ -190,12 +190,8 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
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
self._live_session_resolution_used: bool = False
- # The job set backing this query, resolved once and shared by the reach and credit sides.
- # `resolved` separates "not looked up yet" from "looked up, cannot use the precompute".
- self._sessions_precompute_resolved: bool = False
- self._sessions_precompute_jobs: list[str] | None = None
+ self._live_session_resolution_eligible: bool | 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
@@ -261,7 +257,6 @@ 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,
"live_session_resolution_used": self._live_session_resolution_used,
}
if error is None:
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 914a4d67d6dd..c3d8780d950d 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
@@ -111,7 +111,6 @@ class MarketingAnalyticsConfig:
conversion_goal_precomputation_enabled: bool = False
costs_precomputation_enabled: bool = False
- sessions_precomputation_enabled: bool = False
live_session_resolution_enabled: bool = False
@staticmethod
@@ -154,12 +153,6 @@ 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
@@ -213,7 +206,6 @@ 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"]
config.live_session_resolution_enabled = flags["live_sessions"]
# Gate multi-touch attribution behind its flag; fall back to last-touch when disabled. Evaluated
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py
index 7fe64a7eeb59..56fd9f12e023 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_paths_query_runner.py
@@ -1,8 +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
from parameterized import parameterized
@@ -21,7 +18,6 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.models.utils import uuid7
from posthog.test.persons import create_person
-from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.marketing_analytics.backend.hogql_queries.attribution_paths_query_runner import (
PATH_MAX_LENGTH,
MarketingAnalyticsAttributionPathsQueryRunner,
@@ -409,20 +405,17 @@ class TestMarketingAnalyticsAttributionPathsQueryRunner(ClickhouseTestMixin, Bas
# Same three shapes as the attribution table: direct read, alias normalization, classifier.
@parameterized.expand(
[
- ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, False, False),
- ("source", MarketingAnalyticsAttributionBreakdown.SOURCE, False, False),
- ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, False, False),
- ("cached_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True, False),
- ("cached_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True, False),
- ("cached_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True, False),
- ("shared_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True, True),
- ("shared_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True, True),
- ("shared_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True, True),
+ ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, False),
+ ("source", MarketingAnalyticsAttributionBreakdown.SOURCE, False),
+ ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, False),
+ ("shared_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True),
+ ("shared_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True),
+ ("shared_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True),
]
)
@pytest.mark.usefixtures("unittest_snapshot")
def test_attribution_paths_sql(
- self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown, precomputed: bool, live_resolution: bool
+ self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown, live_resolution: bool
) -> None:
query = MarketingAnalyticsAttributionPathsQuery(
dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
@@ -431,16 +424,10 @@ class TestMarketingAnalyticsAttributionPathsQueryRunner(ClickhouseTestMixin, Bas
properties=[],
)
runner = MarketingAnalyticsAttributionPathsQueryRunner(query=query, team=self.team)
- runner.config.sessions_precomputation_enabled = precomputed
runner.config.live_session_resolution_enabled = live_resolution
context = runner._shared_hogql_context
context.enable_select_queries = True
- with patch(
- "products.marketing_analytics.backend.hogql_queries.attribution_sessions_read.ensure_marketing_sessions_precomputed",
- return_value=LazyComputationResult(ready=True, job_ids=[UUID(int=1)]),
- ):
- printed = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
- assert runner._sessions_precompute_used == (precomputed and not live_resolution)
+ printed = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
assert runner._live_session_resolution_used == live_resolution
sql = printed[0] if isinstance(printed, tuple) else printed
pretty = pretty_print_in_tests(sql, self.team.pk)
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
index 1f7ce50ad555..3f8d4503fb66 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_precompute_parity.py
@@ -8,7 +8,6 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flus
from unittest.mock import patch
from django.conf import settings
-from django.utils import timezone
from parameterized import parameterized
@@ -28,27 +27,17 @@ from posthog.schema import (
from posthog.hogql.escape_sql import escape_clickhouse_identifier
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"
@@ -66,14 +55,7 @@ class _AttributionCounts:
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.
- """
-
+class TestAttributionSessionsParity(ClickhouseTestMixin, BaseTest):
maxDiff = None
CLASS_DATA_LEVEL_SETUP = False
@@ -140,8 +122,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
self,
breakdown: MarketingAnalyticsAttributionBreakdown,
*,
- precomputed: bool,
- live_resolution: bool = False,
+ live_resolution: bool,
exclude_direct: bool = False,
exclude_unattributed: bool = False,
allow_multiple_conversions: bool | None = None,
@@ -158,25 +139,13 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
modifiers=modifiers,
)
runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)
- runner.config.sessions_precomputation_enabled = precomputed
runner.config.live_session_resolution_enabled = live_resolution
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
+ return rows, runner._live_session_resolution_used
@parameterized.expand(
[
@@ -193,9 +162,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
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"])
before_window_minutes = (
30
@@ -223,101 +189,12 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
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)
+ live, live_used = self._run(breakdown, live_resolution=False)
+ shared, shared_used = self._run(breakdown, live_resolution=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}"
- shared, used = self._run(breakdown, precomputed=False, live_resolution=True)
- assert not used
- assert shared == 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
-
- paths_runner = MarketingAnalyticsAttributionPathsQueryRunner(
- query=MarketingAnalyticsAttributionPathsQuery(
- dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
- breakdownBy=MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
- conversionGoalId=GOAL_ID,
- properties=[],
- ),
- team=self.team,
- )
- paths_runner.config.sessions_precomputation_enabled = True
- paths = paths_runner.calculate()
- assert paths_runner._sessions_precompute_used
- assert [(row.path, row.conversions) for row in paths.results] == [(["dup_superseded"], 1)]
+ assert shared_used, "shared live session resolution was not used"
+ assert shared == live, f"shared={shared} legacy={live}"
# Both paths hold their own reference to the ceiling, so both have to be lowered for the fixture
# to stay small enough to read.
@@ -327,9 +204,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
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):
@@ -338,24 +212,20 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
live, live_used = self._run(
MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
- precomputed=False,
+ live_resolution=False,
allow_multiple_conversions=allow_multiple_conversions,
)
- self._materialize()
- pre, pre_used = self._run(
+ shared, shared_used = self._run(
MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
- precomputed=True,
+ live_resolution=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}"
+ assert shared_used, "shared live session resolution was not used"
+ assert shared == live, f"shared={shared} legacy={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"}
]
@@ -375,72 +245,34 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
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)
+ live, live_used = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, live_resolution=False)
+ shared, shared_used = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, live_resolution=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}"
+ assert not shared_used, "shared resolution answered a query whose filter it cannot honor"
+ assert shared == live, f"shared={shared} legacy={live}"
@parameterized.expand([("direct", True, False), ("unattributed", False, True)])
- def test_an_exclusion_judges_the_current_version_of_a_session(
+ def test_exclusions_match_legacy_resolution(
self, _name: str, exclude_direct: bool, exclude_unattributed: bool
) -> 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))
+ create_person(team=self.team, distinct_ids=["excluded-visitor"])
+ self._session("excluded-visitor", datetime(2023, 1, 11, 9, tzinfo=UTC), campaign="", event_offsets_minutes=[0])
+ self._conversion("excluded-visitor", datetime(2023, 1, 12, 12, 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=exclude_direct,
- exclude_unattributed=exclude_unattributed,
- )
- assert used, "the precomputed path was not used, so this proves nothing"
- assert rows == {}, f"an excluded session survived: {rows}"
+ included, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, live_resolution=True)
+ assert used
+ assert included == {"": _AttributionCounts(visitors=1, conversions=1)}
+ for shared in (False, True):
+ rows, used = self._run(
+ MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
+ live_resolution=shared,
+ exclude_direct=exclude_direct,
+ exclude_unattributed=exclude_unattributed,
+ )
+ assert used is shared
+ assert rows == {}
@parameterized.expand(
[
@@ -449,7 +281,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
for before_hours in (48, 120)
]
)
- def test_session_starting_before_reachback_preserves_cached_and_live_reach(
+ def test_session_starting_before_reachback_preserves_reach(
self, version: SessionTableVersion, before_hours: int
) -> None:
self.team.modifiers = {"sessionTableVersion": version}
@@ -467,16 +299,15 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
)
self._conversion("short-session", datetime(2023, 1, 12, 12, tzinfo=UTC))
flush_persons_and_events()
- live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=False)
- self._materialize()
- pre, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
+ live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, live_resolution=False)
+ shared, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, live_resolution=True)
assert used
assert live.get("long") == (_AttributionCounts(visitors=1, conversions=0) if before_hours == 48 else None)
assert live.get("short") == _AttributionCounts(visitors=1, conversions=1)
- assert pre == live
+ assert shared == live
@parameterized.expand([(version,) for version in (SessionTableVersion.V2, SessionTableVersion.V3)])
- def test_custom_channels_match_live_and_rule_changes_invalidate_cache(self, version: SessionTableVersion) -> None:
+ def test_custom_channels_and_rule_changes_match_legacy_resolution(self, version: SessionTableVersion) -> None:
self.team.modifiers = {
"sessionTableVersion": version,
"customChannelTypeRules": [
@@ -508,17 +339,14 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
)
self._conversion(name, datetime(2023, 1, 10, 12, tzinfo=UTC))
flush_persons_and_events()
- original_jobs = self._materialize().job_ids
- for channel, ready in (("Member offer", True), ("Member referral", False), ("Member referral", True)):
+ for channel in ("Member offer", "Member referral"):
self.team.modifiers["customChannelTypeRules"][0]["channel_type"] = channel
- if channel == "Member referral" and ready:
- assert set(self._materialize().job_ids).isdisjoint(original_jobs)
for query_type, runner_type in (
(MarketingAnalyticsAttributionQuery, MarketingAnalyticsAttributionQueryRunner),
(MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),
):
responses = []
- for precomputed, live_resolution in ((False, False), (True, False), (True, True)):
+ for live_resolution in (False, True):
runner = runner_type(
query=query_type(
dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
@@ -528,10 +356,8 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
),
team=self.team,
)
- runner.config.sessions_precomputation_enabled = precomputed
runner.config.live_session_resolution_enabled = live_resolution
response = runner.calculate()
- assert runner._sessions_precompute_used is (precomputed and ready and not live_resolution)
assert runner._live_session_resolution_used is live_resolution
assert response.results
responses.append(response.results)
@@ -542,10 +368,9 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
else:
assert response.attributedConversions == 2
self.assertCountEqual(responses[0], responses[1])
- self.assertCountEqual(responses[0], responses[2])
@parameterized.expand([(SessionTableVersion.V2,), (SessionTableVersion.V3,)])
- def test_long_session_growth_replaces_cached_dimensions(self, version: SessionTableVersion) -> None:
+ def test_long_session_growth_matches_legacy_dimensions(self, version: SessionTableVersion) -> None:
self.team.modifiers = {"sessionTableVersion": version}
create_person(team=self.team, distinct_ids=["growing-session"])
session_id = str(uuid7("2023-01-07T09:00:00Z"))
@@ -557,7 +382,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
properties={"$session_id": session_id, "$current_url": "https://example.com/"},
)
self._conversion("growing-session", datetime(2023, 1, 10, 12, tzinfo=UTC))
- self._materialize()
_create_event(
team=self.team,
distinct_id="growing-session",
@@ -569,50 +393,12 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
"utm_campaign": "late-campaign",
},
)
- live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=False)
- cached, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
+ live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, live_resolution=False)
+ shared, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, live_resolution=True)
assert used
- assert cached == live
+ assert shared == live
expected_campaign = "late-campaign" if version == SessionTableVersion.V3 else ""
- assert cached == {expected_campaign: _AttributionCounts(visitors=1, conversions=1)}
-
- @time_machine.travel("2026-09-11T12:00:00Z", tick=False)
- def test_expired_jobs_are_served_with_grace_and_revalidation_rebuilds_them(self) -> None:
- create_person(team=self.team, distinct_ids=["stale-session"])
- 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)
- )
- live, _ = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=False)
- with 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, "handle_stale_served") as enqueue_after_rebuild:
- fresh, used = self._run(MarketingAnalyticsAttributionBreakdown.CAMPAIGN, precomputed=True)
- assert used
- assert fresh == live
- enqueue_after_rebuild.assert_not_called()
+ assert shared == {expected_campaign: _AttributionCounts(visitors=1, conversions=1)}
@parameterized.expand(
[
@@ -621,7 +407,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
for version in (SessionTableVersion.V2, SessionTableVersion.V3)
]
)
- def test_cached_dimensions_follow_current_event_identity(self, state: str, version: SessionTableVersion) -> None:
+ def test_live_dimensions_follow_current_event_identity(self, state: str, version: SessionTableVersion) -> None:
self.team.modifiers = {
"sessionTableVersion": version,
"personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,
@@ -636,12 +422,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
)
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(
@@ -678,12 +458,10 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
(MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),
):
responses = []
- for precomputed, live_resolution in ((False, False), (True, False), (True, True)):
+ for live_resolution in (False, True):
runner = runner_type(query=query_type(**query_args), team=self.team)
- runner.config.sessions_precomputation_enabled = precomputed
runner.config.live_session_resolution_enabled = live_resolution
response = runner.calculate()
- self.assertEqual(runner._sessions_precompute_used, precomputed and not live_resolution)
self.assertEqual(runner._live_session_resolution_used, live_resolution)
responses.append(response.results)
if isinstance(response, MarketingAnalyticsAttributionQueryResponse):
@@ -692,21 +470,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
else:
self.assertEqual(response.attributedConversions, 0 if state == "mapping_first" else 1)
self.assertCountEqual(responses[0], responses[1])
- self.assertCountEqual(responses[0], responses[2])
-
- stored_after = sync_execute(
- "SELECT * FROM web_sessions_dimensional_preaggregated WHERE team_id = %(team)s ORDER BY session_id_v7",
- {"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(
[
@@ -717,8 +480,8 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
(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
+ def test_query_session_version_matches_live_dimensions(
+ self, team_version: SessionTableVersion, query_version: SessionTableVersion, expected_shared: bool, source: str
) -> None:
self.team.modifiers = {"sessionTableVersion": team_version}
opened_at = datetime(2023, 1, 11, 9, tzinfo=UTC)
@@ -734,12 +497,13 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
)
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)}
+ live, _ = self._run(MarketingAnalyticsAttributionBreakdown.SOURCE, live_resolution=False, modifiers=modifiers)
+ shared, used = self._run(
+ MarketingAnalyticsAttributionBreakdown.SOURCE, live_resolution=True, modifiers=modifiers
+ )
+ assert used is expected_shared
+ assert shared == live == {source: _AttributionCounts(visitors=1, conversions=1)}
@parameterized.expand(["start", "end"])
def test_ambiguous_date_boundary_preserves_live_attribution(self, boundary: str) -> None:
@@ -771,16 +535,12 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
)
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):
+ for live_resolution in (False, True):
runner = runner_type(
query=query_type(
dateRange=date_range,
@@ -790,9 +550,9 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
),
team=self.team,
)
- runner.config.sessions_precomputation_enabled = precomputed
+ runner.config.live_session_resolution_enabled = live_resolution
response = runner.calculate()
- assert not runner._sessions_precompute_used
+ assert not runner._live_session_resolution_used
assert response.totalConversions == 1
responses.append(response.results)
self.assertCountEqual(responses[0], responses[1])
@@ -840,7 +600,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
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,
@@ -852,7 +611,7 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
(MarketingAnalyticsAttributionPathsQuery, MarketingAnalyticsAttributionPathsQueryRunner),
):
results = []
- for precomputed in (False, True):
+ for live_resolution in (False, True):
query = query_type(
dateRange=date_range,
breakdownBy=MarketingAnalyticsAttributionBreakdown.CAMPAIGN,
@@ -860,14 +619,14 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
properties=[],
)
runner = runner_type(query=query, team=self.team)
- runner.config.sessions_precomputation_enabled = precomputed
+ runner.config.live_session_resolution_enabled = live_resolution
response = runner.calculate()
- assert runner._sessions_precompute_used is precomputed
+ assert runner._live_session_resolution_used is live_resolution
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)
+ assert rows == {"reach-only": 1, "boundary": 1, "start": 1}, (live_resolution, rows)
else:
assert response.attributedConversions == expected_conversions
results.append(response.results)
@@ -891,10 +650,8 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
),
team=self.team,
)
- runner.config.sessions_precomputation_enabled = shared
runner.config.live_session_resolution_enabled = shared
response = runner.calculate()
- assert not runner._sessions_precompute_used
assert runner._live_session_resolution_used is shared
assert response.totalConversions == total_conversions
if isinstance(response, MarketingAnalyticsAttributionQueryResponse):
@@ -953,7 +710,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
)
self._conversion("visitor", opened_at + timedelta(hours=1))
flush_persons_and_events()
- self._materialize()
sync_execute(
"""
INSERT INTO raw_sessions_v3
@@ -1063,7 +819,6 @@ class TestAttributionSessionsPrecomputeParity(ClickhouseTestMixin, BaseTest):
),
team=self.team,
)
- runner.config.sessions_precomputation_enabled = False
runner.config.live_session_resolution_enabled = shared
response = runner.calculate()
assert response.totalConversions == 2
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
index de7ebe621ab9..9925e79ebfde 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
@@ -1,5 +1,5 @@
from copy import copy
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, datetime
from uuid import UUID
import time_machine
@@ -25,13 +25,11 @@ from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
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,
)
@@ -42,10 +40,6 @@ from products.marketing_analytics.backend.hogql_queries.attribution_paths_query_
from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
MarketingAnalyticsAttributionQueryRunner,
)
-from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (
- PRECOMPUTE_ONLY_MAX_STALE_SECONDS,
- REVALIDATION_TRIGGER,
-)
class TestAttributionSessionsRead(SimpleTestCase):
@@ -96,15 +90,10 @@ class TestAttributionSessionsRead(SimpleTestCase):
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)
+ runner.config.live_session_resolution_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
@@ -124,7 +113,7 @@ class TestAttributionSessionsRead(SimpleTestCase):
("too_wide", "UTC", "2024-07-05T12:00:00Z", "-91d", None, 30, 90, "window_over_max"),
]
)
- def test_display_window_fits_writer_coverage(
+ def test_display_window_preserves_live_resolution_limit(
self,
_name: str,
timezone: str,
@@ -139,7 +128,7 @@ class TestAttributionSessionsRead(SimpleTestCase):
self.team.marketing_analytics_config.attribution_window_days = lookback
with (
time_machine.travel(now, tick=False),
- patch.object(marketing_sessions_precompute, "PRECOMPUTE_WINDOW_DAYS", display_days),
+ patch.object(attribution_sessions_read, "MAX_DISPLAY_DAYS", display_days),
):
runner = MarketingAnalyticsAttributionQueryRunner(
team=self.team,
@@ -154,53 +143,10 @@ class TestAttributionSessionsRead(SimpleTestCase):
assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) == expected_reason
if expected_reason is None:
read = attribution_sessions_read.window(runner, runner.query_date_range)
- required_start = read.start - timedelta(days=marketing_sessions_precompute.SESSION_READ_REACHBACK_DAYS)
- assert (
- marketing_sessions_precompute.precompute_window_start(self.team, datetime.now(UTC))
- <= required_start
- )
+ required_start = read.start
+ assert attribution_sessions_read.earliest_session_start(self.team, datetime.now(UTC)) <= required_start
- @parameterized.expand(
- [
- ("stale_user", False, True, True),
- ("revalidation", True, False, True),
- ("cold_user", False, False, False),
- ]
- )
- def test_stale_policy_and_revalidation(self, _name: str, 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, "create_default_modifiers_for_team", return_value=runner.modifiers
- ),
- 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"] == (
- None if refreshing else PRECOMPUTE_ONLY_MAX_STALE_SECONDS
- )
- assert revalidate.call_count == int(stale)
-
- def test_failed_precompute_lookup_falls_back(self) -> None:
+ def test_failed_access_rule_lookup_falls_back(self) -> None:
runner = MarketingAnalyticsAttributionQueryRunner(
team=self.team,
modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
@@ -213,8 +159,8 @@ class TestAttributionSessionsRead(SimpleTestCase):
)
with patch.object(
attribution_sessions_read,
- "ensure_marketing_sessions_precomputed",
- side_effect=RuntimeError("Precompute lookup failed"),
+ "team_has_property_access_rules",
+ side_effect=RuntimeError("Access rule lookup failed"),
) as ensure:
assert attribution_sessions_read.build_person_arrays(runner, runner.query_date_range) is None
ensure.assert_called_once()
@@ -252,9 +198,7 @@ class TestAttributionSessionsRead(SimpleTestCase):
),
)
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()
+ assert attribution_sessions_read.build_person_arrays(runner, runner.query_date_range) is None
@parameterized.expand(
[
@@ -313,7 +257,7 @@ class TestAttributionSessionsRead(SimpleTestCase):
):
assert identity() != original
- def test_disabled_reader_does_not_check_jobs_or_session_coverage(self) -> None:
+ def test_disabled_reader_keeps_legacy_resolution(self) -> None:
runner = MarketingAnalyticsAttributionQueryRunner(
team=self.team,
modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
@@ -324,10 +268,10 @@ class TestAttributionSessionsRead(SimpleTestCase):
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()
+ runner.config.live_session_resolution_enabled = False
+ query = runner.to_query()
+ assert "attribution_session_identities" not in (query.ctes or {})
+ assert not runner._live_session_resolution_used
@parameterized.expand(
[
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 048afb41cb39..de4e5740c250 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,5 +1,3 @@
-from uuid import UUID
-
import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
@@ -31,7 +29,6 @@ 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,
@@ -1063,7 +1060,6 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
self,
breakdown: MarketingAnalyticsAttributionBreakdown,
*,
- precomputed: bool = False,
live_resolution: bool = False,
) -> str:
query = MarketingAnalyticsAttributionQuery(
@@ -1073,18 +1069,11 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
properties=[],
)
runner = MarketingAnalyticsAttributionQueryRunner(query=query, team=self.team)
- runner.config.sessions_precomputation_enabled = precomputed
runner.config.live_session_resolution_enabled = live_resolution
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
- 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 and not live_resolution)
+ printed = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
assert runner._live_session_resolution_used == live_resolution
return pretty_print_in_tests(printed[0] if isinstance(printed, tuple) else printed, self.team.pk)
@@ -1103,20 +1092,16 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
printed = self._printed_sql(breakdown)
assert printed == self.sql_snapshot(printed)
- # Entry properties must merge only for exceptional sessions; classifying the full range defeats the cache.
@parameterized.expand(
[
- ("campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, False),
- ("source", MarketingAnalyticsAttributionBreakdown.SOURCE, False),
- ("channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, False),
("live_campaign", MarketingAnalyticsAttributionBreakdown.CAMPAIGN, True),
("live_source", MarketingAnalyticsAttributionBreakdown.SOURCE, True),
("live_channel", MarketingAnalyticsAttributionBreakdown.CHANNEL, True),
]
)
@pytest.mark.usefixtures("unittest_snapshot")
- def test_precomputed_sessions_sql(
+ def test_shared_live_sessions_sql(
self, _name: str, breakdown: MarketingAnalyticsAttributionBreakdown, live_resolution: bool
):
- printed = self._printed_sql(breakdown, precomputed=True, live_resolution=live_resolution)
+ printed = self._printed_sql(breakdown, live_resolution=live_resolution)
assert printed == self.sql_snapshot(printed)