:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(hogql): redesign events predicate pushdown on the lowering architecture (#62239)
Sandy Spicer2a0f0ea100a3
diff --git a/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr b/ee/clickhouse/models/test/__snapshots__/test_cohort.ambrindex 75c20eb61c62..6879d41a8694 100644--- a/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr+++ b/ee/clickhouse/models/test/__snapshots__/test_cohort.ambr@@ -169,7 +169,7 @@cohortpeople.team_id AS team_idFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))+ WHERE and(equals(cohort_people.cohort_id, 99999), equals(cohort_people.team_id, 99999))LIMIT 1000000000))) as person SETTINGS optimize_aggregation_in_order = 1,join_algorithm = 'auto''''@@ -217,7 +217,7 @@cohortpeople.team_id AS team_idFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))+ WHERE and(equals(cohort_people.cohort_id, 99999), equals(cohort_people.team_id, 99999))LIMIT 1000000000))) as person SETTINGS optimize_aggregation_in_order = 1,join_algorithm = 'auto''''@@ -272,7 +272,7 @@cohortpeople.team_id AS team_idFROM cohortpeopleWHERE 0) AS cohort_people- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))))))+ WHERE and(equals(cohort_people.cohort_id, 99999), equals(cohort_people.team_id, 99999))))))LIMIT 1000000000)))'''# ---@@ -399,7 +399,7 @@cohortpeople.team_id AS team_idFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))+ WHERE and(equals(cohort_people.cohort_id, 99999), equals(cohort_people.team_id, 99999))LIMIT 1000000000))) as person SETTINGS optimize_aggregation_in_order = 1,join_algorithm = 'auto''''@@ -447,7 +447,7 @@cohortpeople.team_id AS team_idFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), in(tuple(cohortpeople.cohort_id, cohortpeople.version), [(99999, 0)]))) AS cohort_people- WHERE and(ifNull(equals(cohort_people.cohort_id, 99999), 0), ifNull(equals(cohort_people.team_id, 99999), 0))+ WHERE and(equals(cohort_people.cohort_id, 99999), equals(cohort_people.team_id, 99999))LIMIT 1000000000))) as person SETTINGS optimize_aggregation_in_order = 1,join_algorithm = 'auto''''diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_trends.ambr b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_trends.ambrindex 89ccda041161..8e0a42d562f1 100644--- a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_trends.ambr+++ b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_trends.ambr@@ -145,7 +145,7 @@/* user_id:0 request:_snapshot_ */SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -198,7 +198,7 @@/* user_id:0 request:_snapshot_ */SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -250,11 +250,11 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestamp,breakdown_valueORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')))))GROUP BY day_start,breakdown_valueORDER BY day_start ASC,@@ -284,7 +284,7 @@/* user_id:0 request:_snapshot_ */SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)diff --git a/posthog/hogql/ast.py b/posthog/hogql/ast.pyindex 4bca93ed2835..33b60837eef6 100644--- a/posthog/hogql/ast.py+++ b/posthog/hogql/ast.py@@ -983,6 +983,36 @@ class Tuple(Expr):exprs: list[Expr]+@dataclass(kw_only=True, slots=True)+class PropertyAccess(Expr):+ """The lowered form of a `properties.X` read: "read this key path from this properties field."++ The properties field is treated as an abstract key-value document — how the value is physically served (raw JSON+ extract, materialized column, property-group map) is decided by later passes, never encoded in this node.++ This is what a blob property read becomes after logical lowering. The contrast that matters is with+ `PropertyType`, the read's *type* before lowering. A `PropertyType` means "this is an unresolved property — nobody has+ turned it into anything concrete yet." A `PropertyAccess` is that property **lowered to its concrete pieces**: `expr`+ is the blob column (e.g. `events.properties`), `keys` is the path into it, and the node's own type is the value type of+ the read — a nullable String. It has dropped the "I'm an unresolved property" meaning (it carries *no* `PropertyType`),+ so nothing downstream mistakes it for one and re-runs property logic on it.++ It does **not** decide where the value ultimately comes from. Lowering produces a `PropertyAccess` for *every* blob+ property — a materialized one and a raw one look identical at this stage. On ClickHouse, the next pass (the+ materialized-column / property-group / skip-index physical passes) may rewrite this node to a concrete column read — a+ faster source of the *same* value — when a backing column exists. Raw JSON is only the **default rendering if nothing+ rewrites it**: each printer renders a surviving node mechanically in its own JSON syntax via `visit_property_access`+ (ClickHouse `JSONExtractRaw` + null/quote scrub; Postgres/DuckDB `->`/`->>`) and makes no physical-column decision —+ that is the whole point of this split. For the warehouse dialects there is no second pass, so the node always renders+ as the extract. `keys` mirrors a `PropertyType.chain` —+ string object keys and integer array indices, passed through untyped so each dialect's `_json_property_args` handles+ them just like the legacy `visit_property_type` blob fallback did.+ """++ expr: Expr+ keys: list[str | int]++@dataclass(kw_only=True, slots=True)class Lambda(Expr):args: list[str]@@ -992,6 +1022,13 @@ class Lambda(Expr):@dataclass(kw_only=True, slots=True)class Constant(Expr):value: Any+ # Internal ClickHouse-printer hint, not part of the logical AST. Set True only by the physical pass, only for its+ # fixed scrubbing sentinels (the nullIf ''/'null' literals, the quote-trim regex, the 'true'/'false' the property+ # group stores booleans as), to render them inline instead of as a bound parameter — matching the inline string the+ # `json_extract_trim_quotes` helper emits. The printer enforces a fixed allowlist (`INLINE_SENTINEL_LITERALS`), so it+ # can never inline arbitrary text. Unset (None) by default, like `type`, so the "skip None" AST serializers (Hog+ # compilers, `pretty_dataclasses` snapshots) leave it out.+ inline_sentinel: bool | None = None# Allowlist for `Keyword.name`; the SQL printer interpolates it verbatim (CH returns `name` directly, Postgres uppercases). Restricted to the Postgres-family time pseudo-functions from `resolver.POSTGRES_KEYWORD_TYPES` — a broader `str.isidentifier()` check would still admit arbitrary Python identifiers and let them emit as unquoted ClickHouse tokens.diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_groups_revenue_analytics.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_groups_revenue_analytics.ambrindex 37aed064aea8..c94ededb6947 100644--- a/posthog/hogql/database/schema/test/__snapshots__/test_groups_revenue_analytics.ambr+++ b/posthog/hogql/database/schema/test/__snapshots__/test_groups_revenue_analytics.ambr@@ -175,7 +175,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -212,7 +212,7 @@subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`GROUP BY customer_id) AS mrr_by_customer ON equals(customer_to_group.customer_id, mrr_by_customer.customer_id)GROUP BY group_key) AS mrr_agg ON equals(revenue_agg.group_key, mrr_agg.group_key)) AS groups__revenue_analytics ON equals(groups.groups___key, groups__revenue_analytics.group_key)- WHERE ifNull(equals(groups.key, 'lolol0:xxx'), 0)+ WHERE equals(groups.key, 'lolol0:xxx')LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -254,7 +254,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -659,7 +659,7 @@subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`GROUP BY customer_id) AS mrr_by_customer ON equals(customer_to_group.customer_id, mrr_by_customer.customer_id)GROUP BY group_key) AS mrr_agg ON equals(revenue_agg.group_key, mrr_agg.group_key)) AS groups__revenue_analytics ON equals(groups.groups___key, groups__revenue_analytics.group_key)- WHERE ifNull(equals(groups.key, 'lolol0:xxx'), 0)+ WHERE equals(groups.key, 'lolol0:xxx')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -700,7 +700,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -941,7 +941,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1182,7 +1182,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1423,7 +1423,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1665,7 +1665,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -2049,7 +2049,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -2120,7 +2120,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -2374,7 +2374,7 @@FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`GROUP BY customer_id) AS mrr_by_customer ON equals(customer_to_group.customer_id, mrr_by_customer.customer_id)GROUP BY group_key) AS mrr_agg ON equals(revenue_agg.group_key, mrr_agg.group_key)) AS groups__revenue_analytics ON equals(groups.groups___key, groups__revenue_analytics.group_key)- WHERE ifNull(equals(groups.key, 'lolol0:xxx'), 0)+ WHERE equals(groups.key, 'lolol0:xxx')LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -2487,7 +2487,7 @@FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`GROUP BY customer_id) AS mrr_by_customer ON equals(customer_to_group.customer_id, mrr_by_customer.customer_id)GROUP BY group_key) AS mrr_agg ON equals(revenue_agg.group_key, mrr_agg.group_key)) AS groups__revenue_analytics ON equals(groups.groups___key, groups__revenue_analytics.group_key)- WHERE ifNull(equals(groups.key, 'lolol0:xxx'), 0)+ WHERE equals(groups.key, 'lolol0:xxx')LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambrindex 5b24f29031c5..73d25bc578a8 100644--- a/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr+++ b/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr@@ -129,7 +129,7 @@cohortpeople.cohort_id AS cohort_idFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, persons.id)- WHERE ifNull(equals(__in_cohort.matched, 1), 0)+ WHERE equals(__in_cohort.matched, 1)ORDER BY persons.created_at DESCLIMIT 3 SETTINGS readonly=2,max_execution_time=60,diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambrindex 3456505b352d..9338052ec06d 100644--- a/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambr+++ b/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambr@@ -195,7 +195,7 @@subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))- WHERE ifNull(equals(persons.id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(persons.id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -239,7 +239,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -489,7 +489,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -741,7 +741,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -992,7 +992,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1243,7 +1243,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1495,7 +1495,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1891,7 +1891,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -1967,7 +1967,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -2213,7 +2213,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -2419,7 +2419,7 @@subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))GROUP BY person_id) AS persons_revenue_analytics- WHERE ifNull(equals(persons_revenue_analytics.person_id, toUUIDOrNull('00000000-0000-4000-8000-000000000000')), 0)+ WHERE equals(persons_revenue_analytics.person_id, toUUIDOrNull('00000000-0000-4000-8000-000000000000'))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -2481,18 +2481,18 @@'{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,'{}'), k), JSONExtractKeys(ifNull(inner.metadata,'{}')))), map('posthog_person_distinct_id_source',- 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id,- ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,- '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,- '{}'), k), JSONExtractKeys(ifNull(inner.metadata,- '{}')))), map('posthog_person_distinct_id',- inner.resolved_distinct_id,- 'posthog_person_distinct_id_source',- inner.resolved_source))), inner.metadata)) AS metadata,- inner.country AS country,- inner.cohort AS cohort,- inner.initial_coupon AS initial_coupon,- inner.initial_coupon_id AS initial_coupon_id+ 'customer'))), if(notEquals(inner.resolved_distinct_id,+ ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,+ '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,+ '{}'), k), JSONExtractKeys(ifNull(inner.metadata,+ '{}')))), map('posthog_person_distinct_id',+ inner.resolved_distinct_id,+ 'posthog_person_distinct_id_source',+ inner.resolved_source))), inner.metadata)) AS metadata,+ inner.country AS country,+ inner.cohort AS cohort,+ inner.initial_coupon AS initial_coupon,+ inner.initial_coupon_id AS initial_coupon_idFROM (SELECT outer.id AS id,'stripe.posthog_test' AS source_label,@@ -2884,8 +2884,8 @@GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id,mrr_agg.customer_id))GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))- WHERE ifNull(equals(persons.id,- toUUIDOrNull('00000000-0000-4000-8000-000000000000')), 0)+ WHERE equals(persons.id,+ toUUIDOrNull('00000000-0000-4000-8000-000000000000'))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -2923,7 +2923,7 @@# ---# name: TestPersonsRevenueAnalytics.test_virtual_property_in_trend_0_disabled.1'''- SELECT groupArray(1)(date)[1] AS date, arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total, arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ SELECT groupArray(1)(date)[1] AS date, arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total, arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date, arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total, breakdown_value AS breakdown_value, rowNumberInAllBlocks() AS row_number@@ -3056,7 +3056,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -3275,7 +3275,7 @@# ---# name: TestPersonsRevenueAnalytics.test_virtual_property_in_trend_2_person_id_override_properties_on_events.1'''- SELECT groupArray(1)(date)[1] AS date, arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total, arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ SELECT groupArray(1)(date)[1] AS date, arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total, arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date, arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total, breakdown_value AS breakdown_value, rowNumberInAllBlocks() AS row_number@@ -3394,7 +3394,7 @@# ---# name: TestPersonsRevenueAnalytics.test_virtual_property_in_trend_3_person_id_override_properties_joined.1'''- SELECT groupArray(1)(date)[1] AS date, arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total, arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ SELECT groupArray(1)(date)[1] AS date, arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total, arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date, arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total, breakdown_value AS breakdown_value, rowNumberInAllBlocks() AS row_number@@ -3541,7 +3541,7 @@FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))- WHERE ifNull(equals(persons.id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(persons.id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_session_replay_events.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_session_replay_events.ambrindex 91d7345cfb0d..7786e5628a25 100644--- a/posthog/hogql/database/schema/test/__snapshots__/test_session_replay_events.ambr+++ b/posthog/hogql/database/schema/test/__snapshots__/test_session_replay_events.ambr@@ -11,7 +11,7 @@log_entries.log_source_id AS log_source_idFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries) AS raw_session_replay_events__console_logs ON equals(session_replay_events.session_id, raw_session_replay_events__console_logs.log_source_id)- WHERE and(equals(session_replay_events.team_id, 99999), ifNull(equals(raw_session_replay_events__console_logs.message, 'This is a generic message'), 0))+ WHERE and(equals(session_replay_events.team_id, 99999), equals(raw_session_replay_events__console_logs.message, 'This is a generic message'))ORDER BY session_replay_events.session_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -41,7 +41,7 @@log_entries.log_source_id AS log_source_idFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries) AS raw_session_replay_events__console_logs ON equals(session_replay_events.session_id, raw_session_replay_events__console_logs.log_source_id)- WHERE and(equals(session_replay_events.team_id, 99999), ifNull(equals(raw_session_replay_events__console_logs.message, 'This is a generic message'), 0), ifNull(equals(raw_session_replay_events__console_logs.level, 'error'), 0))+ WHERE and(equals(session_replay_events.team_id, 99999), equals(raw_session_replay_events__console_logs.message, 'This is a generic message'), equals(raw_session_replay_events__console_logs.level, 'error'))ORDER BY session_replay_events.session_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -71,7 +71,7 @@log_entries.log_source_id AS log_source_idFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries) AS raw_session_replay_events__console_logs ON equals(session_replay_events.session_id, raw_session_replay_events__console_logs.log_source_id)- WHERE and(equals(session_replay_events.team_id, 99999), ifNull(equals(raw_session_replay_events__console_logs.level, 'info'), 0))+ WHERE and(equals(session_replay_events.team_id, 99999), equals(raw_session_replay_events__console_logs.level, 'info'))ORDER BY session_replay_events.session_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -96,7 +96,7 @@events.`$session_id` AS `$session_id`FROM events PREWHERE greaterOrEquals(events.timestamp, minus(toDateTime64('today', 6, 'UTC'), toIntervalDay(90)))WHERE equals(events.team_id, 99999)) AS raw_session_replay_events__events ON equals(session_replay_events.session_id, raw_session_replay_events__events.`$session_id`)- WHERE and(equals(session_replay_events.team_id, 99999), ifNull(equals(raw_session_replay_events__events.event, '$pageview'), 0))+ WHERE and(equals(session_replay_events.team_id, 99999), equals(raw_session_replay_events__events.event, '$pageview'))ORDER BY session_replay_events.session_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -240,7 +240,7 @@WHERE equals(person_distinct_id2.team_id, 99999)GROUP BY person_distinct_id2.distinct_idHAVING equals(tupleElement(argMax(tuple(person_distinct_id2.is_deleted), person_distinct_id2.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS raw_session_replay_events__pdi ON equals(session_replay_events.distinct_id, raw_session_replay_events__pdi.distinct_id)- WHERE and(equals(session_replay_events.team_id, 99999), ifNull(equals(raw_session_replay_events__pdi.distinct_id, 'd1'), 0))+ WHERE and(equals(session_replay_events.team_id, 99999), equals(raw_session_replay_events__pdi.distinct_id, 'd1'))ORDER BY session_replay_events.session_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -274,7 +274,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS raw_session_replay_events__pdi__person ON equals(raw_session_replay_events__pdi.raw_session_replay_events__pdi___person_id, raw_session_replay_events__pdi__person.id)- WHERE and(equals(session_replay_events.team_id, 99999), ifNull(equals(raw_session_replay_events__pdi__person.id, toUUIDOrNull('00000000-0000-4000-8000-000000000000')), 0))+ WHERE and(equals(session_replay_events.team_id, 99999), equals(raw_session_replay_events__pdi__person.id, toUUIDOrNull('00000000-0000-4000-8000-000000000000')))ORDER BY session_replay_events.session_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -420,7 +420,7 @@FROM raw_sessionsWHERE equals(raw_sessions.team_id, 99999)GROUP BY raw_sessions.session_id_v7) AS raw_session_replay_events__session ON equals(toUInt128(accurateCastOrNull(session_replay_events.session_id, 'UUID')), raw_session_replay_events__session.session_id_v7)- WHERE and(equals(session_replay_events.team_id, 99999), ifNull(greater(raw_session_replay_events__session.duration, 3600), 0))+ WHERE and(equals(session_replay_events.team_id, 99999), greater(raw_session_replay_events__session.duration, 3600))GROUP BY session_replay_events.session_idHAVING equals(dateDiff('second', min(toTimeZone(session_replay_events.min_first_timestamp, 'UTC')), max(toTimeZone(session_replay_events.max_last_timestamp, 'UTC'))), 3600)ORDER BY session_replay_events.session_id ASC@@ -469,7 +469,7 @@FROM session_replay_eventsWHERE equals(session_replay_events.team_id, 99999)GROUP BY session_replay_events.session_id) AS session_replay_events- WHERE ifNull(equals(session_replay_events.session_id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(session_replay_events.session_id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -493,7 +493,7 @@FROM session_replay_eventsWHERE equals(session_replay_events.team_id, 99999)GROUP BY session_replay_events.session_id) AS session_replay_events- WHERE ifNull(equals(session_replay_events.session_id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(session_replay_events.session_id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -517,7 +517,7 @@FROM session_replay_eventsWHERE equals(session_replay_events.team_id, 99999)GROUP BY session_replay_events.session_id) AS session_replay_events- WHERE ifNull(equals(session_replay_events.session_id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(session_replay_events.session_id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambrindex 792b1d00751c..0e3f59c82e9f 100644--- a/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambr+++ b/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambr@@ -45,7 +45,7 @@FROM raw_sessions_v3WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))GROUP BY raw_sessions_v3.session_id_v7) AS sessions- WHERE ifNull(equals(sessions.session_id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(sessions.session_id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -70,7 +70,7 @@FROM raw_sessions_v3WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))GROUP BY raw_sessions_v3.session_id_v7) AS sessions- WHERE ifNull(equals(sessions.session_id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(sessions.session_id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -99,7 +99,7 @@FROM raw_sessions_v3WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))GROUP BY raw_sessions_v3.session_id_v7) AS sessions- WHERE ifNull(equals(sessions.id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(sessions.id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -206,7 +206,7 @@FROM raw_sessions_v3WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))GROUP BY raw_sessions_v3.session_id_v7) AS sessions- WHERE ifNull(equals(sessions.id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(sessions.id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -231,7 +231,7 @@FROM raw_sessions_v3WHERE equals(raw_sessions_v3.team_id, 99999)GROUP BY raw_sessions_v3.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)- WHERE and(equals(events.team_id, 99999), ifNull(equals(events__session.`$entry_pathname`, '/pathname'), 0))+ WHERE and(equals(events.team_id, 99999), equals(events__session.`$entry_pathname`, '/pathname'))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -256,7 +256,7 @@FROM raw_sessions_v3WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))), greaterOrEquals(raw_sessions_v3.session_timestamp, minus('1970-01-01', toIntervalDay(3))))GROUP BY raw_sessions_v3.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)- WHERE and(equals(events.team_id, 99999), ifNull(equals(session_id, '00000000-0000-0000-0000-000000000000'), 0), greaterOrEquals(events.timestamp, toDateTime64('1970-01-01', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), equals(session_id, '00000000-0000-0000-0000-000000000000'), greaterOrEquals(events.timestamp, toDateTime64('1970-01-01', 6, 'UTC')))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -285,7 +285,7 @@FROM raw_sessions_v3WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))GROUP BY raw_sessions_v3.session_id_v7) AS sessions- WHERE ifNull(equals(sessions.id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(sessions.id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -310,7 +310,7 @@FROM raw_sessions_v3WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))GROUP BY raw_sessions_v3.session_id_v7) AS sessions- WHERE ifNull(equals(sessions.session_id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(sessions.session_id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -571,7 +571,7 @@WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))GROUP BY raw_sessions_v3.session_timestamp,raw_sessions_v3.session_id_v7) AS sessions- WHERE ifNull(equals(sessions.session_id, '00000000-0000-0000-0000-000000000000'), 0)+ WHERE equals(sessions.session_id, '00000000-0000-0000-0000-000000000000')LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -590,8 +590,7 @@'''SELECT events__session.`$channel_type` AS `$channel_type`FROM- (SELECT events.`$session_id` AS `$session_id`,- events.`$session_id_uuid` AS `$session_id_uuid`+ (SELECT events.`$session_id_uuid` AS `$session_id_uuid`FROM eventsWHERE and(equals(events.team_id, 99999), equals(events.`$session_id_uuid`, toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID'))))LIMIT 100) AS eventsdiff --git a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambr b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambrindex 7daf8de98e85..015816a29544 100644--- a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambr+++ b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambr@@ -89,9 +89,9 @@GROUP BYraw_sessions.session_id_v7) AS sessionsWHERE- ifNull(greaterOrEquals(sessions.`$start_timestamp`, %(hogql_val_2)s), 0)) AS subquery+ greaterOrEquals(sessions.`$start_timestamp`, %(hogql_val_2)s)) AS subqueryWHERE- ifNull(equals(subquery.session_id, %(hogql_val_3)s), 0)+ equals(subquery.session_id, %(hogql_val_3)s)LIMIT 50000'''# ---@@ -111,7 +111,7 @@GROUP BYraw_sessions.session_id_v7) AS sessionsWHERE- ifNull(greater(sessions.`$start_timestamp`, %(hogql_val_2)s), 0)+ greater(sessions.`$start_timestamp`, %(hogql_val_2)s)LIMIT 50000'''# ---@@ -120,7 +120,7 @@SELECTcount(DISTINCT e.`$session_id`) AS total,toStartOfDay(toTimeZone(e.timestamp, %(hogql_val_7)s)) AS day_start,- multiIf(and(ifNull(greaterOrEquals(e__session.`$session_duration`, 2.0), 0), ifNull(less(e__session.`$session_duration`, 4.5), 0)), %(hogql_val_8)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 4.5), 0), ifNull(less(e__session.`$session_duration`, 27.0), 0)), %(hogql_val_9)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 27.0), 0), ifNull(less(e__session.`$session_duration`, 44.0), 0)), %(hogql_val_10)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 44.0), 0), ifNull(less(e__session.`$session_duration`, 48.0), 0)), %(hogql_val_11)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 48.0), 0), ifNull(less(e__session.`$session_duration`, 57.5), 0)), %(hogql_val_12)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 57.5), 0), ifNull(less(e__session.`$session_duration`, 61.0), 0)), %(hogql_val_13)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 61.0), 0), ifNull(less(e__session.`$session_duration`, 74.0), 0)), %(hogql_val_14)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 74.0), 0), ifNull(less(e__session.`$session_duration`, 90.0), 0)), %(hogql_val_15)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 90.0), 0), ifNull(less(e__session.`$session_duration`, 98.5), 0)), %(hogql_val_16)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 98.5), 0), ifNull(less(e__session.`$session_duration`, 167.01), 0)), %(hogql_val_17)s, %(hogql_val_18)s) AS breakdown_value+ multiIf(and(greaterOrEquals(e__session.`$session_duration`, 2.0), less(e__session.`$session_duration`, 4.5)), %(hogql_val_8)s, and(greaterOrEquals(e__session.`$session_duration`, 4.5), less(e__session.`$session_duration`, 27.0)), %(hogql_val_9)s, and(greaterOrEquals(e__session.`$session_duration`, 27.0), less(e__session.`$session_duration`, 44.0)), %(hogql_val_10)s, and(greaterOrEquals(e__session.`$session_duration`, 44.0), less(e__session.`$session_duration`, 48.0)), %(hogql_val_11)s, and(greaterOrEquals(e__session.`$session_duration`, 48.0), less(e__session.`$session_duration`, 57.5)), %(hogql_val_12)s, and(greaterOrEquals(e__session.`$session_duration`, 57.5), less(e__session.`$session_duration`, 61.0)), %(hogql_val_13)s, and(greaterOrEquals(e__session.`$session_duration`, 61.0), less(e__session.`$session_duration`, 74.0)), %(hogql_val_14)s, and(greaterOrEquals(e__session.`$session_duration`, 74.0), less(e__session.`$session_duration`, 90.0)), %(hogql_val_15)s, and(greaterOrEquals(e__session.`$session_duration`, 90.0), less(e__session.`$session_duration`, 98.5)), %(hogql_val_16)s, and(greaterOrEquals(e__session.`$session_duration`, 98.5), less(e__session.`$session_duration`, 167.01)), %(hogql_val_17)s, %(hogql_val_18)s) AS breakdown_valueFROMevents AS eLEFT OUTER JOIN (SELECT@@ -190,15 +190,14 @@events__session.`$session_duration` AS durationFROM(SELECT- events.`$session_id_uuid` AS `$session_id_uuid`,- toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ events.`$session_id_uuid` AS `$session_id_uuid`FROMeventsWHEREand(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))LIMIT 50000) AS eventsLEFT JOIN (SELECT- dateDiff(%(hogql_val_1)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_2)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_3)s))) AS `$session_duration`,+ dateDiff(%(hogql_val_0)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`,raw_sessions.session_id_v7 AS session_id_v7FROMraw_sessions@@ -228,7 +227,7 @@GROUP BYraw_sessions.session_id_v7) AS sessionsWHERE- ifNull(greaterOrEquals(sessions.`$start_timestamp`, minus(now64(6, %(hogql_val_2)s), toIntervalDay(7))), 0)+ greaterOrEquals(sessions.`$start_timestamp`, minus(now64(6, %(hogql_val_2)s), toIntervalDay(7)))LIMIT 50000'''# ---diff --git a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambr b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambrindex d0ec6268af27..50dc0fab1f9f 100644--- a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambr+++ b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambr@@ -37,7 +37,7 @@GROUP BYraw_sessions_v3.session_id_v7) AS sessionsWHERE- ifNull(equals(sessions.session_id, %(hogql_val_2)s), 0)+ equals(sessions.session_id, %(hogql_val_2)s)LIMIT 50000'''# ---@@ -61,9 +61,9 @@GROUP BYraw_sessions_v3.session_id_v7) AS sessionsWHERE- ifNull(greaterOrEquals(sessions.`$start_timestamp`, %(hogql_val_2)s), 0)) AS subquery+ greaterOrEquals(sessions.`$start_timestamp`, %(hogql_val_2)s)) AS subqueryWHERE- ifNull(equals(subquery.session_id, %(hogql_val_3)s), 0)+ equals(subquery.session_id, %(hogql_val_3)s)LIMIT 50000'''# ---@@ -83,7 +83,7 @@GROUP BYraw_sessions_v3.session_id_v7) AS sessionsWHERE- ifNull(greater(sessions.`$start_timestamp`, %(hogql_val_2)s), 0)+ greater(sessions.`$start_timestamp`, %(hogql_val_2)s)LIMIT 50000'''# ---@@ -92,7 +92,7 @@SELECTcount(DISTINCT e.`$session_id`) AS total,toStartOfDay(toTimeZone(e.timestamp, %(hogql_val_7)s)) AS day_start,- multiIf(and(ifNull(greaterOrEquals(e__session.`$session_duration`, 2.0), 0), ifNull(less(e__session.`$session_duration`, 4.5), 0)), %(hogql_val_8)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 4.5), 0), ifNull(less(e__session.`$session_duration`, 27.0), 0)), %(hogql_val_9)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 27.0), 0), ifNull(less(e__session.`$session_duration`, 44.0), 0)), %(hogql_val_10)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 44.0), 0), ifNull(less(e__session.`$session_duration`, 48.0), 0)), %(hogql_val_11)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 48.0), 0), ifNull(less(e__session.`$session_duration`, 57.5), 0)), %(hogql_val_12)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 57.5), 0), ifNull(less(e__session.`$session_duration`, 61.0), 0)), %(hogql_val_13)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 61.0), 0), ifNull(less(e__session.`$session_duration`, 74.0), 0)), %(hogql_val_14)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 74.0), 0), ifNull(less(e__session.`$session_duration`, 90.0), 0)), %(hogql_val_15)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 90.0), 0), ifNull(less(e__session.`$session_duration`, 98.5), 0)), %(hogql_val_16)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 98.5), 0), ifNull(less(e__session.`$session_duration`, 167.01), 0)), %(hogql_val_17)s, %(hogql_val_18)s) AS breakdown_value+ multiIf(and(greaterOrEquals(e__session.`$session_duration`, 2.0), less(e__session.`$session_duration`, 4.5)), %(hogql_val_8)s, and(greaterOrEquals(e__session.`$session_duration`, 4.5), less(e__session.`$session_duration`, 27.0)), %(hogql_val_9)s, and(greaterOrEquals(e__session.`$session_duration`, 27.0), less(e__session.`$session_duration`, 44.0)), %(hogql_val_10)s, and(greaterOrEquals(e__session.`$session_duration`, 44.0), less(e__session.`$session_duration`, 48.0)), %(hogql_val_11)s, and(greaterOrEquals(e__session.`$session_duration`, 48.0), less(e__session.`$session_duration`, 57.5)), %(hogql_val_12)s, and(greaterOrEquals(e__session.`$session_duration`, 57.5), less(e__session.`$session_duration`, 61.0)), %(hogql_val_13)s, and(greaterOrEquals(e__session.`$session_duration`, 61.0), less(e__session.`$session_duration`, 74.0)), %(hogql_val_14)s, and(greaterOrEquals(e__session.`$session_duration`, 74.0), less(e__session.`$session_duration`, 90.0)), %(hogql_val_15)s, and(greaterOrEquals(e__session.`$session_duration`, 90.0), less(e__session.`$session_duration`, 98.5)), %(hogql_val_16)s, and(greaterOrEquals(e__session.`$session_duration`, 98.5), less(e__session.`$session_duration`, 167.01)), %(hogql_val_17)s, %(hogql_val_18)s) AS breakdown_valueFROMevents AS eLEFT OUTER JOIN (SELECT@@ -146,7 +146,7 @@GROUP BYraw_sessions_v3.session_id_v7) AS s__session ON equals(toUInt128(accurateCastOrNull(s.session_id, %(hogql_val_2)s)), s__session.session_id_v7)WHERE- and(equals(s.team_id, <TEAM_ID>), ifNull(equals(s__session.`$entry_pathname`, %(hogql_val_4)s), 0), greaterOrEquals(s.min_first_timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), less(s.min_first_timestamp, now64(6, %(hogql_val_7)s)))+ and(equals(s.team_id, <TEAM_ID>), equals(s__session.`$entry_pathname`, %(hogql_val_4)s), greaterOrEquals(s.min_first_timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), less(s.min_first_timestamp, now64(6, %(hogql_val_7)s)))GROUP BYs.session_idLIMIT 50000@@ -171,7 +171,7 @@GROUP BYraw_sessions_v3.session_id_v7) AS sessionsWHERE- and(ifNull(greaterOrEquals(sessions.`$start_timestamp`, UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_8)s, %(hogql_val_9)s))), 0), ifNull(lessOrEquals(sessions.`$start_timestamp`, plus(UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_10)s, %(hogql_val_11)s)), toIntervalHour(1))), 0), ifNull(equals(sessions.session_id, %(hogql_val_12)s), 0))+ and(ifNull(greaterOrEquals(sessions.`$start_timestamp`, UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_8)s, %(hogql_val_9)s))), 0), ifNull(lessOrEquals(sessions.`$start_timestamp`, plus(UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_10)s, %(hogql_val_11)s)), toIntervalHour(1))), 0), equals(sessions.session_id, %(hogql_val_12)s))LIMIT 1'''# ---@@ -191,7 +191,7 @@GROUP BYraw_sessions_v3.session_id_v7) AS sessionsWHERE- and(ifNull(greaterOrEquals(sessions.`$start_timestamp`, UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_7)s, %(hogql_val_8)s))), 0), ifNull(lessOrEquals(sessions.`$start_timestamp`, plus(UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_9)s, %(hogql_val_10)s)), toIntervalDay(2))), 0), ifNull(equals(sessions.session_id, %(hogql_val_11)s), 0))+ and(ifNull(greaterOrEquals(sessions.`$start_timestamp`, UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_7)s, %(hogql_val_8)s))), 0), ifNull(lessOrEquals(sessions.`$start_timestamp`, plus(UUIDv7ToDateTime(accurateCastOrNull(%(hogql_val_9)s, %(hogql_val_10)s)), toIntervalDay(2))), 0), equals(sessions.session_id, %(hogql_val_11)s))LIMIT 50000'''# ---@@ -205,15 +205,14 @@events__session.`$session_duration` AS durationFROM(SELECT- events.`$session_id_uuid` AS `$session_id_uuid`,- toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ events.`$session_id_uuid` AS `$session_id_uuid`FROMeventsWHEREand(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))LIMIT 50000) AS eventsLEFT JOIN (SELECT- dateDiff(%(hogql_val_1)s, min(toTimeZone(raw_sessions_v3.min_timestamp, %(hogql_val_2)s)), max(toTimeZone(raw_sessions_v3.max_timestamp, %(hogql_val_3)s))) AS `$session_duration`,+ dateDiff(%(hogql_val_0)s, min(toTimeZone(raw_sessions_v3.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(raw_sessions_v3.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`,raw_sessions_v3.session_id_v7 AS session_id_v7FROMraw_sessions_v3@@ -243,7 +242,7 @@GROUP BYraw_sessions_v3.session_id_v7) AS sessionsWHERE- ifNull(greaterOrEquals(sessions.`$start_timestamp`, minus(now64(6, %(hogql_val_2)s), toIntervalDay(7))), 0)+ greaterOrEquals(sessions.`$start_timestamp`, minus(now64(6, %(hogql_val_2)s), toIntervalDay(7)))LIMIT 50000'''# ---diff --git a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambr b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambrindex 40db25576792..4caf1e6a98fc 100644--- a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambr+++ b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambr@@ -38,7 +38,7 @@sessions.session_id,sessions.session_id) AS sessionsWHERE- ifNull(greater(sessions.`$start_timestamp`, %(hogql_val_2)s), 0)+ greater(sessions.`$start_timestamp`, %(hogql_val_2)s)LIMIT 50000'''# ---@@ -47,7 +47,7 @@SELECTcount(DISTINCT e.`$session_id`) AS total,toStartOfDay(toTimeZone(e.timestamp, %(hogql_val_7)s)) AS day_start,- multiIf(and(ifNull(greaterOrEquals(e__session.`$session_duration`, 2.0), 0), ifNull(less(e__session.`$session_duration`, 4.5), 0)), %(hogql_val_8)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 4.5), 0), ifNull(less(e__session.`$session_duration`, 27.0), 0)), %(hogql_val_9)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 27.0), 0), ifNull(less(e__session.`$session_duration`, 44.0), 0)), %(hogql_val_10)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 44.0), 0), ifNull(less(e__session.`$session_duration`, 48.0), 0)), %(hogql_val_11)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 48.0), 0), ifNull(less(e__session.`$session_duration`, 57.5), 0)), %(hogql_val_12)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 57.5), 0), ifNull(less(e__session.`$session_duration`, 61.0), 0)), %(hogql_val_13)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 61.0), 0), ifNull(less(e__session.`$session_duration`, 74.0), 0)), %(hogql_val_14)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 74.0), 0), ifNull(less(e__session.`$session_duration`, 90.0), 0)), %(hogql_val_15)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 90.0), 0), ifNull(less(e__session.`$session_duration`, 98.5), 0)), %(hogql_val_16)s, and(ifNull(greaterOrEquals(e__session.`$session_duration`, 98.5), 0), ifNull(less(e__session.`$session_duration`, 167.01), 0)), %(hogql_val_17)s, %(hogql_val_18)s) AS breakdown_value+ multiIf(and(greaterOrEquals(e__session.`$session_duration`, 2.0), less(e__session.`$session_duration`, 4.5)), %(hogql_val_8)s, and(greaterOrEquals(e__session.`$session_duration`, 4.5), less(e__session.`$session_duration`, 27.0)), %(hogql_val_9)s, and(greaterOrEquals(e__session.`$session_duration`, 27.0), less(e__session.`$session_duration`, 44.0)), %(hogql_val_10)s, and(greaterOrEquals(e__session.`$session_duration`, 44.0), less(e__session.`$session_duration`, 48.0)), %(hogql_val_11)s, and(greaterOrEquals(e__session.`$session_duration`, 48.0), less(e__session.`$session_duration`, 57.5)), %(hogql_val_12)s, and(greaterOrEquals(e__session.`$session_duration`, 57.5), less(e__session.`$session_duration`, 61.0)), %(hogql_val_13)s, and(greaterOrEquals(e__session.`$session_duration`, 61.0), less(e__session.`$session_duration`, 74.0)), %(hogql_val_14)s, and(greaterOrEquals(e__session.`$session_duration`, 74.0), less(e__session.`$session_duration`, 90.0)), %(hogql_val_15)s, and(greaterOrEquals(e__session.`$session_duration`, 90.0), less(e__session.`$session_duration`, 98.5)), %(hogql_val_16)s, and(greaterOrEquals(e__session.`$session_duration`, 98.5), less(e__session.`$session_duration`, 167.01)), %(hogql_val_17)s, %(hogql_val_18)s) AS breakdown_valueFROMevents AS eLEFT OUTER JOIN (SELECT@@ -119,15 +119,14 @@events__session.`$session_duration` AS durationFROM(SELECT- events.`$session_id` AS `$session_id`,- toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ events.`$session_id` AS `$session_id`FROMeventsWHEREand(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))LIMIT 50000) AS eventsLEFT JOIN (SELECT- dateDiff(%(hogql_val_1)s, min(toTimeZone(sessions.min_timestamp, %(hogql_val_2)s)), max(toTimeZone(sessions.max_timestamp, %(hogql_val_3)s))) AS `$session_duration`,+ dateDiff(%(hogql_val_0)s, min(toTimeZone(sessions.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(sessions.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`,sessions.session_id AS session_idFROMsessionsdiff --git a/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.py b/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.pyindex cbd73b32ef80..626948074e2b 100644--- a/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.py+++ b/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.py@@ -32,6 +32,12 @@ def _select(return parsed+def prop_read(blob: str, *keys: Union[str, int]) -> ast.PropertyAccess:+ """The lowered form of a `blob.key...` property read: `prop_read("properties", "email")` matches `properties.email`+ after lowering. Build expected clauses with it via placeholders, e.g. `_expr("{e} = 'x'", {"e": prop_read(...)})`."""+ return ast.PropertyAccess(expr=ast.Field(chain=[blob]), keys=list(keys))++class RemoveHiddenAliases(CloningVisitor):def visit_alias(self, node):if node.hidden:@@ -86,12 +92,12 @@ class TestPersonWhereClauseExtractor(ClickhouseTestMixin, APIBaseTest):def test_person_properties(self):actual = self.get_clause("SELECT * FROM events WHERE person.properties.email = '[email protected]'")- expected = _expr("properties.email = '[email protected]'")+ expected = _expr("{e} = '[email protected]'", {"e": prop_read("properties", "email")})assert actual == expecteddef test_person_properties_andor_1(self):actual = self.get_clause("SELECT * FROM events WHERE person.properties.email = '[email protected]' or false")- expected = _expr("properties.email = '[email protected]'")+ expected = _expr("{e} = '[email protected]'", {"e": prop_read("properties", "email")})assert actual == expecteddef test_person_properties_andor_2(self):@@ -102,28 +108,40 @@ class TestPersonWhereClauseExtractor(ClickhouseTestMixin, APIBaseTest):actual = self.get_clause("SELECT * FROM events WHERE person.properties.email = '[email protected]' and person.properties.email = '[email protected]'")- expected = _expr("properties.email = '[email protected]' and properties.email = '[email protected]'")+ expected = _expr(+ "{e1} = '[email protected]' and {e2} = '[email protected]'",+ {"e1": prop_read("properties", "email"), "e2": prop_read("properties", "email")},+ )assert actual == expecteddef test_person_properties_andor_4(self):actual = self.get_clause("SELECT * FROM events WHERE person.properties.email = '[email protected]' or person.properties.email = '[email protected]'")- expected = _expr("properties.email = '[email protected]' or properties.email = '[email protected]'")+ expected = _expr(+ "{e1} = '[email protected]' or {e2} = '[email protected]'",+ {"e1": prop_read("properties", "email"), "e2": prop_read("properties", "email")},+ )assert actual == expecteddef test_person_properties_andor_5(self):actual = self.get_clause("SELECT * FROM events WHERE person.properties.email = '[email protected]' or (1 and person.properties.email = '[email protected]')")- expected = _expr("properties.email = '[email protected]' or properties.email = '[email protected]'")+ expected = _expr(+ "{e1} = '[email protected]' or {e2} = '[email protected]'",+ {"e1": prop_read("properties", "email"), "e2": prop_read("properties", "email")},+ )assert actual == expecteddef test_person_properties_andor_6(self):actual = self.get_clause("SELECT * FROM events WHERE person.properties.email = '[email protected]' or (0 or person.properties.email = '[email protected]')")- expected = _expr("properties.email = '[email protected]' or properties.email = '[email protected]'")+ expected = _expr(+ "{e1} = '[email protected]' or {e2} = '[email protected]'",+ {"e1": prop_read("properties", "email"), "e2": prop_read("properties", "email")},+ )assert actual == expecteddef test_person_properties_andor_7(self):@@ -136,7 +154,7 @@ class TestPersonWhereClauseExtractor(ClickhouseTestMixin, APIBaseTest):actual = self.get_clause("SELECT * FROM events WHERE event == '$pageview' and person.properties.email = '[email protected]'")- expected = _expr("properties.email = '[email protected]'")+ expected = _expr("{e} = '[email protected]'", {"e": prop_read("properties", "email")})assert actual == expecteddef test_person_properties_andor_9(self):@@ -155,26 +173,26 @@ class TestPersonWhereClauseExtractor(ClickhouseTestMixin, APIBaseTest):actual = self.get_clause("SELECT * FROM events WHERE properties.email = '[email protected]' and person.properties.email = '[email protected]'")- expected = _expr("properties.email = '[email protected]'")+ expected = _expr("{e} = '[email protected]'", {"e": prop_read("properties", "email")})assert actual == expecteddef test_person_array(self):actual = self.get_clause("SELECT * FROM events WHERE person.properties.email IN ['[email protected]']")- expected = _expr("properties.email IN ['[email protected]']")+ expected = _expr("{e} IN ['[email protected]']", {"e": prop_read("properties", "email")})assert actual == expecteddef test_person_properties_function_calls(self):actual = self.get_clause("SELECT * FROM events WHERE properties.email = '[email protected]' and toString(person.properties.email) = '[email protected]'")- expected = _expr("toString(properties.email) = '[email protected]'")+ expected = _expr("toString({e}) = '[email protected]'", {"e": prop_read("properties", "email")})assert actual == expecteddef test_person_properties_function_call_args(self):actual = self.get_clause("SELECT * FROM events WHERE properties.email = '[email protected]' and substring(person.properties.email, 10) = '[email protected]'")- expected = _expr("substring(properties.email, 10) = '[email protected]'")+ expected = _expr("substring({e}, 10) = '[email protected]'", {"e": prop_read("properties", "email")})assert actual == expecteddef test_person_properties_function_call_args_complex(self):diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.pyindex df50b1261a3f..70cb648f3cbf 100644--- a/posthog/hogql/database/test/test_postgres_table.py+++ b/posthog/hogql/database/test/test_postgres_table.py@@ -341,7 +341,7 @@ class TestPostgresTable(BaseTest):)self.assertEqual(self._select("SELECT id FROM postgres_table LIMIT 10"),- f"SELECT postgres_table.id AS id FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS postgres_table WHERE and(equals(postgres_table.team_id, {self.team.pk}), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(postgres_table.properties, %(hogql_val_15)s), ''), 'null'), '^\"|\"$', ''), %(hogql_val_16)s), 1)) LIMIT 10",+ f"SELECT postgres_table.id AS id FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS postgres_table WHERE and(equals(postgres_table.team_id, {self.team.pk}), ifNull(notEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(postgres_table.properties, %(hogql_val_5)s), ''), 'null'), '^\"|\"$', ''), %(hogql_val_6)s), 1)) LIMIT 10",)diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.pyindex 9ef4c5f110f3..a3a78be90e16 100644--- a/posthog/hogql/printer/base.py+++ b/posthog/hogql/printer/base.py@@ -2,12 +2,12 @@ import refrom collections.abc import Iterablefrom datetime import date, datetimefrom difflib import get_close_matches-from typing import Any, ClassVar, Literal, Optional, Union, cast, get_args+from typing import Any, ClassVar, Optional, cast, get_argsfrom uuid import UUIDfrom django.conf import settings as django_settings-from posthog.schema import MaterializationMode, PersonsOnEventsMode+from posthog.schema import PersonsOnEventsModefrom posthog.hogql import astfrom posthog.hogql.ast import StringType@@ -30,24 +30,12 @@ from posthog.hogql.functions.mapping import (HOGQL_COMPARISON_MAPPING,is_allowed_parametric_function,)-from posthog.hogql.printer.types import (- JoinExprResponse,- PrintableMaterializedColumn,- PrintableMaterializedPropertyGroupItem,-)-from posthog.hogql.property_planner import get_dmat_column+from posthog.hogql.printer.types import JoinExprResponsefrom posthog.hogql.resolver import resolve_typesfrom posthog.hogql.resolver_utils import lookup_field_by_namefrom posthog.hogql.visitor import Visitor, clone_exprfrom posthog.clickhouse.kafka_engine import json_extract_trim_quotes-from posthog.clickhouse.materialized_columns import (- DMAT_STRING_COLUMN_NAME_PREFIX,- MaterializedColumn,- TablesWithMaterializedColumns,- get_materialized_column_for_property,-)-from posthog.models.property import PropertyName, TableColumnfrom posthog.models.team.team import WeekStartDayfrom posthog.models.utils import UUIDT@@ -67,18 +55,6 @@ def resolve_field_type(expr: ast.Expr) -> ast.Type | None:return expr_type-def _classify_materialized_property_source(- source: PrintableMaterializedColumn | PrintableMaterializedPropertyGroupItem | None,-) -> str:- if source is None:- return "json"- if isinstance(source, PrintableMaterializedPropertyGroupItem):- return "property_group"- if source.column.strip("`\"'").startswith(DMAT_STRING_COLUMN_NAME_PREFIX):- return "dynamic_materialized_column"- return "materialized_column"--class BasePrinter(Visitor[str]):# NOTE: Call "print_ast()", not this class directly.# Shared AST walker for all dialect printers (HogQL, ClickHouse, Postgres).@@ -1115,13 +1091,6 @@ class BasePrinter(Visitor[str]):args = [self.visit(arg) for arg in node.args]return f"{node.name}({', '.join(args)})"- def _yield_property_group_columns(self, field_type, table_name: str, field_name: str, property_name: str):- """Yield printable property-group column accessors for this dialect.-- Default yields nothing (property groups are a ClickHouse-only storage optimization).- """- yield from ()-def visit_placeholder(self, node: ast.Placeholder):if node.field is None:raise QueryError("You can not use placeholders here")@@ -1179,6 +1148,7 @@ class BasePrinter(Visitor[str]):return self._print_identifier(type.name)def visit_field_type(self, type: ast.FieldType):+ name_resolution_ambiguous = Falsetry:last_select = self._last_select()type_with_name_in_scope = (@@ -1187,7 +1157,9 @@ class BasePrinter(Visitor[str]):else None)except ResolutionError:+ # The name resolves to more than one source: it genuinely needs a table prefix to disambiguate.type_with_name_in_scope = None+ name_resolution_ambiguous = Trueif (isinstance(type.table_type, ast.TableType)@@ -1234,8 +1206,16 @@ class BasePrinter(Visitor[str]):if not isinstance(resolved_field, DatabaseField):raise QueryError(f"Can't resolve field {type.name}")field_sql = self._print_identifier(resolved_field.name)- if self.context.within_non_hogql_query and type_with_name_in_scope == type:- # Do not prepend table name in non-hogql context. We don't know what it actually is.+ if (+ self.context.within_non_hogql_query+ and not name_resolution_ambiguous+ and (type_with_name_in_scope is None or type_with_name_in_scope == type)+ ):+ # Print the column bare. A non-HogQL fragment (lightweight-DELETE predicate, legacy insight) splices+ # into a single-base-table context whose mutation analyzer rejects table-qualified names. We can drop+ # the prefix whenever the bare name is unambiguous: it resolves to *this* field, or to nothing at all+ # (e.g. a materialized column the physical pass synthesized, which isn't in the HogQL scope). We keep+ # the prefix only when the name resolves to a *different* field (shadowing) or is ambiguous.return field_sqlfield_sql = f"{self.visit(type.table_type)}.{field_sql}"@@ -1271,142 +1251,26 @@ class BasePrinter(Visitor[str]):return field_sql- def _get_materialized_property_source_for_property_type(- self, type: ast.PropertyType- ) -> PrintableMaterializedColumn | PrintableMaterializedPropertyGroupItem | None:- """- Find the most efficient materialized property source for the provided property type.- """- for source in self._get_all_materialized_property_sources(type.field_type, str(type.chain[0])):- return source- return None-- def _get_table_name(self, table: ast.TableType) -> str:- return table.table.to_printed_hogql()-- def _get_all_materialized_property_sources(- self, field_type: ast.FieldType, property_name: str- ) -> Iterable[PrintableMaterializedColumn | PrintableMaterializedPropertyGroupItem]:- """- Find all materialized property sources for the provided field type and property name, ordered from what is- likely to be the most efficient access path to the least efficient.- """- # TODO: It likely makes sense to make this independent of whether or not property groups are used.- if self.context.modifiers.materializationMode == "disabled":- return-- field = field_type.resolve_database_field(self.context)-- # check for a materialised column- table = field_type.table_type- while isinstance(table, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.VirtualTableType)):- table = table.table_type-- if isinstance(table, ast.TableType):- table_name = self._get_table_name(table)-- if field is None:- raise QueryError(f"Can't resolve field {field_type.name} on table {table_name}")- if not isinstance(field, DatabaseField):- raise QueryError(f"Can't resolve field {field_type.name} on table {table_name}")- field_name = cast(Union[Literal["properties"], Literal["person_properties"]], field.name)-- # In non-HogQL contexts (legacy queries, data deletion predicates) the consumer splices- # this fragment into a query whose table scope is fixed and known (e.g. ``events e``,- # ``DELETE FROM sharded_events``). Mirror what visit_field_type already does for regular- # columns at line 1201: drop the table prefix. In particular, lightweight DELETE rewrites- # the predicate into a mutation, whose expression analyzer rejects table-qualified- # references like ``sharded_events.mat_$current_url`` even when the column exists.- table_prefix: str | None = (- None if self.context.within_non_hogql_query else self.visit(field_type.table_type)- )-- materialized_column = self._get_materialized_column(table_name, property_name, field_name)- if materialized_column is not None:- yield PrintableMaterializedColumn(- table_prefix,- self._print_identifier(materialized_column.name),- is_nullable=materialized_column.is_nullable,- type=materialized_column.type,- has_minmax_index=materialized_column.has_minmax_index,- has_ngram_lower_index=materialized_column.has_ngram_lower_index,- has_bloom_filter_index=materialized_column.has_bloom_filter_index,- has_bloom_filter_lower_index=materialized_column.has_bloom_filter_lower_index,- )-- # Check for dmat (dynamic materialized) columns- if dmat_column := self._get_dmat_column(table_name, field_name, property_name):- yield PrintableMaterializedColumn(- table_prefix,- self._print_identifier(dmat_column),- is_nullable=True,- type="Nullable(String)",- has_minmax_index=False,- has_ngram_lower_index=False,- has_bloom_filter_index=False,- has_bloom_filter_lower_index=False,- )-- yield from self._yield_property_group_columns(field_type, table_name, field_name, property_name)- elif self.context.within_non_hogql_query and (- isinstance(table, ast.SelectQueryAliasType) and table.alias == "events__pdi__person"- ):- # :KLUDGE: Legacy person properties handling. Only used within non-HogQL queries, such as insights.- if self.context.modifiers.personsOnEventsMode != PersonsOnEventsMode.DISABLED:- materialized_column = self._get_materialized_column("events", property_name, "person_properties")- else:- materialized_column = self._get_materialized_column("person", property_name, "properties")- if materialized_column is not None:- yield PrintableMaterializedColumn(- None,- self._print_identifier(materialized_column.name),- is_nullable=materialized_column.is_nullable,- type=materialized_column.type,- has_minmax_index=materialized_column.has_minmax_index,- has_ngram_lower_index=materialized_column.has_ngram_lower_index,- has_bloom_filter_index=materialized_column.has_bloom_filter_index,- has_bloom_filter_lower_index=materialized_column.has_bloom_filter_lower_index,- )-def visit_property_type(self, type: ast.PropertyType):+ # After lowering, a blob property read is a `PropertyAccess`. A `PropertyType` still reaching the printer is the+ # leftover OUTER reference to a person/group property that `resolve_lazy_tables` pulled into a join subquery: the+ # JSON extract now lives inside that subquery (and was lowered there), so this outer node is just an+ # `alias.column` read of the subquery's result — nothing to lower. (Plus, in the ClickHouse override, a+ # data-warehouse struct column.) The printer makes no physical-column decision — that moved to+ # `logical_property_lowering` + the ClickHouse physical passes.if type.joined_subquery is not None and type.joined_subquery_field_name is not None:return f"{self._print_identifier(type.joined_subquery.alias)}.{self._print_identifier(type.joined_subquery_field_name)}"- materialized_property_source = self._get_materialized_property_source_for_property_type(type)- if self.context.type_observability is not None:- self.context.type_observability.record_materialized_property_usage(- _classify_materialized_property_source(materialized_property_source)- )- if materialized_property_source is not None:- # Special handling for $ai_trace_id, $ai_session_id, and $ai_is_error to avoid nullIf wrapping for index optimization- if (- len(type.chain) == 1- and type.chain[0] in ("$ai_trace_id", "$ai_session_id", "$ai_is_error")- and isinstance(materialized_property_source, PrintableMaterializedColumn)- ):- materialized_property_sql = str(materialized_property_source)- elif (- isinstance(materialized_property_source, PrintableMaterializedColumn)- and not materialized_property_source.is_nullable- ):- # TODO: rematerialize all columns to properly support empty strings and "null" string values.- if self.context.modifiers.materializationMode == MaterializationMode.LEGACY_NULL_AS_STRING:- materialized_property_sql = f"nullIf({materialized_property_source}, '')"- else: # MaterializationMode AUTO or LEGACY_NULL_AS_NULL- materialized_property_sql = f"nullIf(nullIf({materialized_property_source}, ''), 'null')"- else:- materialized_property_sql = str(materialized_property_source)-- if len(type.chain) == 1:- return materialized_property_sql- else:- return self._unsafe_json_extract_trim_quotes(- materialized_property_sql,- self._json_property_args(type.chain[1:]),- )-return self._unsafe_json_extract_trim_quotes(self.visit(type.field_type), self._json_property_args(type.chain))+ def visit_property_access(self, node: ast.PropertyAccess) -> str:+ # Renders a lowered property read: extract the key path from the JSON source in this dialect's syntax (ClickHouse+ # JSONExtractRaw + null/quote scrub via the base helper; Postgres/DuckDB override+ # `_unsafe_json_extract_trim_quotes`/`_json_property_args` for `->`/`->>`). It calls the same JSON-extract helper+ # `visit_property_type` uses for its blob fallback just above, so the output is the plain JSON-extract form. No+ # physical-column decision happens here.+ return self._unsafe_json_extract_trim_quotes(self.visit(node.expr), self._json_property_args(node.keys))+def visit_sample_expr(self, node: ast.SampleExpr) -> Optional[str]:# SAMPLE 1 means no sampling, skip it entirelyif node.sample_value.left.value == 1 and node.sample_value.right is None and node.offset_value is None:@@ -1599,16 +1463,6 @@ class BasePrinter(Visitor[str]):def _json_property_args(self, chain: Iterable[Any]) -> list[str]:return [self.context.add_value(name) for name in chain]- def _get_materialized_column(- self, table_name: str, property_name: PropertyName, field_name: TableColumn- ) -> MaterializedColumn | None:- return get_materialized_column_for_property(- cast(TablesWithMaterializedColumns, table_name), field_name, property_name- )-- def _get_dmat_column(self, table_name: str, field_name: str, property_name: str) -> str | None:- return get_dmat_column(self.context, table_name, field_name, property_name)-def _get_timezone(self) -> str:if self.context.modifiers.convertToProjectTimezone is False:return "UTC"@@ -1625,6 +1479,15 @@ class BasePrinter(Visitor[str]):elif isinstance(node_type, ast.CallType):return node_type.return_type.nullableelif isinstance(node_type, ast.FieldType):+ # A field reading from a subquery (alias) has no database field, so `is_nullable` defaults to True and+ # over-wraps the column in `ifNull(...)`. Its real nullability is the projected column's constant type —+ # use that, so a non-nullable value selected from a subquery isn't needlessly null-wrapped (which, for a+ # join key, ClickHouse can't use). Real-table fields keep `is_nullable` (identical result, no risk).+ if not isinstance(node_type.table_type, ast.BaseTableType):+ try:+ return node_type.resolve_constant_type(self.context).nullable+ except Exception:+ return Truereturn node_type.is_nullable(self.context)return Nonediff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.pyindex b90072caf251..5ce2abc69e64 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -1,17 +1,15 @@import refrom datetime import date, datetime-from typing import ClassVar, Literal, Union, cast+from typing import ClassVar, castfrom uuid import UUIDfrom django.conf import settings as django_settings-from posthog.schema import PropertyGroupsMode-from posthog.hogql import astfrom posthog.hogql.ast import AST, Constant, StringTypefrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.models import DANGEROUS_NoTeamIdCheckTable, DatabaseField, SavedQuery, StructDatabaseField+from posthog.hogql.database.models import DANGEROUS_NoTeamIdCheckTable, SavedQuery, StructDatabaseFieldfrom posthog.hogql.database.s3_table import DataWarehouseTable, S3Tablefrom posthog.hogql.errors import ImpossibleASTError, InternalHogQLError, QueryErrorfrom posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_clickhouse_string, safe_identifier@@ -19,20 +17,10 @@ from posthog.hogql.functions import ADD_OR_NULL_DATETIME_FUNCTIONS, FIRST_ARG_DAfrom posthog.hogql.functions.embed_text import resolve_embed_textfrom posthog.hogql.printer.base import BasePrinter, get_channel_definition_dict, resolve_field_typefrom posthog.hogql.printer.hogql import HogQLPrinter-from posthog.hogql.printer.types import PrintableMaterializedColumn, PrintableMaterializedPropertyGroupItem-from posthog.hogql.property_planner import (- PropertyLiteralConversion,- PropertySourceKind,- get_restricted_keys_for_table_type,- is_property_type_restricted,- plan_property_comparison,-)+from posthog.hogql.restricted_properties import restricted_property_keys_for_table_typefrom posthog.hogql.type_system import parse_sql_runtime_type-from posthog.hogql.utils import ilike_matches, like_matchesfrom posthog.hogql.visitor import GetFieldsTraverser, clone_expr-from posthog.clickhouse.materialized_columns import MATERIALIZATION_VALID_TABLES, MATERIALIZED_COLUMN_NAME_PREFIXES-from posthog.clickhouse.property_groups import property_groupsfrom posthog.models.exchange_rate.sql import EXCHANGE_RATE_DICTIONARY_NAMEfrom posthog.models.team.team import WeekStartDayfrom posthog.models.utils import UUIDT@@ -58,22 +46,21 @@ def team_id_guard_for_table(table_type: ast.TableOrSelectType, context: HogQLCon)-# In non-nullable materialized columns, these values are treated as NULL-MAT_COL_NULL_SENTINELS = ["", "null"]+# The $ai_* properties whose materialized columns carry bloom-filter skip indexes. We read them bare — no nullIf/ifNull+# wrapping — so the index stays usable. Canonical set; ClickHouse property resolution imports it to make the same call.+AI_BLOOM_FILTER_PROPERTIES = {"$ai_trace_id", "$ai_session_id", "$ai_is_error"}-# We skip nullIf/ifNull wrapping for these columns, to improve performance and help skip index usage+# Both the property name and its `mat_` column spelling, so visit_compare_operation can match either side of a comparison.COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING = {- "mat_$ai_trace_id",- "mat_$ai_session_id",- "mat_$ai_is_error",- "$ai_trace_id",- "$ai_session_id",- "$ai_is_error",+ *AI_BLOOM_FILTER_PROPERTIES,+ *(f"mat_{prop}" for prop in AI_BLOOM_FILTER_PROPERTIES),}--def _is_physical_materialized_column_name(name: str) -> bool:- return name.strip("`\"'").startswith(MATERIALIZED_COLUMN_NAME_PREFIXES)+# The only string literals a `Constant(inline_sentinel=True)` is allowed to render inline (escaped, unparameterized): the+# fixed scrubbing markers property resolution emits — the nullIf ''/'null' sentinels, the quote-trim regex, and the+# 'true'/'false' the property-group map stores booleans as. The printer refuses to inline anything else, so the flag can+# never be turned into an unparameterized read of arbitrary (e.g. user-supplied) text.+INLINE_SENTINEL_LITERALS = frozenset({"", "null", "true", "false", '^"|"$'})class ClickHousePrinter(BasePrinter):@@ -96,22 +83,6 @@ class ClickHousePrinter(BasePrinter):if node.within_group is not None:raise QueryError(f"Aggregation '{node.name}' with WITHIN GROUP is not supported in ClickHouse dialect")- def _yield_property_group_columns(self, field_type, table_name: str, field_name: str, property_name: str):- if self.context.modifiers.propertyGroupsMode not in (- PropertyGroupsMode.ENABLED,- PropertyGroupsMode.OPTIMIZED,- ):- return- # For now, we're assuming that properties are in either no groups or one group, so just using the- # first group returned is fine. If we start putting properties in multiple groups, this should be- # revisited to find the optimal set (i.e. smallest set) of groups to read from.- for property_group_column in property_groups.get_property_group_columns(table_name, field_name, property_name):- yield PrintableMaterializedPropertyGroupItem(- self.visit(field_type.table_type),- self._print_identifier(property_group_column),- self.context.add_value(property_name),- )-def _render_function_call(self, node: ast.Call, func_meta) -> str:args_count = len(node.args) - func_meta.passthrough_suffix_args_countnode_args, passthrough_suffix_args = node.args[:args_count], node.args[args_count:]@@ -393,6 +364,13 @@ class ClickHousePrinter(BasePrinter):return f"ifNull({op}, 0)"def visit_constant(self, node: ast.Constant):+ # Opt-in inline rendering for the fixed scrubbing sentinels property resolution emits, so its AST-built scrub renders+ # identically to the `json_extract_trim_quotes` helper's inline string. Gated to a fixed allowlist: the flag is set+ # only internally, so a value outside it is a bug — refuse to inline it rather than emit unparameterized text.+ if node.inline_sentinel and isinstance(node.value, str):+ if node.value not in INLINE_SENTINEL_LITERALS:+ raise ImpossibleASTError(f"inline_sentinel set on a non-sentinel constant: {node.value!r}")+ return self._print_escaped_string(node.value)if (node.value is Noneor isinstance(node.value, bool)@@ -436,21 +414,6 @@ class ClickHousePrinter(BasePrinter):field_sql = super().visit_field_type(type)return self._maybe_apply_json_drop_keys(type, field_sql)- def _get_materialized_property_source_for_property_type(- self, type: ast.PropertyType- ) -> PrintableMaterializedColumn | PrintableMaterializedPropertyGroupItem | None:- # If this property is restricted by property-level access control, skip the- # materialized-column / property-group shortcut and force the JSON-extract path- # below. The JSON column itself is wrapped by ``JSONDropKeys`` in- # ``_maybe_apply_json_drop_keys`` (see ``visit_field_type``), so the extracted- # value collapses to an empty string instead of leaking the materialized value.- if self._is_property_type_restricted(type):- return None- return super()._get_materialized_property_source_for_property_type(type)-- def _is_property_type_restricted(self, type: ast.PropertyType) -> bool:- return is_property_type_restricted(type, self.context)-def _maybe_apply_json_drop_keys(self, type: ast.FieldType, field_sql: str) -> str:"""Wraps a StringJSONDatabaseField in JSONDropKeys() to strip restricted property keys@@ -474,651 +437,13 @@ class ClickHousePrinter(BasePrinter):if resolved_field.name not in ("properties", "person_properties"):return field_sql- keys_to_drop = self._get_restricted_keys_for_table_type(type.table_type)+ keys_to_drop = restricted_property_keys_for_table_type(type.table_type, self.context)if not keys_to_drop:return field_sqlkeys_placeholder = self.context.add_sensitive_value(sorted(keys_to_drop))return f"JSONDropKeys({keys_placeholder})({field_sql})"- def _get_restricted_keys_for_table_type(self, table_type: ast.Type) -> set[str]:- """- Given a table type, returns the set of property names that should be stripped- from the JSON blob based on restricted_properties in the context.- """- return get_restricted_keys_for_table_type(table_type, self.context)-- def _get_property_group_source_for_field(- self, field_type: ast.FieldType, property_name: str- ) -> PrintableMaterializedPropertyGroupItem | None:- """- Find a property group source for the given field and property name.- Used for JSONHas optimizations where we specifically need property group sources- (not mat_* columns) because property groups can efficiently check for key existence.- """- if self.context.modifiers.propertyGroupsMode not in (- PropertyGroupsMode.ENABLED,- PropertyGroupsMode.OPTIMIZED,- ):- return None-- field = field_type.resolve_database_field(self.context)- table = field_type.table_type- while isinstance(table, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.VirtualTableType)):- table = table.table_type-- if not isinstance(table, ast.TableType):- return None-- table_name = table.table.to_printed_clickhouse(self.context)- if field is None or not isinstance(field, DatabaseField):- return None- field_name = cast(Union[Literal["properties"], Literal["person_properties"]], field.name)-- for property_group_column in property_groups.get_property_group_columns(table_name, field_name, property_name):- return PrintableMaterializedPropertyGroupItem(- self.visit(field_type.table_type),- self._print_identifier(property_group_column),- self.context.add_value(property_name),- )-- return None-- def _get_optimized_property_group_call(self, node: ast.Call) -> str | None:- """- Returns a printed expression corresponding to the provided call, if the function is being applied to a property- group value and the function can be rewritten so that it can be eligible for use by the property group's map's- key bloom filter index, or can be optimized to avoid reading the property group's map ``values`` subcolumn.- """- if self.context.modifiers.propertyGroupsMode != PropertyGroupsMode.OPTIMIZED:- return None-- # XXX: A lot of this is duplicated (sometimes just copy/pasted) from the null equality comparison logic -- it- # might make sense to make it so that ``isNull``/``isNotNull`` is rewritten to comparison expressions before- # this step, similar to how ``equals``/``notEquals`` are interpreted as their comparison operation counterparts.-- match node:- case ast.Call(name="isNull" | "isNotNull" as function_name, args=[field]):- # TODO: can probably optimize chained operations, but will need more thought- field_type = resolve_field_type(field)- if isinstance(field_type, ast.PropertyType) and len(field_type.chain) == 1:- property_source = self._get_materialized_property_source_for_property_type(field_type)- if not isinstance(property_source, PrintableMaterializedPropertyGroupItem):- return None-- match function_name:- case "isNull":- return f"not({property_source.has_expr})"- case "isNotNull":- return property_source.has_expr- case _:- raise ValueError(f"unexpected node name: {function_name}")- case ast.Call(name="JSONHas", args=[field, ast.Constant(value=property_name)]):- # TODO: can probably optimize chained operations here as well- field_type = resolve_field_type(field)- if not isinstance(field_type, ast.FieldType):- return None-- # TRICKY: Materialized property columns do not currently support null values (see comment in- # `visit_property_type`) so checking whether or not a property is set for a row cannot safely use that- # field and falls back to the equivalent ``JSONHas(properties, ...)`` call instead. However, if this- # property is part of *any* property group, we can use that column instead to evaluate this expression- # more efficiently -- even if the materialized column would be a better choice in other situations.- if property_source := self._get_property_group_source_for_field(field_type, str(property_name)):- return property_source.has_expr-- return None # nothing to optimize-- def _get_optimized_materialized_column_equals_operation(self, node: ast.CompareOperation) -> str | None:- """- Returns an optimized printed expression for comparisons involving individually materialized columns.-- When comparing equality between a materialized column and a non-empty, non-null string constant, we can avoid the- nullIf() wrapping that normally happens. This allows ClickHouse to use skip indexes on the materialized column.-- For example, instead of:- ifNull(equals(nullIf(nullIf(events.`mat_$feature_flag`, ''), 'null'), 'some_value'), 0)- We can emit:- ifNull(equals(events.`mat_$feature_flag`, 'some_value'), 0)-- This is safe because we know 'some_value' is neither empty string nor 'null', so the nullIf- checks are redundant for the comparison result. We keep the outer ifNull to ensure proper- boolean semantics when composed with not() or other logical operations.- """- if node.op not in (ast.CompareOperationOp.Eq, ast.CompareOperationOp.NotEq):- return None-- # Property can be on either side of the comparison- property_source: PrintableMaterializedColumn | None = None- constant_expr: ast.Constant | None = None-- if (ps := self._get_materialized_string_property_source(node.left)) and (- ce := self._get_string_pattern_constant(node.right)- ):- property_source, constant_expr = ps, ce- elif (ps := self._get_materialized_string_property_source(node.right)) and (- ce := self._get_string_pattern_constant(node.left)- ):- property_source, constant_expr = ps, ce-- if property_source is None or constant_expr is None:- return None-- # Bail out for sentinel values - let normal code path handle with nullIf wrapping- if constant_expr.value in MAT_COL_NULL_SENTINELS:- return None-- # These are optimized elsewhere- if property_source.column.strip("`\"'") in COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING:- return None-- # Build the optimized comparison using the raw materialized column- materialized_column_sql = str(property_source)- constant_sql = self.visit(constant_expr)-- # Wrap in additional handling to ensure proper boolean semantics when composed with not() or other logic.- # - equals(NULL, 'value') → NULL, but should be 0 (false) so not() works correctly- # - notEquals(NULL, 'value') → NULL, but should be 1 (true) since NULL != 'value'- # Use a compound expression for the Eq case to allow skip indexes to be used (which are broken by ifNull)- if node.op == ast.CompareOperationOp.Eq:- if property_source.is_nullable:- return (- f"(equals({materialized_column_sql}, {constant_sql}) AND ({materialized_column_sql} IS NOT NULL))"- )- else:- return f"equals({materialized_column_sql}, {constant_sql})"- else:- if property_source.is_nullable:- return f"ifNull(notEquals({materialized_column_sql}, {constant_sql}), 1)"- else:- return f"notEquals({materialized_column_sql}, {constant_sql})"-- _RANGE_OP_TO_CH_NAME: dict[ast.CompareOperationOp, str] = {- ast.CompareOperationOp.Lt: "less",- ast.CompareOperationOp.LtEq: "lessOrEquals",- ast.CompareOperationOp.Gt: "greater",- ast.CompareOperationOp.GtEq: "greaterOrEquals",- }- _RANGE_CH_NAMES = frozenset(_RANGE_OP_TO_CH_NAME.values())-- def _record_range_rewrite(self, result: str) -> None:- if self.context.type_observability is None:- return- self.context.type_observability.record_materialized_range_rewrite(result)- if result.startswith("fired"):- # A fired rewrite prints the materialized column directly, bypassing- # visit_property_type, so account for the materialized access here.- self.context.type_observability.record_materialized_property_usage("materialized_column")-- def _get_optimized_materialized_column_range_operation(self, node: ast.CompareOperation) -> str | None:- """Rewrite property ranges on materialized columns so minmax can fire.-- String-backed columns keep the current sentinel handling.- Typed physical columns, such as future numeric or DateTime materializations, can compare the bare column directly- when the property planner proves the physical source matches the semantic property type.- """- if node.op not in self._RANGE_OP_TO_CH_NAME:- return None-- comparison_plan = plan_property_comparison(node, self.context)- if (- comparison_plan is not None- and comparison_plan.property_side == "left"- and comparison_plan.access.source.kind == PropertySourceKind.MATERIALIZED_COLUMN- ):- physical_type = comparison_plan.access.source.physical_type- if not comparison_plan.source_matches_semantics:- self._record_range_rewrite("skipped")- return None- if not comparison_plan.can_compare_physical_source_directly and not isinstance(- physical_type, ast.StringType- ):- self._record_range_rewrite("skipped")- return None-- property_source = self._get_materialized_property_source_for_property_type(- comparison_plan.access.property_type- )- if not isinstance(property_source, PrintableMaterializedColumn):- self._record_range_rewrite("skipped")- return None-- constant_sql = self._print_property_range_value(node.right, comparison_plan.literal_conversion)- else:- fallback = self._get_physical_materialized_column_source(node.left)- if fallback is None:- return None-- property_source, physical_type = fallback- constant_sql = self.visit(node.right)-- right_constant = node.right if isinstance(node.right, ast.Constant) else None- if right_constant is not None and right_constant.value is None:- self._record_range_rewrite("skipped")- return None-- if property_source.column.strip("`\"'") in COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING:- self._record_range_rewrite("skipped")- return None-- op_name = self._RANGE_OP_TO_CH_NAME[node.op]- materialized_column_sql = str(property_source)- is_string_source = isinstance(physical_type, ast.StringType)- if is_string_source and right_constant is None:- self._record_range_rewrite("skipped")- return None-- if property_source.is_nullable:- self._record_range_rewrite("fired_compare")- return f"({op_name}({materialized_column_sql}, {constant_sql}) AND ({materialized_column_sql} IS NOT NULL))"-- if not is_string_source:- # A non-nullable, non-string column stores the ClickHouse type default (e.g. 0 for a- # Float64) when the JSON value is missing or invalid, so a bare comparison would match- # rows where the property does not exist. There is no safe bare rewrite without- # nullability to distinguish a real default from a missing value, so skip the optimization.- self._record_range_rewrite("skipped")- return None-- # Non-nullable strings: exclude the '' / 'null' sentinels inline so the comparison stays bare.- self._record_range_rewrite("fired_compare")- sentinel_exclusions = " AND ".join(- f"notEquals({materialized_column_sql}, {self._print_escaped_string(s)})" for s in MAT_COL_NULL_SENTINELS- )- return f"({op_name}({materialized_column_sql}, {constant_sql}) AND {sentinel_exclusions})"-- def _get_optimized_materialized_range_if_null_call(self, node: ast.Call) -> str | None:- if node.name.lower() != "ifnull" or len(node.args) != 2:- return None-- fallback = node.args[1]- if not isinstance(fallback, ast.Constant) or fallback.value not in (0, False):- return None-- range_call = node.args[0]- if not isinstance(range_call, ast.Call) or range_call.name not in self._RANGE_CH_NAMES:- return None- if len(range_call.args) != 2:- return None-- source = self._get_materialized_range_source(range_call.args[0])- if source is None:- return None-- property_source, is_string_source = source- if not property_source.is_nullable:- self._record_range_rewrite("skipped")- return None-- right_constant = range_call.args[1] if isinstance(range_call.args[1], ast.Constant) else None- if right_constant is not None and right_constant.value is None:- self._record_range_rewrite("skipped")- return None- if is_string_source and right_constant is None:- self._record_range_rewrite("skipped")- return None-- materialized_column_sql = str(property_source)- constant_sql = self.visit(range_call.args[1])- self._record_range_rewrite("fired_if_null")- return (- f"({range_call.name}({materialized_column_sql}, {constant_sql}) "- f"AND ({materialized_column_sql} IS NOT NULL))"- )-- def _get_materialized_range_source(self, expr: ast.Expr) -> tuple[PrintableMaterializedColumn, bool] | None:- physical_source = self._get_physical_materialized_column_source(expr)- if physical_source is not None:- physical_property_source, physical_type = physical_source- return physical_property_source, isinstance(physical_type, ast.StringType)-- expr_type = resolve_field_type(expr)- if not isinstance(expr_type, ast.PropertyType) or len(expr_type.chain) != 1:- return None-- semantic_type = expr_type.resolve_constant_type(self.context)- if not isinstance(semantic_type, ast.StringType):- return None-- materialized_source = self._get_materialized_property_source_for_property_type(expr_type)- if not isinstance(materialized_source, PrintableMaterializedColumn):- return None-- return materialized_source, parse_sql_runtime_type(materialized_source.type or "").family == "string"-- def _get_physical_materialized_column_source(- self, expr: ast.Expr- ) -> tuple[PrintableMaterializedColumn, ast.ConstantType] | None:- while isinstance(expr, ast.Alias):- expr = expr.expr-- field_type = resolve_field_type(expr)- if not isinstance(field_type, ast.FieldType):- return None-- field = field_type.resolve_database_field(self.context)- if not isinstance(field, DatabaseField):- return None-- if not _is_physical_materialized_column_name(field.name):- return None-- table = field_type.table_type- while isinstance(table, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.VirtualTableType)):- table = table.table_type-- if not isinstance(table, ast.TableType):- return None-- if (- table.resolve_database_table(self.context).to_printed_clickhouse(self.context)- not in MATERIALIZATION_VALID_TABLES- ):- return None-- return (- PrintableMaterializedColumn(- self.visit(field_type.table_type),- self._print_identifier(field.name),- is_nullable=field.is_nullable(),- type=None,- has_minmax_index=False,- has_bloom_filter_index=False,- has_ngram_lower_index=False,- has_bloom_filter_lower_index=False,- ),- field.get_constant_type(),- )-- def _print_property_range_value(self, expr: ast.Expr, literal_conversion: PropertyLiteralConversion) -> str:- if literal_conversion == PropertyLiteralConversion.DATETIME and isinstance(expr, ast.Constant):- return (- f"toDateTime64({self.visit(expr)}, "- f"{self.visit(ast.Constant(value=6))}, "- f"{self.visit(ast.Constant(value=self._get_timezone()))})"- )- return self.visit(expr)-- def _get_materialized_string_property_source(self, expr: ast.Expr) -> PrintableMaterializedColumn | None:- """- Extracts a PrintableMaterializedColumn from an expression if it's a simple string property access.-- String properties can have their mat col returned even if they are wrapped in a toString() call. Sometimes this- wrapping is added for safety (as users can change the type of key properties), but this should not prevent us- from doing optimisations that are safe.- Returns None if the expression is not a valid string property access or doesn't have a- materialized column.- """- property_type: ast.PropertyType | None = None-- # Check for direct property access- expr_type = resolve_field_type(expr)- if isinstance(expr_type, ast.PropertyType):- property_type = expr_type- # Check for toString(properties.X) wrapper- elif isinstance(expr, ast.Call) and expr.name == "toString" and len(expr.args) == 1:- # Unwrap Alias if present to check the actual structure- inner_expr = expr.args[0]- if isinstance(inner_expr, ast.Alias):- inner_expr = inner_expr.expr- # Only match if the inner expression is a direct Field access, not a Call- # (e.g., we want toString(properties.X), not toString(toFloat(properties.X)))- # This ensures we don't apply the optimization when PropertySwapper has wrapped- # the property in a type conversion function- if isinstance(inner_expr, ast.Field):- inner_type = resolve_field_type(inner_expr)- if isinstance(inner_type, ast.PropertyType) and len(inner_type.chain) == 1:- property_type = inner_type-- if property_type is None:- return None-- # Only optimize simple property access (not chained like properties.foo.bar)- if len(property_type.chain) != 1:- return None-- # Check if this property has a non-string type defined - if so, skip the optimization- property_name = str(property_type.chain[0])- if self.context.property_swapper is not None:- prop_info = self.context.property_swapper.event_properties.get(property_name)- if prop_info is not None and prop_info.get("type") not in (None, "String"):- return None-- # Check if this property uses an individually materialized column (not a property group)- property_source = self._get_materialized_property_source_for_property_type(property_type)- if not isinstance(property_source, PrintableMaterializedColumn):- return None-- return property_source-- def _get_string_pattern_constant(self, expr: ast.Expr) -> ast.Constant | None:- if isinstance(expr, ast.Constant) and isinstance(expr.value, str):- return expr- return None-- def _get_optimized_materialized_column_ilike_operation(self, node: ast.CompareOperation) -> str | None:- """- Returns an optimized printed expression for ILIKE comparisons involving materialized columns.-- For non-nullable columns with patterns that could match sentinel values ('', 'null'),- we bail out and let the normal code path handle it with proper nullif wrapping.-- For patterns that cannot match sentinels, we use the raw materialized column directly,- enabling skip index optimization.- """- if node.op not in (ast.CompareOperationOp.ILike, ast.CompareOperationOp.NotILike):- return None-- if not (- (property_source := self._get_materialized_string_property_source(node.left))- and (pattern_expr := self._get_string_pattern_constant(node.right))- ):- return None-- materialized_column_sql = str(property_source)- pattern_sql = self.visit(pattern_expr)-- if property_source.is_nullable:- if node.op == ast.CompareOperationOp.ILike:- if property_source.has_ngram_lower_index:- # Use the ngram_lower index if it exists, must use like instead of ilike.- # ilike(haystack, needle) is equivalent to like(lower(haystack), lower(needle)), though the latter is less CPU- # efficient so ONLY do this if the skip index is present.- # We use coalesce to match the index expression (ngram indexes don't support nullable columns).- return f"and(like(lower(coalesce({materialized_column_sql}, '')), lower({pattern_sql})), {materialized_column_sql} IS NOT NULL)"- else:- # We include IS NOT NULL because we want to return FALSE rather than NULL if the column is NULL,- # and prefer this to wrapping in ifNull because it allows skip index usage.- return (- f"and(ilike({materialized_column_sql}, {pattern_sql}), {materialized_column_sql} IS NOT NULL)"- )- else:- # For NOT ILIKE, we need ifNull wrapper because NULL NOT ILIKE pattern should be TRUE.- # We don't care about the skip index here, as bloom filters don't help with detecting negative presence- return f"ifNull(notILike({materialized_column_sql}, {pattern_sql}), 1)"- else:- # Non-nullable columns store null values as the string 'null', so bail out of optimizing and let the- # regular code path handle it, which handles this case- if any(ilike_matches(pattern_expr.value, s) for s in MAT_COL_NULL_SENTINELS):- return None-- if node.op == ast.CompareOperationOp.ILike:- if property_source.has_ngram_lower_index:- return f"like(lower({materialized_column_sql}), lower({pattern_sql}))"- else:- return f"ilike({materialized_column_sql}, {pattern_sql})"- else:- return f"notILike({materialized_column_sql}, {pattern_sql})"-- def _get_optimized_materialized_column_like_operation(self, node: ast.CompareOperation) -> str | None:- """- Returns an optimized printed expression for LIKE comparisons involving materialized columns.-- For non-nullable columns with patterns that could match sentinel values ('', 'null'),- we bail out and let the normal code path handle it with proper nullif wrapping.-- For patterns that cannot match sentinels, we use the raw materialized column directly,- enabling skip index optimization. Unlike ILIKE, LIKE is case-sensitive which allows- ClickHouse to use ngrambf_v1 skip indexes.- """- if node.op not in (ast.CompareOperationOp.Like, ast.CompareOperationOp.NotLike):- return None-- if not (- (property_source := self._get_materialized_string_property_source(node.left))- and (pattern_expr := self._get_string_pattern_constant(node.right))- ):- return None-- materialized_column_sql = str(property_source)-- if property_source.is_nullable:- pattern_sql = self.visit(pattern_expr)- if node.op == ast.CompareOperationOp.Like:- # We include IS NOT NULL because we want to return FALSE rather than NULL if the column is NULL,- # and prefer this to wrapping in ifNull because it allows skip index usage.- return f"and(like({materialized_column_sql}, {pattern_sql}), {materialized_column_sql} IS NOT NULL)"- else: # NotLike- # For NOT LIKE, we need ifNull wrapper because NULL NOT LIKE pattern should be TRUE- return f"ifNull(notLike({materialized_column_sql}, {pattern_sql}), 1)"- else:- # Non-nullable columns store null values as the string 'null', so bail out of optimizing and let the- # regular code path handle it, which handles this case- if any(like_matches(pattern_expr.value, s) for s in MAT_COL_NULL_SENTINELS):- return None- pattern_sql = self.visit(pattern_expr)-- # For non-nullable columns with non-sentinel patterns, use raw column for performance- if node.op == ast.CompareOperationOp.Like:- return f"like({materialized_column_sql}, {pattern_sql})"- else: # NotLike- return f"notLike({materialized_column_sql}, {pattern_sql})"-- def _get_optimized_materialized_column_in_operation(self, node: ast.CompareOperation) -> str | None:- """- Returns an optimized printed expression for IN comparisons involving materialized columns.-- For non-nullable columns with values that could match sentinel values ('', 'null'),- we bail out and let the normal code path handle it with proper nullif wrapping.-- For values that cannot match sentinels, we use the raw materialized column directly,- enabling skip index optimization (bloom filter).- """- if node.op not in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):- return None-- left_type = resolve_field_type(node.left)- if not isinstance(left_type, ast.PropertyType):- return None-- if len(left_type.chain) != 1:- return None-- property_source = self._get_materialized_property_source_for_property_type(left_type)- if not isinstance(property_source, PrintableMaterializedColumn):- return None-- if property_source.column.strip("`\"'") in COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING:- return None-- if isinstance(node.right, ast.Constant) and isinstance(node.right.value, str):- values: list[ast.Constant] = [node.right]- elif isinstance(node.right, ast.Tuple) or isinstance(node.right, ast.Array):- values = []- for value in node.right.exprs:- if isinstance(value, ast.Constant) and isinstance(value.value, str):- values.append(value)- else:- return None- else:- return None-- if len(values) == 0:- return None-- materialized_column_sql = str(property_source)-- if property_source.is_nullable:- values_sql = ", ".join(self.visit(v) for v in values)- if node.op == ast.CompareOperationOp.In:- # We use transform_null_in=1 which makes it hard to use a skip index with the in() function in ClickHouse.- # As a workaround, flip the args and use has() - this is safe because we already excluded NULL- return f"and(has([{values_sql}], {materialized_column_sql}), {materialized_column_sql} IS NOT NULL)"- else:- return f"ifNull(notIn({materialized_column_sql}, tuple({values_sql})), 1)"- else:- # non-nullable materialized columns store NULL as 'null' or '', so bail out if the values contain this- for value in values:- if value.value in MAT_COL_NULL_SENTINELS:- return None- values_sql = ", ".join(self.visit(v) for v in values)- if node.op == ast.CompareOperationOp.In:- return f"has([{values_sql}], {materialized_column_sql})"- else:- return f"notIn({materialized_column_sql}, tuple({values_sql}))"-- def _get_optimized_materialized_column_lower_in_operation(self, node: ast.CompareOperation) -> str | None:- """- Optimized printed expression for `lower(<property>) IN (...)`, matching the lower() expression the- bloom_filter_lower / ngram_lower indexes are built on so ClickHouse can pick whichever one exists.- """- if node.op not in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):- return None-- # HogQL `lower` is case-insensitive, so `LOWER(...)` keeps the user-typed casing on the Call- if not (isinstance(node.left, ast.Call) and node.left.name.lower() == "lower" and len(node.left.args) == 1):- return None-- property_source = self._get_materialized_string_property_source(node.left.args[0])- if not isinstance(property_source, PrintableMaterializedColumn) or not (- property_source.has_bloom_filter_lower_index or property_source.has_ngram_lower_index- ):- return None-- if property_source.column.strip("`\"'") in COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING:- return None-- # IN values: a string constant, a tuple/array of constants, or a constant list (from a {placeholder})- if isinstance(node.right, ast.Constant) and isinstance(node.right.value, str):- string_values: list[str] = [node.right.value]- elif isinstance(node.right, ast.Constant) and isinstance(node.right.value, (list, tuple)):- if not all(isinstance(value, str) for value in node.right.value):- return None- string_values = list(node.right.value)- elif isinstance(node.right, (ast.Tuple, ast.Array)):- string_values = []- for value in node.right.exprs:- if isinstance(value, ast.Constant) and isinstance(value.value, str):- string_values.append(value.value)- else:- return None- else:- return None-- if len(string_values) == 0:- return None-- # Bail if an IN value could collide with a stored NULL sentinel: nullable columns alias NULL to ''- # (via coalesce); non-nullable columns store NULL as '' or 'null'. 'null' is a real value when nullable.- null_sentinels = [""] if property_source.is_nullable else MAT_COL_NULL_SENTINELS- if any(value in null_sentinels for value in string_values):- return None-- materialized_column_sql = str(property_source)- values_sql = ", ".join(self.context.add_value(value) for value in string_values)-- # Match the index expression; coalesce() removes NULL so no ifNull / IS NOT NULL guard is needed- if property_source.is_nullable:- indexed_expr = f"lower(coalesce({materialized_column_sql}, ''))"- else:- indexed_expr = f"lower({materialized_column_sql})"-- if node.op == ast.CompareOperationOp.In:- # has() with a constant array keeps the skip index usable (unlike in() under transform_null_in=1)- return f"has([{values_sql}], {indexed_expr})"- else:- return f"notIn({indexed_expr}, tuple({values_sql}))"-def _get_events_session_id_table_type(self, node: ast.Expr) -> ast.BaseTableType | None:"""If the expression resolves to $session_id on the events table, return the table type."""from posthog.hogql.database.schema.events import EventsTable@@ -1188,152 +513,6 @@ class ClickHousePrinter(BasePrinter):return resultreturn []- def _optimize_in_with_string_values(- self, values: list[ast.Expr], property_source: PrintableMaterializedPropertyGroupItem- ) -> str | None:- """- Optimizes an IN comparison against a list of values for property group bloom filter usage.- Returns the optimized expression string, or None if optimization is not possible.- """- # Bail on the optimisation if any value is not a Constant, is the empty string, is NULL, or is not a string- for v in values:- if not isinstance(v, ast.Constant):- return None- if v.value == "" or v.value is None or not isinstance(v.value, str):- return None-- # IN with an empty set of values is always false- if len(values) == 0:- return "0"-- # A problem we run into here is that an expression like- # in(events.properties_group_feature_flags['$feature/onboarding-use-case-selection'], ('control', 'test'))- # does not hit the bloom filter on the key, so we need to modify the expression so that it does-- # If only one value, switch to equality operator. Expressions like this will hit the bloom filter for both keys and values:- # events.properties_group_feature_flags['$feature/onboarding-use-case-selection'] = 'control'- if len(values) == 1:- return f"equals({property_source.value_expr}, {self.visit(values[0])})"-- # With transform_null_in=1 in SETTINGS (which we have by default), if there are several values, we need to- # include a check for whether the key exists to hit the keys bloom filter.- # Unlike the version WITHOUT mapKeys above, the following expression WILL hit the bloom filter:- # and(has(mapKeys(properties_group_feature_flags), '$feature/onboarding-use-case-selection'),- # in(events.properties_group_feature_flags['$feature/onboarding-use-case-selection'], ('control', 'test')))- # Note that we could add a mapValues to this to use the values bloom filter- # TODO to profile whether we should add mapValues. Probably no for flags, yes for properties.- values_tuple = ", ".join(self.visit(v) for v in values)- return f"and({property_source.has_expr}, in({property_source.value_expr}, tuple({values_tuple})))"-- def _get_optimized_property_group_compare_operation(self, node: ast.CompareOperation) -> str | None:- """- Returns a printed expression corresponding to the provided compare operation, if one of the operands is part of- a property group value and: the comparison can be rewritten so that it can be eligible for use by one or more- the property group's bloom filter data skipping indices, or the expression can be optimized to avoid reading the- property group's map ``values`` subcolumn when doing comparisons to NULL values.- """- if self.context.modifiers.propertyGroupsMode != PropertyGroupsMode.OPTIMIZED:- return None-- if node.op in (ast.CompareOperationOp.Eq, ast.CompareOperationOp.NotEq):- # For commutative operations, we can rewrite the expression with parameters in either order without- # affecting the result.- # NOTE: For now, this only works with comparisons to constant values directly since we need to know whether- # or not the non-``PropertyType`` operand is ``NULL`` to be able to rewrite the expression to the correct- # optimized version. This could be extended to support *any* non-``Nullable`` expression as well, so that- # expressions which do not reference a field as part of the expression (and therefore can be resolved to a- # constant value during the initial stages of query execution, e.g. ``lower(concat('X', 'Y'))`` ) can also- # utilize the index. (The same applies to ``In`` comparisons below, too.)- property_type: ast.PropertyType | None = None- constant_expr: ast.Constant | None = None-- # TODO: This doesn't resolve aliases for the constant operand, so this does not comprehensively cover all- # optimizable expressions, but that case seems uncommon enough to avoid for now.- if isinstance(node.right, ast.Constant):- left_type = resolve_field_type(node.left)- if isinstance(left_type, ast.PropertyType):- property_type = left_type- constant_expr = node.right- elif isinstance(node.left, ast.Constant):- right_type = resolve_field_type(node.right)- if isinstance(right_type, ast.PropertyType):- property_type = right_type- constant_expr = node.left-- # TODO: Chained properties could likely be supported here to at least use the keys index.- if property_type is None or len(property_type.chain) > 1:- return None- else:- assert constant_expr is not None # appease mypy - if we got this far, we should have a constant-- property_source = self._get_materialized_property_source_for_property_type(property_type)- if not isinstance(property_source, PrintableMaterializedPropertyGroupItem):- return None-- if node.op == ast.CompareOperationOp.Eq:- if constant_expr.value is None:- # "IS NULL" can be interpreted as "does not exist in the map" -- this avoids unnecessarily reading- # the ``values`` subcolumn of the map.- return f"not({property_source.has_expr})"-- # Equality comparisons to boolean constants can skip NULL checks while maintaining our desired result- # (i.e. comparisons with NULL evaluate to false) since the value expression will return an empty string- # if the property doesn't exist in the map.- if constant_expr.value is True:- return f"equals({property_source.value_expr}, 'true')"- elif constant_expr.value is False:- return f"equals({property_source.value_expr}, 'false')"-- if isinstance(constant_expr.type, ast.StringType):- printed_expr = f"equals({property_source.value_expr}, {self.visit(constant_expr)})"- if constant_expr.value == "":- # If we're comparing to an empty string literal, we need to disambiguate this from the default value- # for the ``Map(String, String)`` type used for storing property group values by also ensuring that- # the property key is present in the map. If this is in a ``WHERE`` clause, this also ensures we can- # still use the data skipping index on keys, even though the values index cannot be used.- printed_expr = f"and({property_source.has_expr}, {printed_expr})"-- return printed_expr-- elif node.op == ast.CompareOperationOp.NotEq:- if constant_expr.value is None:- # "IS NOT NULL" can be interpreted as "does exist in the map" -- this avoids unnecessarily reading- # the ``values`` subcolumn of the map, and also allows us to use the data skipping index on keys.- return property_source.has_expr-- elif node.op in (ast.CompareOperationOp.In):- # ``IN`` is _not_ commutative, so we only need to check the left side operand (in contrast with above.)- left_type = resolve_field_type(node.left)- if not isinstance(left_type, ast.PropertyType):- return None-- # TODO: Chained properties could likely be supported here to at least use the keys index.- if left_type is None or len(left_type.chain) > 1:- return None-- property_source = self._get_materialized_property_source_for_property_type(left_type)- if not isinstance(property_source, PrintableMaterializedPropertyGroupItem):- return None-- if isinstance(node.right, ast.Constant):- if node.right.value is None:- # we can't optimize here, as the unoptimized version returns true if the key doesn't exist OR the value is null- return None- if node.right.value == "":- # If the RHS is the empty string, we need to disambiguate it from the default value for missing keys.- return f"and({property_source.has_expr}, equals({property_source.value_expr}, {self.visit(node.right)}))"- elif isinstance(node.right.type, ast.StringType):- return f"equals({property_source.value_expr}, {self.visit(node.right)})"- elif isinstance(node.right, ast.Tuple) or isinstance(node.right, ast.Array):- return self._optimize_in_with_string_values(node.right.exprs, property_source)- else:- # TODO: Alias types are not resolved here (similarly to equality operations above) so some expressions- # are not optimized that possibly could be if we took that additional step to determine whether or not- # they are references to Constant types.- return None-- return None # nothing to optimize-def _is_events_table_timestamp_field(self, node: ast.Expr) -> bool:traverser = GetFieldsTraverser(node)@@ -1368,29 +547,12 @@ class ClickHousePrinter(BasePrinter):return Falsedef visit_compare_operation(self, node: ast.CompareOperation):- # If either side of the operation is a property that is part of a property group, special optimizations may- # apply here to ensure that data skipping indexes can be used when possible.+ # $session_id comparisons optimize a real column (not a property), so they stay on the printer. Every+ # property-based skip-index rewrite (materialized column, property group) now runs in ClickHouse property+ # resolution, which emits the optimized form as AST before printing (see clickhouse_property_resolution.py).if optimized_session_id := self._get_optimized_session_id_compare_operation(node):return optimized_session_id- if optimized_property_group_compare_operation := self._get_optimized_property_group_compare_operation(node):- return optimized_property_group_compare_operation-- # When comparing an individually materialized column being compared to a string constant,- # we can skip the nullIf wrapping to allow skip index usage.- if optimized_materialized_column_compare := self._get_optimized_materialized_column_equals_operation(node):- return optimized_materialized_column_compare- if optimized_materialized_range := self._get_optimized_materialized_column_range_operation(node):- return optimized_materialized_range- if optimized_materialized_ilike := self._get_optimized_materialized_column_ilike_operation(node):- return optimized_materialized_ilike- if optimized_materialized_like := self._get_optimized_materialized_column_like_operation(node):- return optimized_materialized_like- if optimized_materialized_in := self._get_optimized_materialized_column_in_operation(node):- return optimized_materialized_in- if optimized_materialized_lower_in := self._get_optimized_materialized_column_lower_in_operation(node):- return optimized_materialized_lower_in-in_join_constraint = any(isinstance(item, ast.JoinConstraint) for item in self.stack)# indexHint() is purely an optimizer directive — its result is always true,# so ifNull wrapping inside it is unnecessary and prevents index usage.@@ -1552,6 +714,8 @@ class ClickHousePrinter(BasePrinter):raise ImpossibleASTError("Impossible")def visit_call(self, node: ast.Call):+ # Property-group call optimizations (isNull/isNotNull/JSONHas over a property-group key) now run in ClickHouse+ # property resolution, which rewrites them to the keys-index `has(group, key)` form before printing.# The type-name argument reaches ClickHouse's type parser verbatim, so bound it to# type names we can classify — mirroring the whitelist CAST already enforces.if node.name.lower() in ("accuratecast", "accuratecastornull"):@@ -1561,14 +725,6 @@ class ClickHousePrinter(BasePrinter):if parse_sql_runtime_type(type_arg.value).family == "unknown":raise QueryError(f"Unsupported type in {node.name}: '{type_arg.value}'")- # If the argument(s) are part of a property group, special optimizations may apply here to ensure that data- # skipping indexes can be used when possible.- if optimized_materialized_range_if_null := self._get_optimized_materialized_range_if_null_call(node):- return optimized_materialized_range_if_null-- if optimized_property_group_call := self._get_optimized_property_group_call(node):- return optimized_property_group_call-return super().visit_call(node)def visit_array_slice(self, node: ast.ArraySlice):diff --git a/posthog/hogql/printer/hogql.py b/posthog/hogql/printer/hogql.pyindex 369bcee2f97e..f40c045e81fe 100644--- a/posthog/hogql/printer/hogql.py+++ b/posthog/hogql/printer/hogql.py@@ -15,6 +15,14 @@ class HogQLPrinter(BasePrinter):DIALECT_NAME: ClassVar[HogQLDialect] = "hogql"+ def visit_property_access(self, node: ast.PropertyAccess) -> str:+ # A lowered `properties.$x` read prints back as the HogQL property chain it came from, not the ClickHouse+ # `JSONExtractRaw(...)` form the base renderer emits — so `dialect="hogql"` stays valid, re-parseable HogQL+ # (e.g. the stored batch-export `hogql_query`). The keys join onto the blob field as chain access.+ parts = [self.visit(node.expr)]+ parts.extend(self._print_identifier(str(key)) for key in node.keys)+ return ".".join(parts)+def _render_aggregation_name(self, node: ast.Call, func_meta) -> str:return node.namediff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.pyindex b29227c6ab4e..1b57d5065b61 100644--- a/posthog/hogql/printer/postgres.py+++ b/posthog/hogql/printer/postgres.py@@ -454,6 +454,11 @@ class PostgresPrinter(BasePrinter):if isinstance(column, ast.Field) and isinstance(column.type, ast.PropertyType):alias_name = ".".join(map(str, column.chain))column = ast.Alias(alias=alias_name, expr=column)+ elif isinstance(column, ast.PropertyAccess) and isinstance(column.expr, ast.Field):+ # A lowered property read: reconstruct the same `properties.X` column name the un-lowered Field above+ # would get (source chain + keys), so logical lowering doesn't change the result column name.+ alias_name = ".".join(map(str, [*column.expr.chain, *column.keys]))+ column = ast.Alias(alias=alias_name, expr=column)columns_sql.append(self.visit(column))return columns_sqldiff --git a/posthog/hogql/printer/test/__snapshots__/test_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_printer.ambrindex 6c1811ad2b8f..b84ebee14977 100644--- a/posthog/hogql/printer/test/__snapshots__/test_printer.ambr+++ b/posthog/hogql/printer/test/__snapshots__/test_printer.ambr@@ -283,7 +283,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%@posthog.com'), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%@posthog.com'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -363,7 +363,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '[email protected]'), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '[email protected]'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -403,7 +403,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%null%'), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%null%'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -443,7 +443,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%'), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -483,7 +483,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, ''), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, ''), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -763,7 +763,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%@posthog.com')), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%@posthog.com')), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -843,7 +843,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('[email protected]')), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('[email protected]')), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -883,7 +883,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%null%')), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%null%')), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -923,7 +923,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%')), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%')), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -963,7 +963,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('')), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('')), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1563,7 +1563,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1603,7 +1603,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has([''], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has([''], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1643,7 +1643,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'null'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'null'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1683,7 +1683,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', ''], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', ''], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1723,7 +1723,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'other_value'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'other_value'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1763,7 +1763,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['null'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['null'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1803,7 +1803,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['NULL'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['NULL'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -1843,7 +1843,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['null', 'NULL'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['null', 'NULL'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2203,7 +2203,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2243,7 +2243,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has([''], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has([''], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2283,7 +2283,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'null'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'null'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2323,7 +2323,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', ''], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', ''], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2363,7 +2363,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'other_value'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['[email protected]', 'other_value'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2403,7 +2403,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['null'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['null'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2443,7 +2443,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['NULL'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['NULL'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2483,7 +2483,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), and(has(['null', 'NULL'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['null', 'NULL'], events.mat_test_prop), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -2992,8 +2992,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), (equals(events.mat_test_prop, 'target_value')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.mat_test_prop, 'target_value'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -3073,8 +3072,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, 'mango')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, 'mango'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -3094,8 +3092,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), (greaterOrEquals(events.mat_test_prop, 'mango')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.mat_test_prop, 'mango'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -3115,9 +3112,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, 'mango')- AND notEquals(events.mat_test_prop, '')- AND notEquals(events.mat_test_prop, 'null')))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, 'mango'), notEquals(events.mat_test_prop, ''), notEquals(events.mat_test_prop, 'null')))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -3137,9 +3132,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), (greaterOrEquals(events.mat_test_prop, 'mango')- AND notEquals(events.mat_test_prop, '')- AND notEquals(events.mat_test_prop, 'null')))+ WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.mat_test_prop, 'mango'), notEquals(events.mat_test_prop, ''), notEquals(events.mat_test_prop, 'null')))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -3373,10 +3366,10 @@'SELECT e.event AS event FROM (SELECT events.uuid AS uuid, events.event AS event, events.properties AS properties, toTimeZone(events.timestamp, %(hogql_val_3)s) AS timestamp, events.distinct_id AS distinct_id, events.elements_chain AS elements_chain, toTimeZone(events.created_at, %(hogql_val_4)s) AS created_at, events.`$session_id` AS `$session_id`, events.`$window_id` AS `$window_id`, events.person_mode AS person_mode, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, events.`$group_0` AS `$group_0`, events.`$group_1` AS `$group_1`, events.`$group_2` AS `$group_2`, events.`$group_3` AS `$group_3`, events.`$group_4` AS `$group_4`, events.elements_chain_href AS elements_chain_href, events.elements_chain_texts AS elements_chain_texts, events.elements_chain_ids AS elements_chain_ids, events.elements_chain_elements AS elements_chain_elements, events.person_id AS event_person_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_5)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_6)s) AS event_issue_id, if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_7)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_8)s)) AS issue_id, events__fingerprint_issue_state.issue_id AS issue_id_v2, events__fingerprint_issue_state.issue_name AS issue_name, events__fingerprint_issue_state.issue_description AS issue_description, events__fingerprint_issue_state.issue_status AS issue_status, events__fingerprint_issue_state.assigned_user_id AS issue_assigned_user_id, events__fingerprint_issue_state.assigned_role_id AS issue_assigned_role_id, events__fingerprint_issue_state.first_seen AS issue_first_seen FROM events LEFT OUTER JOIN (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_name), error_tracking_fingerprint_issue_state.version), 1)) AS issue_name, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_description), error_tracking_fingerprint_issue_state.version), 1)) AS issue_description, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_status), error_tracking_fingerprint_issue_state.version), 1)) AS issue_status, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_user_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_user_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_role_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_role_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, %(hogql_val_0)s)), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen FROM error_tracking_fingerprint_issue_state WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999) GROUP BY fp_hash HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\')), events__fingerprint_issue_state.fp_hash) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.issue_id), error_tracking_issue_fingerprint_overrides.version), 1) AS issue_id, error_tracking_issue_fingerprint_overrides.fingerprint AS fingerprint FROM error_tracking_issue_fingerprint_overrides WHERE equals(error_tracking_issue_fingerprint_overrides.team_id, 99999) GROUP BY error_tracking_issue_fingerprint_overrides.fingerprint HAVING equals(tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.is_deleted), error_tracking_issue_fingerprint_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__exception_issue_override ON equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), \'\'), \'null\'), \'^"|"$\', \'\'), events__exception_issue_override.fingerprint) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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, 99999) GROUP BY person_distinct_id_overrides.distinct_id HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) WHERE equals(events.team_id, 99999)) AS e LEFT JOIN (SELECT person.id AS id FROM person WHERE equals(person.team_id, 99999) GROUP BY person.id HAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, %(hogql_val_9)s)), person.version), 1), plus(now64(6, %(hogql_val_10)s), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, e.person_id) LIMIT 50000'# ---# name: TestPrinter.test_projection_pushdown_preserves_where_columns_0_with_optimize_projections- 'SELECT sub.event AS event FROM (SELECT events.event AS event, events.distinct_id AS distinct_id, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_3)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_4)s) AS event_issue_id, if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_5)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_6)s)) AS issue_id, events__fingerprint_issue_state.issue_id AS issue_id_v2, events__fingerprint_issue_state.issue_name AS issue_name, events__fingerprint_issue_state.issue_description AS issue_description, events__fingerprint_issue_state.issue_status AS issue_status, events__fingerprint_issue_state.assigned_user_id AS issue_assigned_user_id, events__fingerprint_issue_state.assigned_role_id AS issue_assigned_role_id, events__fingerprint_issue_state.first_seen AS issue_first_seen FROM events LEFT OUTER JOIN (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_name), error_tracking_fingerprint_issue_state.version), 1)) AS issue_name, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_description), error_tracking_fingerprint_issue_state.version), 1)) AS issue_description, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_status), error_tracking_fingerprint_issue_state.version), 1)) AS issue_status, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_user_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_user_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_role_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_role_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, %(hogql_val_0)s)), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen FROM error_tracking_fingerprint_issue_state WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999) GROUP BY fp_hash HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\')), events__fingerprint_issue_state.fp_hash) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.issue_id), error_tracking_issue_fingerprint_overrides.version), 1) AS issue_id, error_tracking_issue_fingerprint_overrides.fingerprint AS fingerprint FROM error_tracking_issue_fingerprint_overrides WHERE equals(error_tracking_issue_fingerprint_overrides.team_id, 99999) GROUP BY error_tracking_issue_fingerprint_overrides.fingerprint HAVING equals(tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.is_deleted), error_tracking_issue_fingerprint_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__exception_issue_override ON equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), \'\'), \'null\'), \'^"|"$\', \'\'), events__exception_issue_override.fingerprint) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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, 99999) GROUP BY person_distinct_id_overrides.distinct_id HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) WHERE equals(events.team_id, 99999)) AS sub WHERE ifNull(equals(sub.distinct_id, %(hogql_val_7)s), 0) LIMIT 50000'+ 'SELECT sub.event AS event FROM (SELECT events.event AS event, events.distinct_id AS distinct_id, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_3)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_4)s) AS event_issue_id, if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_5)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_6)s)) AS issue_id, events__fingerprint_issue_state.issue_id AS issue_id_v2, events__fingerprint_issue_state.issue_name AS issue_name, events__fingerprint_issue_state.issue_description AS issue_description, events__fingerprint_issue_state.issue_status AS issue_status, events__fingerprint_issue_state.assigned_user_id AS issue_assigned_user_id, events__fingerprint_issue_state.assigned_role_id AS issue_assigned_role_id, events__fingerprint_issue_state.first_seen AS issue_first_seen FROM events LEFT OUTER JOIN (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_name), error_tracking_fingerprint_issue_state.version), 1)) AS issue_name, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_description), error_tracking_fingerprint_issue_state.version), 1)) AS issue_description, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_status), error_tracking_fingerprint_issue_state.version), 1)) AS issue_status, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_user_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_user_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_role_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_role_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, %(hogql_val_0)s)), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen FROM error_tracking_fingerprint_issue_state WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999) GROUP BY fp_hash HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\')), events__fingerprint_issue_state.fp_hash) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.issue_id), error_tracking_issue_fingerprint_overrides.version), 1) AS issue_id, error_tracking_issue_fingerprint_overrides.fingerprint AS fingerprint FROM error_tracking_issue_fingerprint_overrides WHERE equals(error_tracking_issue_fingerprint_overrides.team_id, 99999) GROUP BY error_tracking_issue_fingerprint_overrides.fingerprint HAVING equals(tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.is_deleted), error_tracking_issue_fingerprint_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__exception_issue_override ON equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), \'\'), \'null\'), \'^"|"$\', \'\'), events__exception_issue_override.fingerprint) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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, 99999) GROUP BY person_distinct_id_overrides.distinct_id HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) WHERE equals(events.team_id, 99999)) AS sub WHERE equals(sub.distinct_id, %(hogql_val_7)s) LIMIT 50000'# ---# name: TestPrinter.test_projection_pushdown_preserves_where_columns_1_without_optimize_projections- 'SELECT sub.event AS event FROM (SELECT events.uuid AS uuid, events.event AS event, events.properties AS properties, toTimeZone(events.timestamp, %(hogql_val_3)s) AS timestamp, events.distinct_id AS distinct_id, events.elements_chain AS elements_chain, toTimeZone(events.created_at, %(hogql_val_4)s) AS created_at, events.`$session_id` AS `$session_id`, events.`$window_id` AS `$window_id`, events.person_mode AS person_mode, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, events.`$group_0` AS `$group_0`, events.`$group_1` AS `$group_1`, events.`$group_2` AS `$group_2`, events.`$group_3` AS `$group_3`, events.`$group_4` AS `$group_4`, events.elements_chain_href AS elements_chain_href, events.elements_chain_texts AS elements_chain_texts, events.elements_chain_ids AS elements_chain_ids, events.elements_chain_elements AS elements_chain_elements, events.person_id AS event_person_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_5)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_6)s) AS event_issue_id, if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_7)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_8)s)) AS issue_id, events__fingerprint_issue_state.issue_id AS issue_id_v2, events__fingerprint_issue_state.issue_name AS issue_name, events__fingerprint_issue_state.issue_description AS issue_description, events__fingerprint_issue_state.issue_status AS issue_status, events__fingerprint_issue_state.assigned_user_id AS issue_assigned_user_id, events__fingerprint_issue_state.assigned_role_id AS issue_assigned_role_id, events__fingerprint_issue_state.first_seen AS issue_first_seen FROM events LEFT OUTER JOIN (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_name), error_tracking_fingerprint_issue_state.version), 1)) AS issue_name, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_description), error_tracking_fingerprint_issue_state.version), 1)) AS issue_description, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_status), error_tracking_fingerprint_issue_state.version), 1)) AS issue_status, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_user_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_user_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_role_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_role_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, %(hogql_val_0)s)), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen FROM error_tracking_fingerprint_issue_state WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999) GROUP BY fp_hash HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\')), events__fingerprint_issue_state.fp_hash) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.issue_id), error_tracking_issue_fingerprint_overrides.version), 1) AS issue_id, error_tracking_issue_fingerprint_overrides.fingerprint AS fingerprint FROM error_tracking_issue_fingerprint_overrides WHERE equals(error_tracking_issue_fingerprint_overrides.team_id, 99999) GROUP BY error_tracking_issue_fingerprint_overrides.fingerprint HAVING equals(tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.is_deleted), error_tracking_issue_fingerprint_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__exception_issue_override ON equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), \'\'), \'null\'), \'^"|"$\', \'\'), events__exception_issue_override.fingerprint) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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, 99999) GROUP BY person_distinct_id_overrides.distinct_id HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) WHERE equals(events.team_id, 99999)) AS sub WHERE ifNull(equals(sub.distinct_id, %(hogql_val_9)s), 0) LIMIT 50000'+ 'SELECT sub.event AS event FROM (SELECT events.uuid AS uuid, events.event AS event, events.properties AS properties, toTimeZone(events.timestamp, %(hogql_val_3)s) AS timestamp, events.distinct_id AS distinct_id, events.elements_chain AS elements_chain, toTimeZone(events.created_at, %(hogql_val_4)s) AS created_at, events.`$session_id` AS `$session_id`, events.`$window_id` AS `$window_id`, events.person_mode AS person_mode, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, events.`$group_0` AS `$group_0`, events.`$group_1` AS `$group_1`, events.`$group_2` AS `$group_2`, events.`$group_3` AS `$group_3`, events.`$group_4` AS `$group_4`, events.elements_chain_href AS elements_chain_href, events.elements_chain_texts AS elements_chain_texts, events.elements_chain_ids AS elements_chain_ids, events.elements_chain_elements AS elements_chain_elements, events.person_id AS event_person_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_5)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_6)s) AS event_issue_id, if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_7)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_8)s)) AS issue_id, events__fingerprint_issue_state.issue_id AS issue_id_v2, events__fingerprint_issue_state.issue_name AS issue_name, events__fingerprint_issue_state.issue_description AS issue_description, events__fingerprint_issue_state.issue_status AS issue_status, events__fingerprint_issue_state.assigned_user_id AS issue_assigned_user_id, events__fingerprint_issue_state.assigned_role_id AS issue_assigned_role_id, events__fingerprint_issue_state.first_seen AS issue_first_seen FROM events LEFT OUTER JOIN (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_name), error_tracking_fingerprint_issue_state.version), 1)) AS issue_name, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_description), error_tracking_fingerprint_issue_state.version), 1)) AS issue_description, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_status), error_tracking_fingerprint_issue_state.version), 1)) AS issue_status, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_user_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_user_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_role_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_role_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, %(hogql_val_0)s)), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen FROM error_tracking_fingerprint_issue_state WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999) GROUP BY fp_hash HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\')), events__fingerprint_issue_state.fp_hash) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.issue_id), error_tracking_issue_fingerprint_overrides.version), 1) AS issue_id, error_tracking_issue_fingerprint_overrides.fingerprint AS fingerprint FROM error_tracking_issue_fingerprint_overrides WHERE equals(error_tracking_issue_fingerprint_overrides.team_id, 99999) GROUP BY error_tracking_issue_fingerprint_overrides.fingerprint HAVING equals(tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.is_deleted), error_tracking_issue_fingerprint_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__exception_issue_override ON equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), \'\'), \'null\'), \'^"|"$\', \'\'), events__exception_issue_override.fingerprint) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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, 99999) GROUP BY person_distinct_id_overrides.distinct_id HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) WHERE equals(events.team_id, 99999)) AS sub WHERE equals(sub.distinct_id, %(hogql_val_9)s) LIMIT 50000'# ---# name: TestPrinter.test_projection_pushdown_simple_asterisk_subquery_0_with_optimize_projections'SELECT sub.event AS event FROM (SELECT events.event AS event, if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_3)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_4)s) AS event_issue_id, if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_5)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_6)s)) AS issue_id, events__fingerprint_issue_state.issue_id AS issue_id_v2, events__fingerprint_issue_state.issue_name AS issue_name, events__fingerprint_issue_state.issue_description AS issue_description, events__fingerprint_issue_state.issue_status AS issue_status, events__fingerprint_issue_state.assigned_user_id AS issue_assigned_user_id, events__fingerprint_issue_state.assigned_role_id AS issue_assigned_role_id, events__fingerprint_issue_state.first_seen AS issue_first_seen FROM events LEFT OUTER JOIN (SELECT cityHash64(error_tracking_fingerprint_issue_state.fingerprint) AS fp_hash, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_id), error_tracking_fingerprint_issue_state.version), 1)) AS issue_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_name), error_tracking_fingerprint_issue_state.version), 1)) AS issue_name, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_description), error_tracking_fingerprint_issue_state.version), 1)) AS issue_description, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.issue_status), error_tracking_fingerprint_issue_state.version), 1)) AS issue_status, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_user_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_user_id, toNullable(tupleElement(argMax(tuple(error_tracking_fingerprint_issue_state.assigned_role_id), error_tracking_fingerprint_issue_state.version), 1)) AS assigned_role_id, toNullable(tupleElement(argMax(tuple(toTimeZone(error_tracking_fingerprint_issue_state.first_seen, %(hogql_val_0)s)), error_tracking_fingerprint_issue_state.version), 1)) AS first_seen FROM error_tracking_fingerprint_issue_state WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999) GROUP BY fp_hash HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\')), events__fingerprint_issue_state.fp_hash) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.issue_id), error_tracking_issue_fingerprint_overrides.version), 1) AS issue_id, error_tracking_issue_fingerprint_overrides.fingerprint AS fingerprint FROM error_tracking_issue_fingerprint_overrides WHERE equals(error_tracking_issue_fingerprint_overrides.team_id, 99999) GROUP BY error_tracking_issue_fingerprint_overrides.fingerprint HAVING equals(tupleElement(argMax(tuple(error_tracking_issue_fingerprint_overrides.is_deleted), error_tracking_issue_fingerprint_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__exception_issue_override ON equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), \'\'), \'null\'), \'^"|"$\', \'\'), events__exception_issue_override.fingerprint) LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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, 99999) GROUP BY person_distinct_id_overrides.distinct_id HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) WHERE equals(events.team_id, 99999)) AS sub LIMIT 50000'diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 723526565992..4ead4cd10703 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -713,7 +713,7 @@ class TestPrinter(BaseTest):self.assertEqual(self._expr("properties['foo']", context),- "has(events.properties_group_custom, %(hogql_val_0)s) ? events.properties_group_custom[%(hogql_val_0)s] : null",+ "if(has(events.properties_group_custom, %(hogql_val_0)s), events.properties_group_custom[%(hogql_val_1)s], NULL)",)self.assertEqual(context.values["hogql_val_0"], "foo")@@ -737,7 +737,7 @@ class TestPrinter(BaseTest):self.assertEqual(self._expr("person.properties['foo']", context),- "has(events.person_properties_map_custom, %(hogql_val_0)s) ? events.person_properties_map_custom[%(hogql_val_0)s] : null",+ "if(has(events.person_properties_map_custom, %(hogql_val_0)s), events.person_properties_map_custom[%(hogql_val_1)s], NULL)",)self.assertEqual(context.values["hogql_val_0"], "foo")@@ -885,14 +885,14 @@ class TestPrinter(BaseTest):# filter so it won't be used here.self._test_property_group_comparison("properties.key = '' as eq",- "and(has(events.properties_group_custom, %(hogql_val_0)s), equals(events.properties_group_custom[%(hogql_val_0)s], %(hogql_val_1)s)) AS eq",- {"hogql_val_0": "key", "hogql_val_1": ""},+ "and(has(events.properties_group_custom, %(hogql_val_0)s), equals(events.properties_group_custom[%(hogql_val_1)s], %(hogql_val_2)s)) AS eq",+ {"hogql_val_0": "key", "hogql_val_1": "key", "hogql_val_2": ""},expected_skip_indexes_used={"properties_group_custom_keys_bf"},)self._test_property_group_comparison("equals(properties.key, '') as eq",- "and(has(events.properties_group_custom, %(hogql_val_0)s), equals(events.properties_group_custom[%(hogql_val_0)s], %(hogql_val_1)s)) AS eq",- {"hogql_val_0": "key", "hogql_val_1": ""},+ "and(has(events.properties_group_custom, %(hogql_val_0)s), equals(events.properties_group_custom[%(hogql_val_1)s], %(hogql_val_2)s)) AS eq",+ {"hogql_val_0": "key", "hogql_val_1": "key", "hogql_val_2": ""},expected_skip_indexes_used={"properties_group_custom_keys_bf"},)@@ -961,15 +961,15 @@ class TestPrinter(BaseTest):# We check which skip indexes are used on the test DB, but please test this on a prod-sized DB too when changing this.self._test_property_group_comparison("properties.key IN ('a', 'b')",- "and(has(events.properties_group_custom, %(hogql_val_0)s), in(events.properties_group_custom[%(hogql_val_0)s], tuple(%(hogql_val_1)s, %(hogql_val_2)s)))",- {"hogql_val_0": "key", "hogql_val_1": "a", "hogql_val_2": "b"},+ "and(has(events.properties_group_custom, %(hogql_val_0)s), in(events.properties_group_custom[%(hogql_val_1)s], tuple(%(hogql_val_2)s, %(hogql_val_3)s)))",+ {"hogql_val_0": "key", "hogql_val_1": "key", "hogql_val_2": "a", "hogql_val_3": "b"},expected_skip_indexes_used={"properties_group_custom_keys_bf"},expected_skip_indexes_not_used={"properties_group_custom_values_bf"},)self._test_property_group_comparison("properties.key IN ['a', 'b']",- "and(has(events.properties_group_custom, %(hogql_val_0)s), in(events.properties_group_custom[%(hogql_val_0)s], tuple(%(hogql_val_1)s, %(hogql_val_2)s)))",- {"hogql_val_0": "key", "hogql_val_1": "a", "hogql_val_2": "b"},+ "and(has(events.properties_group_custom, %(hogql_val_0)s), in(events.properties_group_custom[%(hogql_val_1)s], tuple(%(hogql_val_2)s, %(hogql_val_3)s)))",+ {"hogql_val_0": "key", "hogql_val_1": "key", "hogql_val_2": "a", "hogql_val_3": "b"},expected_skip_indexes_used={"properties_group_custom_keys_bf"},expected_skip_indexes_not_used={"properties_group_custom_values_bf"},)@@ -991,8 +991,8 @@ class TestPrinter(BaseTest):# Single empty string does need to check if the key exists as well as equalityself._test_property_group_comparison("properties.key IN ''",- "and(has(events.properties_group_custom, %(hogql_val_0)s), equals(events.properties_group_custom[%(hogql_val_0)s], %(hogql_val_1)s))",- {"hogql_val_0": "key", "hogql_val_1": ""},+ "and(has(events.properties_group_custom, %(hogql_val_0)s), equals(events.properties_group_custom[%(hogql_val_1)s], %(hogql_val_2)s))",+ {"hogql_val_0": "key", "hogql_val_1": "key", "hogql_val_2": ""},expected_skip_indexes_used={"properties_group_custom_keys_bf"},expected_skip_indexes_not_used={"properties_group_custom_values_bf"},)@@ -1010,19 +1010,19 @@ class TestPrinter(BaseTest):) # if changing this assumption, you'll need to change the printer tooself._test_property_group_comparison("properties.key in NULL",- "in(has(events.properties_group_custom, %(hogql_val_2)s) ? events.properties_group_custom[%(hogql_val_2)s] : null, NULL)",+ "in(if(has(events.properties_group_custom, %(hogql_val_0)s), events.properties_group_custom[%(hogql_val_1)s], NULL), NULL)",)self._test_property_group_comparison("properties.key in (NULL)",- "in(has(events.properties_group_custom, %(hogql_val_2)s) ? events.properties_group_custom[%(hogql_val_2)s] : null, NULL)",+ "in(if(has(events.properties_group_custom, %(hogql_val_0)s), events.properties_group_custom[%(hogql_val_1)s], NULL), NULL)",)self._test_property_group_comparison("properties.key in (NULL, NULL, NULL)",- "in(has(events.properties_group_custom, %(hogql_val_2)s) ? events.properties_group_custom[%(hogql_val_2)s] : null, tuple(NULL, NULL, NULL))",+ "in(if(has(events.properties_group_custom, %(hogql_val_0)s), events.properties_group_custom[%(hogql_val_1)s], NULL), tuple(NULL, NULL, NULL))",)self._test_property_group_comparison("properties.key in [NULL, NULL, NULL]",- "in(has(events.properties_group_custom, %(hogql_val_2)s) ? events.properties_group_custom[%(hogql_val_2)s] : null, [NULL, NULL, NULL])",+ "in(if(has(events.properties_group_custom, %(hogql_val_0)s), events.properties_group_custom[%(hogql_val_1)s], NULL), [NULL, NULL, NULL])",)# Don't optimize comparisons to types that require additional type conversions.@@ -1156,9 +1156,9 @@ class TestPrinter(BaseTest):parsed = parse_select("SELECT properties.file_type AS ft FROM events WHERE ft = 'image/svg'")printed, _ = prepare_and_print_ast(parsed, build_context(PropertyGroupsMode.OPTIMIZED), dialect="clickhouse")assert printed == (- "SELECT has(events.properties_group_custom, %(hogql_val_0)s) ? events.properties_group_custom[%(hogql_val_0)s] : null AS ft "+ "SELECT if(has(events.properties_group_custom, %(hogql_val_0)s), events.properties_group_custom[%(hogql_val_1)s], NULL) AS ft ""FROM events "- f"WHERE and(equals(events.team_id, {self.team.pk}), equals(events.properties_group_custom[%(hogql_val_1)s], %(hogql_val_2)s)) "+ f"WHERE and(equals(events.team_id, {self.team.pk}), equals(events.properties_group_custom[%(hogql_val_2)s], %(hogql_val_3)s)) ""LIMIT 50000")@@ -1172,6 +1172,36 @@ class TestPrinter(BaseTest):== prepare_and_print_ast(parsed, build_context(PropertyGroupsMode.ENABLED), dialect="clickhouse")[0])+ def _print_shadowed_alias_query(self) -> str:+ # Two aliases share the name `a`: the outer one is a property read, the inner one is `event`. The inner+ # `WHERE a = 'v'` must compare the inner alias — never the outer query's property.+ context = HogQLContext(+ team_id=self.team.pk,+ enable_select_queries=True,+ modifiers=HogQLQueryModifiers(+ materializationMode=MaterializationMode.AUTO,+ propertyGroupsMode=PropertyGroupsMode.OPTIMIZED,+ ),+ )+ parsed = parse_select(+ "SELECT properties.file_type AS a FROM events WHERE event IN (SELECT event AS a FROM events WHERE a = 'v')"+ )+ printed, _ = prepare_and_print_ast(parsed, context, dialect="clickhouse")+ return printed++ def test_property_alias_shadowed_in_subquery_is_not_rebound(self):+ printed = self._print_shadowed_alias_query()+ inner = printed.split("SELECT", 2)[2]+ assert "properties_group_custom" not in inner, f"inner alias rebound to the outer property:\n{printed}"+ assert "equals(a," in inner, f"expected the inner comparison to stay on the inner alias:\n{printed}"++ def test_materialized_property_alias_shadowed_in_subquery_is_not_rebound(self):+ with materialized("events", "file_type"):+ printed = self._print_shadowed_alias_query()+ inner = printed.split("SELECT", 2)[2]+ assert "file_type" not in inner, f"inner alias rebound to the outer materialized property:\n{printed}"+ assert "equals(a," in inner, f"expected the inner comparison to stay on the inner alias:\n{printed}"+def test_methods(self):self.assertEqual(self._expr("count()"), "count()")self.assertEqual(self._expr("count(distinct event)"), "count(DISTINCT events.event)")@@ -2324,18 +2354,18 @@ class TestPrinter(BaseTest):assert generated_sql_statements1 == generated_sql_statements2assert generated_sql_statements1 == (f"SELECT "+ # The view projects min(...)/sum(...), which resolve non-nullable, and the printer reads a subquery+ # column's nullability from its resolved type — so every comparison below prints bare, no ifNull wrapping.# start_time = toStartOfMonth(now())- # (the return of toStartOfMonth() is treated as "potentially nullable" since we yet have full typing support)- f"ifNull(equals(session_replay_events.start_time, toStartOfMonth(now64(6, %(hogql_val_1)s))), "- f"isNull(session_replay_events.start_time) and isNull(toStartOfMonth(now64(6, %(hogql_val_1)s)))) AS a, "+ f"equals(session_replay_events.start_time, toStartOfMonth(now64(6, %(hogql_val_1)s))) AS a, "# 1 = 1f"1 AS b, "# click_count = 1- f"ifNull(equals(session_replay_events.click_count, 1), 0) AS c, "+ f"equals(session_replay_events.click_count, 1) AS c, "# 1 = click_count- f"ifNull(equals(1, session_replay_events.click_count), 0) AS d, "+ f"equals(1, session_replay_events.click_count) AS d, "# click_count = keypress_count- f"ifNull(equals(session_replay_events.click_count, session_replay_events.keypress_count), isNull(session_replay_events.click_count) and isNull(session_replay_events.keypress_count)) AS e, "+ f"equals(session_replay_events.click_count, session_replay_events.keypress_count) AS e, "# click_count = nullf"isNull(session_replay_events.click_count) AS f, "# null = click_count@@ -2358,26 +2388,47 @@ class TestPrinter(BaseTest):assert generated_sql1 == generated_sql2assert generated_sql1 == (f"SELECT "- # start_time = toStartOfMonth(now())- # (the return of toStartOfMonth() is treated as "potentially nullable" since we yet have full typing support)- f"ifNull(notEquals(session_replay_events.start_time, toStartOfMonth(now64(6, %(hogql_val_1)s))), "- f"isNotNull(session_replay_events.start_time) or isNotNull(toStartOfMonth(now64(6, %(hogql_val_1)s)))) AS a, "- # 1 = 1+ # Same as test_field_nullable_equals: non-nullable view columns print bare comparisons.+ # start_time != toStartOfMonth(now())+ f"notEquals(session_replay_events.start_time, toStartOfMonth(now64(6, %(hogql_val_1)s))) AS a, "+ # 1 != 1f"0 AS b, "- # click_count = 1- f"ifNull(notEquals(session_replay_events.click_count, 1), 1) AS c, "- # 1 = click_count- f"ifNull(notEquals(1, session_replay_events.click_count), 1) AS d, "- # click_count = keypress_count- f"ifNull(notEquals(session_replay_events.click_count, session_replay_events.keypress_count), isNotNull(session_replay_events.click_count) or isNotNull(session_replay_events.keypress_count)) AS e, "- # click_count = null+ # click_count != 1+ f"notEquals(session_replay_events.click_count, 1) AS c, "+ # 1 != click_count+ f"notEquals(1, session_replay_events.click_count) AS d, "+ # click_count != keypress_count+ f"notEquals(session_replay_events.click_count, session_replay_events.keypress_count) AS e, "+ # click_count != nullf"isNotNull(session_replay_events.click_count) AS f, "- # null = click_count+ # null != click_countf"isNotNull(session_replay_events.click_count) AS g "# ...f"FROM (SELECT min(toTimeZone(session_replay_events.min_first_timestamp, %(hogql_val_0)s)) AS start_time, sum(session_replay_events.click_count) AS click_count, sum(session_replay_events.keypress_count) AS keypress_count FROM session_replay_events WHERE equals(session_replay_events.team_id, {self.team.pk})) AS session_replay_events LIMIT {MAX_SELECT_RETURNED_ROWS}")+ def test_subquery_column_nullability_drives_comparison_wrapping(self):+ # The printer reads a subquery column's nullability from its resolved type. Both directions matter: a+ # genuinely nullable projection must KEEP its ifNull comparison guard (erasing it would change NULL semantics+ # outside filter position), and a non-nullable projection prints bare (wrapping it hides the column from+ # join-key detection and skip indexes).+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=Database())+ context.database.get_table("events").fields["nullable_field"] = StringDatabaseField( # type: ignore+ name="nullable_field", nullable=True+ )+ printed_nullable = self._select(+ "SELECT x = 'a' AS matches FROM (SELECT nullable_field AS x FROM events) AS sub",+ context,+ )+ assert "ifNull(equals(sub.x, %(hogql_val_0)s), 0) AS matches" in printed_nullable, printed_nullable++ printed_non_nullable = self._select(+ "SELECT x = 'a' AS matches FROM (SELECT event AS x FROM events) AS sub",+ HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=Database()),+ )+ assert "equals(sub.x, %(hogql_val_0)s) AS matches" in printed_non_nullable, printed_non_nullable+ assert "ifNull" not in printed_non_nullable.split("FROM")[0], printed_non_nullable+def test_field_nullable_not_in(self):context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=Database())context.database.get_table("events").fields["nullable_field"] = StringDatabaseField( # type: ignore@@ -2472,7 +2523,7 @@ class TestPrinter(BaseTest):"hogql_val_5": [1, 0],}- @patch("posthog.hogql.printer.base.get_materialized_column_for_property")+ @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")def test_ai_trace_id_optimizations(self, mock_get_mat_col):"""Test that $ai_trace_id gets special treatment for bloom filter index optimization"""@@ -2548,7 +2599,7 @@ class TestPrinter(BaseTest):sql,)- @patch("posthog.hogql.printer.base.get_materialized_column_for_property")+ @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")def test_ai_session_id_optimizations(self, mock_get_mat_col):"""Test that $ai_session_id gets special treatment for bloom filter index optimization"""@@ -2599,6 +2650,58 @@ class TestPrinter(BaseTest):)self.assertNotIn("ifNull(in", sql)+ @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")+ def test_materialized_property_through_column_aliased_table(self, mock_get_mat_col):+ # A property read through a column-renamed table (`FROM events AS e (...)`, a ColumnAliasedTableType) must still+ # resolve to its materialized column. Property resolution has to unwrap that table type to reach the real table; if+ # it doesn't, the read silently falls back to a slow JSONExtract over the raw blob.+ from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails++ mock_get_mat_col.return_value = MaterializedColumn(+ name="mat_foo",+ details=MaterializedColumnDetails(table_column="properties", property_name="foo", is_disabled=False),+ is_nullable=False,+ )+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ sql = self._select("SELECT e.properties.foo FROM events AS e (a, b)", context)+ self.assertIn("mat_foo", sql)+ self.assertNotIn("JSONExtractRaw(events.properties", sql)++ @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")+ def test_deep_key_materialized_read_prints_shared_json_extract_shape(self, mock_get_mat_col):+ # Reading properties.foo.bar through materialized column mat_foo extracts key "bar" from the column value.+ # That extract must print exactly what `json_extract_trim_quotes` (kafka_engine.py) builds — the one+ # implementation of the extract-and-trim SQL shape, which backfill and ingest also match byte-for-byte.+ from posthog.clickhouse.kafka_engine import json_extract_trim_quotes++ from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails++ mock_get_mat_col.return_value = MaterializedColumn(+ name="mat_foo",+ details=MaterializedColumnDetails(table_column="properties", property_name="foo", is_disabled=False),+ is_nullable=False,+ )+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ printed = self._expr("properties.foo.bar", context)+ head = "nullIf(nullIf(events.mat_foo, ''), 'null')"+ self.assertEqual(printed, json_extract_trim_quotes(head, "%(hogql_val_0)s"))+ self.assertEqual(context.values, {"hogql_val_0": "bar"})++ def _print_constant(self, node: ast.Constant) -> str:+ return print_prepared_ast(+ node, HogQLContext(team_id=self.team.pk, enable_select_queries=True), "clickhouse", stack=[]+ )++ def test_inline_sentinel_renders_allowlisted_literal_inline(self):+ # An allowlisted scrubbing sentinel renders inline (escaped), not as a bound parameter.+ self.assertEqual(self._print_constant(ast.Constant(value="null", inline_sentinel=True)), "'null'")++ def test_inline_sentinel_rejects_non_allowlisted_literal(self):+ # The flag is internal-only; setting it on anything outside the sentinel allowlist is a bug, so the printer+ # refuses to inline it rather than emit unparameterized text.+ with self.assertRaises(ImpossibleASTError):+ self._print_constant(ast.Constant(value="evil'; DROP", inline_sentinel=True))+def test_field_nullable_like(self):context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=Database())context.database.get_table("events").fields["nullable_field"] = StringDatabaseField( # type: ignore@@ -2983,8 +3086,8 @@ class TestPrinter(BaseTest):)self.assertEqual(printed,- f"SELECT `$browser` AS `$browser` FROM (SELECT nullIf(nullIf(events.`mat_$browser`, ''), 'null'), "- f"nullIf(nullIf(events.`mat_$browser`, ''), 'null') AS `$browser` " # only the second one gets the alias+ f"SELECT `$browser` AS `$browser` FROM (SELECT nullIf(nullIf(events.`mat_$browser`, ''), 'null') AS `$browser`, "+ f"nullIf(nullIf(events.`mat_$browser`, ''), 'null') AS `$browser` "f"FROM events WHERE equals(events.team_id, {self.team.pk})) LIMIT {MAX_SELECT_RETURNED_ROWS} "f"SETTINGS readonly=2, max_execution_time=10, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0",)@@ -4269,12 +4372,12 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):# equals: use AND IS NOT NULL to preserve skip index usageself._test_materialized_column_comparison("properties.test_prop = 'some_value'",- f"(equals(events.{mat_col.name}, %(hogql_val_0)s) AND (events.{mat_col.name} IS NOT NULL))",+ f"and(equals(events.{mat_col.name}, %(hogql_val_0)s), isNotNull(events.{mat_col.name}))",{"hogql_val_0": "some_value"},)self._test_materialized_column_comparison("'some_value' = properties.test_prop",- f"(equals(events.{mat_col.name}, %(hogql_val_0)s) AND (events.{mat_col.name} IS NOT NULL))",+ f"and(equals(events.{mat_col.name}, %(hogql_val_0)s), isNotNull(events.{mat_col.name}))",{"hogql_val_0": "some_value"},)# notEquals: use ifNull since skip index is less important here@@ -4331,9 +4434,9 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):with materialized("events", "test_prop", is_nullable=False) as mat_col:self._test_materialized_column_comparison(f"properties.test_prop {op} 'some_value'",- f"({ch_fn}(events.{mat_col.name}, %(hogql_val_0)s) "- f"AND notEquals(events.{mat_col.name}, '') "- f"AND notEquals(events.{mat_col.name}, 'null'))",+ f"and({ch_fn}(events.{mat_col.name}, %(hogql_val_0)s), "+ f"notEquals(events.{mat_col.name}, ''), "+ f"notEquals(events.{mat_col.name}, 'null'))",{"hogql_val_0": "some_value"},)@@ -4350,7 +4453,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):with materialized("events", "test_prop", is_nullable=True) as mat_col:self._test_materialized_column_comparison(f"properties.test_prop {op} 'some_value'",- f"({ch_fn}(events.{mat_col.name}, %(hogql_val_0)s) AND (events.{mat_col.name} IS NOT NULL))",+ f"and({ch_fn}(events.{mat_col.name}, %(hogql_val_0)s), isNotNull(events.{mat_col.name}))",{"hogql_val_0": "some_value"},)@@ -4402,9 +4505,9 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):assert f"less(events.{mat_col.name}," not in printed@patch("posthog.hogql.property_planner.get_materialized_column_for_property")- @patch("posthog.hogql.printer.base.get_materialized_column_for_property")+ @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")def test_materialized_column_range_comparison_uses_typed_numeric_source(- self, mock_base_get_mat_col, mock_planner_get_mat_col+ self, mock_resolution_get_mat_col, mock_planner_get_mat_col) -> None:from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails@@ -4424,7 +4527,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):column_type="Nullable(Float64)",has_minmax_index=True,)- mock_base_get_mat_col.return_value = mock_mat_col+ mock_resolution_get_mat_col.return_value = mock_mat_colmock_planner_get_mat_col.return_value = mock_mat_colprinted = self._expr("properties.numeric_test_prop < 5")@@ -4434,9 +4537,9 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):assert "accurateCastOrNull" not in printed@patch("posthog.hogql.property_planner.get_materialized_column_for_property")- @patch("posthog.hogql.printer.base.get_materialized_column_for_property")+ @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")def test_materialized_column_range_comparison_uses_typed_datetime_source(- self, mock_base_get_mat_col, mock_planner_get_mat_col+ self, mock_resolution_get_mat_col, mock_planner_get_mat_col) -> None:from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails@@ -4456,7 +4559,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):column_type="Nullable(DateTime64(6, 'UTC'))",has_minmax_index=True,)- mock_base_get_mat_col.return_value = mock_mat_col+ mock_resolution_get_mat_col.return_value = mock_mat_colmock_planner_get_mat_col.return_value = mock_mat_colprinted = self._expr("properties.datetime_test_prop < '2024-01-15'")@@ -4467,9 +4570,9 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):assert "parseDateTime64BestEffortOrNull" not in printed@patch("posthog.hogql.property_planner.get_materialized_column_for_property")- @patch("posthog.hogql.printer.base.get_materialized_column_for_property")+ @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")def test_materialized_column_range_comparison_skips_non_nullable_numeric_source(- self, mock_base_get_mat_col, mock_planner_get_mat_col+ self, mock_resolution_get_mat_col, mock_planner_get_mat_col) -> None:from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails@@ -4489,7 +4592,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):column_type="Float64",has_minmax_index=True,)- mock_base_get_mat_col.return_value = mock_mat_col+ mock_resolution_get_mat_col.return_value = mock_mat_colmock_planner_get_mat_col.return_value = mock_mat_colprinted = self._expr("properties.numeric_test_prop < 5")@@ -4828,13 +4931,13 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):with materialized("events", "test_prop", is_nullable=False) as mat_col:self._test_materialized_column_comparison("properties.test_prop ilike '%null%'",- f"ifNull(ilike(nullIf(nullIf(events.{mat_col.name}, ''), 'null'), %(hogql_val_1)s), 0)",- {"hogql_val_1": "%null%"},+ f"ifNull(ilike(nullIf(nullIf(events.{mat_col.name}, ''), 'null'), %(hogql_val_0)s), 0)",+ {"hogql_val_0": "%null%"},)self._test_materialized_column_comparison("properties.test_prop ilike '%NULL%'",- f"ifNull(ilike(nullIf(nullIf(events.{mat_col.name}, ''), 'null'), %(hogql_val_1)s), 0)",- {"hogql_val_1": "%NULL%"},+ f"ifNull(ilike(nullIf(nullIf(events.{mat_col.name}, ''), 'null'), %(hogql_val_0)s), 0)",+ {"hogql_val_0": "%NULL%"},)def test_materialized_column_like_uses_raw_column_for_non_nullable(self) -> None:@@ -4908,7 +5011,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):with materialized("events", "test_prop", is_nullable=True) as mat_col:self._test_materialized_column_comparison("properties.test_prop in ('value1', 'value2')",- f"and(has([%(hogql_val_0)s, %(hogql_val_1)s], events.{mat_col.name}), events.mat_test_prop IS NOT NULL)",+ f"and(has([%(hogql_val_0)s, %(hogql_val_1)s], events.{mat_col.name}), isNotNull(events.{mat_col.name}))",{"hogql_val_0": "value1", "hogql_val_1": "value2"},)diff --git a/posthog/hogql/printer/test/test_property_access_control.py b/posthog/hogql/printer/test/test_property_access_control.pyindex 90df3bdade74..e397150b129a 100644--- a/posthog/hogql/printer/test/test_property_access_control.py+++ b/posthog/hogql/printer/test/test_property_access_control.py@@ -1,4 +1,4 @@-from posthog.test.base import BaseTest+from posthog.test.base import BaseTest, ClickhouseTestMixin, cleanup_materialized_columns, materializedfrom parameterized import parameterized@@ -79,19 +79,20 @@ class TestRestrictPropertiesInHogQL(BaseTest):assert "secret_field" in sqldef test_denied_event_property_is_stripped_silently(self):- # Restricted properties are removed from the JSON blob via JSONDropKeys rather than- # raising an error, so explicit access (``properties.secret_field``) compiles to a- # JSON extract over the stripped blob and resolves to an empty string at runtime.+ # A restricted property reads as NULL rather than raising. Explicit access (``properties.secret_field``)+ # compiles to a constant NULL — the value is never extracted from the blob, and the key never appears, inline+ # or as a parameter.PropertyAccessControl.objects.create(team=self.team,property_definition=self.event_prop,access_level=PropertyAccessLevel.NONE.value,)sql, values = self._compile_select_with_values("SELECT properties.secret_field FROM events")- assert "JSONDropKeys" in sql- # the restricted key only appears as a parameter placeholder — never as an inline literal+ assert "NULL AS secret_field" in sql+ assert "JSONExtract" not in sql # the restricted value is never read from the blob+ assert "JSONDropKeys" not in sql # no redundant drop-then-extractassert "'secret_field'" not in sql- self._assert_value_present(values, "secret_field")+ assert not any("secret_field" in str(v) for v in values.values())def test_allowed_property_not_affected(self):PropertyAccessControl.objects.create(@@ -136,8 +137,9 @@ class TestRestrictPropertiesInHogQL(BaseTest):assert "secret_field" in sqldef test_denied_person_property_is_stripped_silently(self):- # Restricted person properties are removed from ``person.properties`` rather than- # raising — so the same query produces consistent (empty) output across PoE modes.+ # A restricted person property reads as NULL rather than raising. Through the PoE join it resolves to+ # ``argMax(tuple(NULL), ...)`` inside the subquery, so the value is never extracted and the same query produces+ # consistent (NULL) output across PoE modes.person_prop = PropertyDefinition.objects.create(team=self.team,name="secret_person_field",@@ -150,9 +152,10 @@ class TestRestrictPropertiesInHogQL(BaseTest):access_level=PropertyAccessLevel.NONE.value,)sql, values = self._compile_select_with_values("SELECT person.properties.secret_person_field FROM events")- assert "JSONDropKeys" in sql+ assert "JSONExtract" not in sql # the restricted value is never read from the blob+ assert "JSONDropKeys" not in sqlassert "'secret_person_field'" not in sql- self._assert_value_present(values, "secret_person_field")+ assert not any("secret_person_field" in str(v) for v in values.values())def test_no_user_context_uses_default_rules(self):PropertyAccessControl.objects.create(@@ -168,10 +171,11 @@ class TestRestrictPropertiesInHogQL(BaseTest):)node = parse_select("SELECT properties.secret_field FROM events")sql, _ = prepare_and_print_ast(node, context=context, dialect="clickhouse")- # default rules still apply without a user — the restricted key is stripped- assert "JSONDropKeys" in sql+ # default rules still apply without a user — the restricted property reads as NULL+ assert "NULL AS secret_field" in sql+ assert "JSONExtract" not in sqlassert "'secret_field'" not in sql- assert "secret_field" in context.values.values()+ assert not any("secret_field" in str(v) for v in context.values.values())def test_non_property_fields_not_affected(self):PropertyAccessControl.objects.create(@@ -189,12 +193,14 @@ class TestRestrictPropertiesInHogQL(BaseTest):property_definition=self.event_prop,access_level=PropertyAccessLevel.NONE.value,)- # the WHERE clause compiles, but the restricted property is stripped from the JSON,- # so the comparison effectively runs against an empty string+ # the WHERE clause compiles, but the restricted property reads as NULL, so the comparison is against NULL (never+ # against the column or the blob) and matches no rowssql, values = self._compile_select_with_values("SELECT event FROM events WHERE properties.secret_field = 'foo'")- assert "JSONDropKeys" in sql+ assert "equals(NULL," in sql+ assert "JSONExtract" not in sql+ assert "JSONDropKeys" not in sqlassert "'secret_field'" not in sql- self._assert_value_present(values, "secret_field")+ assert not any("secret_field" in str(v) for v in values.values())def test_select_star_works_with_restrictions(self):PropertyAccessControl.objects.create(@@ -230,22 +236,19 @@ class TestRestrictPropertiesInHogQL(BaseTest):assert "secret_field" in sqldef test_silent_strip_does_not_leak_access_control_information(self):- # The compiled SQL must not embed the restricted property name as a literal,- # error message, or comment — anything an attacker could read off the wire to- # tell "this property exists but I can't see it" apart from "this property- # doesn't exist". Restricted keys are passed through ``add_sensitive_value`` so- # they appear only in the parameter dict, not the SQL string.+ # The compiled SQL must not reveal that a property was hidden — an attacker must not be able to tell "this+ # property exists but I can't see it" apart from "this property doesn't exist". The restricted read is a constant+ # NULL, so the key name appears nowhere: not as an inline literal, not as a parameter.PropertyAccessControl.objects.create(team=self.team,property_definition=self.event_prop,access_level=PropertyAccessLevel.NONE.value,)sql, values = self._compile_select_with_values("SELECT properties.secret_field FROM events")- # restricted key never appears as an inline literal in SQL — only as a parameterassert "'secret_field'" not in sqlfor forbidden_word in ["restricted", "denied", "permission", "not allowed"]:assert forbidden_word not in sql.lower(), f"SQL leaks access control info: '{sql}'"- self._assert_value_present(values, "secret_field")+ assert not any("secret_field" in str(v) for v in values.values())@parameterized.expand([@@ -378,17 +381,19 @@ class TestRestrictPropertiesInHogQL(BaseTest):self._assert_value_present(values, "secret_field")def test_column_aliased_explicit_property_access_is_stripped(self):- # regression: explicit access ``e.c.secret_field`` (where ``c`` aliases ``properties``)- # must be stripped via JSONDropKeys, matching the unaliased case.+ # regression: explicit access ``e.c.secret_field`` (where ``c`` aliases ``properties``) reads as NULL, matching+ # the unaliased case.PropertyAccessControl.objects.create(team=self.team,property_definition=self.event_prop,access_level=PropertyAccessLevel.NONE.value,)sql, values = self._compile_select_with_values("SELECT e.c.secret_field FROM events AS e (a, b, c)")- assert "JSONDropKeys" in sql+ assert "NULL AS secret_field" in sql+ assert "JSONExtract" not in sql+ assert "JSONDropKeys" not in sqlassert "'secret_field'" not in sql- self._assert_value_present(values, "secret_field")+ assert not any("secret_field" in str(v) for v in values.values())@parameterized.expand([@@ -401,10 +406,9 @@ class TestRestrictPropertiesInHogQL(BaseTest):def test_person_property_access_is_consistent_across_poe_modes(self, _case_name: str, persons_on_events_mode: PersonsOnEventsMode):- # regression: previously, ``person.properties.email`` raised a ResolutionError in joined- # mode but silently returned an empty value in PoE mode. The intended behaviour is to- # strip restricted keys from the JSON blob (returning empty) in *all* modes, so the same- # query produces the same compiled output regardless of how person properties are sourced.+ # regression: previously, ``person.properties.email`` raised a ResolutionError in joined mode but silently+ # returned an empty value in PoE mode. The intended behaviour is consistent across modes — a restricted property+ # reads as NULL regardless of how person properties are sourced.person_prop = PropertyDefinition.objects.create(team=self.team,name="email",@@ -425,7 +429,54 @@ class TestRestrictPropertiesInHogQL(BaseTest):)node = parse_select("SELECT uuid, event, person.properties.email FROM events")sql, _ = prepare_and_print_ast(node, context=context, dialect="clickhouse")- assert "JSONDropKeys" in sql- # the restricted key never leaks as an inline literal in any PoE mode+ # the restricted value is never extracted, in any PoE mode, and the key never leaks+ assert "JSONExtract" not in sql+ assert "JSONDropKeys" not in sqlassert "'email'" not in sql- assert "email" in context.values.values()+ assert not any("email" in str(v) for v in context.values.values())+++class TestRestrictedPropertyWithMaterializedColumn(ClickhouseTestMixin, BaseTest):+ """A restricted property that also has a materialized column must not be readable through that column.++ The materialized column holds the raw value and bypasses the JSONDropKeys blob scrub, so reading or comparing it+ directly is an information-disclosure leak. Every path (value read, comparison, key-existence) must decline the+ materialized column for a restricted property and fall back to the scrubbed JSON blob.+ """++ def setUp(self):+ super().setUp()+ self.organization.available_product_features = [+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}+ ]+ self.organization.save()+ self.event_prop = PropertyDefinition.objects.create(+ team=self.team,+ name="secret_field",+ property_type="String",+ type=PropertyDefinition.Type.EVENT,+ )+ PropertyAccessControl.objects.create(+ team=self.team,+ property_definition=self.event_prop,+ access_level=PropertyAccessLevel.NONE.value,+ )++ def _compile_select(self, query: str) -> str:+ context = HogQLContext(team_id=self.team.pk, team=self.team, user=self.user, enable_select_queries=True)+ sql, _ = prepare_and_print_ast(parse_select(query), context=context, dialect="clickhouse")+ return sql++ def test_restricted_materialized_property_in_where_is_not_read_from_column(self):+ self.addCleanup(cleanup_materialized_columns)+ with materialized("events", "secret_field", is_nullable=False):+ sql = self._compile_select("SELECT event FROM events WHERE properties.secret_field = 'foo'")+ # The comparison must NOT read the bare materialized column — that bypasses the JSONDropKeys scrub and lets a+ # user without access probe the value. It must go through the scrubbed blob (or a constant) instead.+ assert "mat_secret_field" not in sql, f"restricted property leaked via materialized column: {sql}"++ def test_restricted_materialized_property_read_is_not_read_from_column(self):+ self.addCleanup(cleanup_materialized_columns)+ with materialized("events", "secret_field", is_nullable=False):+ sql = self._compile_select("SELECT properties.secret_field FROM events")+ assert "mat_secret_field" not in sql, f"restricted property leaked via materialized column: {sql}"diff --git a/posthog/hogql/printer/test/test_within_non_hogql_delete.py b/posthog/hogql/printer/test/test_within_non_hogql_delete.pynew file mode 100644index 000000000000..917dcdd0a571--- /dev/null+++ b/posthog/hogql/printer/test/test_within_non_hogql_delete.py@@ -0,0 +1,218 @@+"""Tests the ``within_non_hogql_query`` lightweight-DELETE-mutation path.++Data deletion compiles a HogQL property predicate into a ClickHouse fragment via ``compile_hogql_predicate`` (which sets+``within_non_hogql_query=True``), and the deletion DAG splices that fragment into a lightweight+``DELETE FROM sharded_events WHERE …`` mutation. The catch: a ClickHouse lightweight-delete expression analyzer rejects+table-qualified column references, so when the predicate hits a materialized column the fragment must read it+**unqualified** — ``mat_$browser``, never ``sharded_events.mat_$browser`` — even though the column exists on every+replica. The DAG tests (``posthog/dags/tests/test_data_deletion_requests.py``) cover the delete flow only over an+unmaterialized property, so the materialized-column case is tested here.++This file checks two things:++1. ``compile_hogql_predicate`` over ``properties.$browser = 'Chrome'`` with ``$browser`` materialized produces an+ unqualified fragment (no ``events.`` / ``sharded_events.`` prefix on the mat column) using only mutation-safe scalar+ functions.+2. A real lightweight DELETE built from that fragment (mirroring the production ``LightweightDeleteMutationRunner``+ statement and settings) removes the matching rows and leaves the non-matching and other-team rows in place.+"""++import re+from typing import cast++from posthog.test.base import (+ APIBaseTest,+ ClickhouseTestMixin,+ _create_event,+ cleanup_materialized_columns,+ flush_persons_and_events,+ materialized,+)++from parameterized import parameterized++from posthog.hogql.context import HogQLContext+from posthog.hogql.hogql import translate_hogql++from posthog.clickhouse.client.execute import sync_execute+from posthog.models import Organization, Team+from posthog.models.data_deletion_request import compile_hogql_predicate+from posthog.models.event.sql import EVENTS_DATA_TABLE+from posthog.models.property import TableColumn+from posthog.settings.data_stores import CLICKHOUSE_DATABASE+++class _PredicateObj:+ """Minimal stand-in for the deletion-request shape ``compile_hogql_predicate`` reads (``team_id`` + predicate)."""++ def __init__(self, team_id: int, hogql_predicate: str) -> None:+ self.team_id = team_id+ self.hogql_predicate = hogql_predicate+++# Functions a ClickHouse lightweight-delete mutation expression analyzer accepts: plain scalar functions. The compiled+# fragment for a property predicate must use only these (no aggregates, no table-qualified columns, no window/array+# higher-order forms). This is the allow-list the form constraint cares about.+_MUTATION_SAFE_FUNCTIONS = frozenset(+ {+ "equals",+ "notequals",+ "and",+ "or",+ "not",+ "ifnull",+ "isnull",+ "isnotnull",+ "nullif",+ "in",+ "notin",+ "has",+ "jsonextractraw",+ "jsonextractstring",+ "jsonhas",+ "replaceregexpall",+ "tostring",+ "like",+ "ilike",+ "lower",+ "greater",+ "less",+ "greaterorequals",+ "lessorequals",+ }+)+++class TestWithinNonHogqlDelete(ClickhouseTestMixin, APIBaseTest):+ maxDiff = None++ def _materialized_column_name(self, table: str, prop: str, table_column: str = "properties") -> str:+ from ee.clickhouse.materialized_columns.columns import get_materialized_columns # noqa: PLC0415++ column = get_materialized_columns(table).get((prop, cast(TableColumn, table_column)))+ assert column is not None, f"expected materialized column for {table}.{prop} ({table_column})"+ return column.name++ def _assert_unqualified_and_mutation_safe(self, sql: str, mat_column_name: str) -> None:+ sql_lower = sql.lower()++ # Unqualified — the lightweight-delete mutation analyzer rejects table-qualified column references.+ assert f"events.{mat_column_name.lower()}" not in sql_lower, f"mat column must be unqualified, got: {sql}"+ assert "events." not in sql_lower, f"fragment must carry no table prefix at all, got: {sql}"+ assert "sharded_events." not in sql_lower, f"fragment must carry no table prefix at all, got: {sql}"+ # The bare (unqualified) materialized column must be present — confirms it was actually used.+ assert mat_column_name.lower() in sql_lower, f"expected the materialized column {mat_column_name} in: {sql}"++ # Mutation-safe: every function name used is on the scalar allow-list (no aggregates / unsafe forms).+ called = {name.lower() for name in re.findall(r"([A-Za-z_][A-Za-z0-9_]*)\s*\(", sql)}+ unexpected = called - _MUTATION_SAFE_FUNCTIONS+ assert not unexpected, f"fragment uses non-mutation-safe functions {unexpected} in: {sql}"++ def test_compiled_predicate_is_unqualified_and_mutation_safe_with_materialized_column(self) -> None:+ self.addCleanup(cleanup_materialized_columns)+ with materialized("events", "$browser", is_nullable=False):+ mat_name = self._materialized_column_name("events", "$browser")+ sql, params = compile_hogql_predicate(_PredicateObj(self.team.pk, "properties.$browser = 'Chrome'"))++ self._assert_unqualified_and_mutation_safe(sql, mat_name)+ # The compared value is parameterized (not inlined), and resolves to the literal we passed.+ assert params == {"hogql_val_0": "Chrome"}, params++ def test_within_non_hogql_predicate_stays_unqualified_with_materialized_column(self) -> None:+ # within_non_hogql_query queries run through lowering + the physical pass like any other: the synthetic+ # materialized-column field is marked `unqualified`, so the printer drops the table prefix and the+ # lightweight-delete mutation analyzer accepts the bare column.+ self.addCleanup(cleanup_materialized_columns)+ with materialized("events", "$browser", is_nullable=False):+ mat_name = self._materialized_column_name("events", "$browser")+ context = HogQLContext(+ team_id=self.team.pk,+ within_non_hogql_query=True,+ enable_select_queries=True,+ )+ sql = translate_hogql("properties.$browser = 'Chrome'", context, dialect="clickhouse")+ self._assert_unqualified_and_mutation_safe(sql, mat_name)++ def test_compiled_predicate_is_unqualified_and_mutation_safe_without_materialized_column(self) -> None:+ # Without materialization the fragment is the JSON-blob form; it must STILL be unqualified and mutation-safe+ # (the deletion path always runs with within_non_hogql_query=True). This is the other production shape.+ sql, _params = compile_hogql_predicate(_PredicateObj(self.team.pk, "properties.$browser = 'Chrome'"))++ sql_lower = sql.lower()+ assert "events." not in sql_lower, f"blob fragment must be unqualified, got: {sql}"+ assert "sharded_events." not in sql_lower, f"blob fragment must be unqualified, got: {sql}"+ assert "jsonextractraw" in sql_lower, f"expected the JSON-blob extract form, got: {sql}"+ called = {name.lower() for name in re.findall(r"([A-Za-z_][A-Za-z0-9_]*)\s*\(", sql)}+ unexpected = called - _MUTATION_SAFE_FUNCTIONS+ assert not unexpected, f"blob fragment uses non-mutation-safe functions {unexpected} in: {sql}"++ def _count_browser_rows(self, team_id: int, browser: str) -> int:+ # Read through the Distributed ``events`` proxy; in the single-shard test cluster it reflects ``sharded_events``.+ result = sync_execute(+ "SELECT count() FROM events WHERE team_id = %(team_id)s AND JSONExtractString(properties, '$browser') = %(b)s",+ {"team_id": team_id, "b": browser},+ )+ return result[0][0]++ def _run_lightweight_delete(self, team_id: int, predicate_fragment: str, params: dict) -> None:+ # Mirror production ``LightweightDeleteMutationRunner.get_statement``: a lightweight ``DELETE FROM`` against the+ # local sharded table, scoped by team_id (the compiled fragment carries no team guard of its own) AND the+ # compiled predicate. Synchronous settings so the mutation completes before we assert.+ table = EVENTS_DATA_TABLE() # "sharded_events"+ delete_sql = (+ f"DELETE FROM {CLICKHOUSE_DATABASE}.{table} " # nosemgrep: clickhouse-fstring-param-audit+ f"WHERE team_id = %(_del_team_id)s AND ({predicate_fragment})"+ )+ sync_execute(+ delete_sql,+ {**params, "_del_team_id": team_id},+ settings={"lightweight_deletes_sync": 2, "mutations_sync": 2},+ )++ @parameterized.expand([("materialized", True), ("unmaterialized", False)])+ def test_lightweight_delete_mutation_removes_matching_rows(self, _name: str, is_materialized: bool) -> None:+ self.addCleanup(cleanup_materialized_columns)++ # A second team to prove the team_id guard keeps the delete scoped (cross-team safety).+ other_org = Organization.objects.create(name="del-other-org")+ other_team = Team.objects.create(organization=other_org, name="del-other-team")++ def seed() -> None:+ for i in range(5):+ _create_event(+ team=self.team, distinct_id=f"chrome_{i}", event="$pageview", properties={"$browser": "Chrome"}+ )+ for i in range(3):+ _create_event(+ team=self.team, distinct_id=f"firefox_{i}", event="$pageview", properties={"$browser": "Firefox"}+ )+ # Same matching property on a different team — must NOT be deleted.+ _create_event(+ team=other_team, distinct_id="other_chrome", event="$pageview", properties={"$browser": "Chrome"}+ )+ flush_persons_and_events()++ if is_materialized:+ with materialized("events", "$browser", is_nullable=False):+ seed()+ sql, params = compile_hogql_predicate(_PredicateObj(self.team.pk, "properties.$browser = 'Chrome'"))+ # The materialized fragment must be unqualified or the mutation analyzer rejects it.+ self._assert_unqualified_and_mutation_safe(sql, self._materialized_column_name("events", "$browser"))+ self._run_and_assert_delete(sql, params, other_team)+ else:+ seed()+ sql, params = compile_hogql_predicate(_PredicateObj(self.team.pk, "properties.$browser = 'Chrome'"))+ self._run_and_assert_delete(sql, params, other_team)++ def _run_and_assert_delete(self, predicate_fragment: str, params: dict, other_team: Team) -> None:+ # Pre-conditions.+ self.assertEqual(self._count_browser_rows(self.team.pk, "Chrome"), 5)+ self.assertEqual(self._count_browser_rows(self.team.pk, "Firefox"), 3)+ self.assertEqual(self._count_browser_rows(other_team.pk, "Chrome"), 1)++ self._run_lightweight_delete(self.team.pk, predicate_fragment, params)++ # Chrome rows for this team are gone; Firefox rows and the other team's Chrome row survive.+ self.assertEqual(self._count_browser_rows(self.team.pk, "Chrome"), 0)+ self.assertEqual(self._count_browser_rows(self.team.pk, "Firefox"), 3)+ self.assertEqual(self._count_browser_rows(other_team.pk, "Chrome"), 1)diff --git a/posthog/hogql/printer/types.py b/posthog/hogql/printer/types.pyindex f1faebeef11a..55ed2a16be62 100644--- a/posthog/hogql/printer/types.py+++ b/posthog/hogql/printer/types.py@@ -7,46 +7,3 @@ from posthog.hogql import astclass JoinExprResponse:printed_sql: strwhere: ast.Expr | None = None---@dataclass-class PrintableMaterializedColumn:- table: str | None- column: str- is_nullable: bool- type: str | None- has_minmax_index: bool- has_bloom_filter_index: bool- has_ngram_lower_index: bool- has_bloom_filter_lower_index: bool-- def __str__(self) -> str:- if self.table is None:- # XXX: For legacy person properties handling (see comment at instantiation site.)- return self.column- else:- return f"{self.table}.{self.column}"---@dataclass-class PrintableMaterializedPropertyGroupItem:- table: str- column: str- property_name: str-- def __str__(self) -> str:- # If the key we're looking for doesn't exist in the map for this property group, an empty string (the default- # value for the `String` type) is returned. Since that is a valid property value, we need to check it here.- return f"{self.has_expr} ? {self.value_expr} : null"-- @property- def __qualified_column(self) -> str:- return f"{self.table}.{self.column}"-- @property- def has_expr(self) -> str:- return f"has({self.__qualified_column}, {self.property_name})"-- @property- def value_expr(self) -> str:- return f"{self.__qualified_column}[{self.property_name}]"diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex ac10b0ddc66f..c98ea10d5792 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -21,9 +21,11 @@ from posthog.hogql.printer.duckdb import DuckDBPrinterfrom posthog.hogql.printer.hogql import HogQLPrinterfrom posthog.hogql.printer.postgres import PostgresPrinterfrom posthog.hogql.resolver import ResolverFactory, resolve_types+from posthog.hogql.transforms.clickhouse_property_resolution import clickhouse_property_resolutionfrom posthog.hogql.transforms.events_predicate_pushdown import apply_events_predicate_pushdown, events_pushdown_enabledfrom posthog.hogql.transforms.in_cohort import resolve_in_cohorts, resolve_in_cohorts_conjoinedfrom posthog.hogql.transforms.lazy_tables import resolve_lazy_tables+from posthog.hogql.transforms.logical_property_lowering import lower_property_accessfrom posthog.hogql.transforms.projection_pushdown import pushdown_projectionsfrom posthog.hogql.transforms.property_types import PropertySwapper, build_property_swapperfrom posthog.hogql.transforms.type_aware_simplification import simplify_redundant_type_operations@@ -75,17 +77,15 @@ def prepare_and_print_ast(collect_hogql_type_coverage(prepared_ast, context.type_observability)collect_hogql_sql_shape(prepared_ast, context.type_observability)- return (- print_prepared_ast(- node=prepared_ast,- context=context,- dialect=dialect,- stack=stack,- settings=settings,- pretty=pretty,- ),- prepared_ast,+ printed = print_prepared_ast(+ node=prepared_ast,+ context=context,+ dialect=dialect,+ stack=stack,+ settings=settings,+ pretty=pretty,)+ return printed, prepared_astexcept Exception:if context.type_observability is not None:context.type_observability.result = "error"@@ -119,8 +119,10 @@ def prepare_ast_for_printing(context.modifiers = set_default_in_cohort_via(context.modifiers)- # Load property-level access control restrictions before type resolution so that- # FieldType.get_child() can block access to restricted properties during resolution.+ # Load property-level access control restrictions onto the context. They are enforced only on the ClickHouse path —+ # the printer wraps the JSON blob in JSONDropKeys, and property resolution declines backing columns (and reads a+ # restricted property as NULL). The warehouse (Postgres / DuckDB) dialects only compile external data-warehouse+ # sources, which carry no restrictable event/person properties, so they need no enforcement here.if context.team_id is not None and context.restricted_properties is None:with context.timings.measure("load_restricted_properties"):context.restricted_properties = get_restricted_properties_for_team(@@ -159,6 +161,11 @@ def prepare_ast_for_printing(with context.timings.measure("resolve_lazy_tables"):resolve_lazy_tables(node, dialect, stack, context, resolver_factory=resolver_factory)+ # Lower JSON-blob property reads to dialect-neutral PropertyAccess nodes. The warehouse dialects have no+ # materialized columns, so logical lowering is the whole story for them (no ClickHouse property resolution).+ with context.timings.measure("lower_property_access"):+ node = lower_property_access(node, context)+if dialect == "clickhouse":with context.timings.measure("resolve_property_types"):build_property_swapper(node, context)@@ -182,10 +189,6 @@ def prepare_ast_for_printing(with context.timings.measure("resolve_lazy_tables"):resolve_lazy_tables(node, dialect, stack, context, resolver_factory=resolver_factory)- if events_pushdown_enabled(context.modifiers):- with context.timings.measure("events_predicate_pushdown"):- node = apply_events_predicate_pushdown(node, context)-with context.timings.measure("swap_properties"):node = PropertySwapper(timezone=context.property_swapper.timezone,@@ -196,6 +199,28 @@ def prepare_ast_for_printing(setTimeZones=context.modifiers.convertToProjectTimezone is not False,).visit(node)+ # The two passes that replaced the printer's old property handling, in order. Both run AFTER the PropertySwapper+ # passes, so any scalar cast already wraps the property. (1) Lowering replaces every blob `PropertyType` Field with+ # a `PropertyAccess` — a plain "read these keys from this blob", no decision about how. (2) Property resolution+ # then picks the source: each `PropertyAccess` backed by a materialized / skip-index / property-group column is+ # rewritten to read that column; the rest survive and print as the raw JSON extract. The within_non_hogql_query+ # (lightweight-DELETE) path runs through here too; the printer renders every column bare there (the single-table+ # mutation analyzer rejects table prefixes), so no extra marking is needed.+ with context.timings.measure("lower_property_access"):+ node = lower_property_access(node, context)++ # Events predicate pushdown runs on the lowered AST (between lowering and property resolution), so it matches the+ # dialect-neutral PropertyAccess form. Its pre-filtering subquery projects only source columns (raw blobs and+ # bare events columns); outer blob references are re-typed onto the subquery, so the resolution pass substitutes+ # physical columns only inside the subquery body — where the real events table is in scope — and outer+ # references print as JSON extracts over the projected blob.+ if events_pushdown_enabled(context.modifiers):+ with context.timings.measure("events_predicate_pushdown"):+ node = apply_events_predicate_pushdown(node, context)++ with context.timings.measure("clickhouse_property_resolution"):+ node = clickhouse_property_resolution(node, context)+# We support global query settings, and local subquery settings.# If the global query is a select query with settings, merge the two.if isinstance(node, ast.SelectQuery) and node.settings is not None and settings is not None:diff --git a/posthog/hogql/property_planner.py b/posthog/hogql/property_planner.pyindex bae4bca3dd1b..38133664b3f9 100644--- a/posthog/hogql/property_planner.py+++ b/posthog/hogql/property_planner.py@@ -16,6 +16,7 @@ from posthog.hogql.errors import (QueryError,ResolutionError,)+from posthog.hogql.restricted_properties import restricted_property_keys_for_table_typefrom posthog.hogql.type_system import (ComparisonCompatibility,comparison_compatibility,@@ -33,7 +34,7 @@ from posthog.clickhouse.materialized_columns import (from posthog.clickhouse.property_groups import property_groupsfrom posthog.models.property import PropertyName, TableColumn-from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType+from products.event_definitions.backend.models.property_definition import PropertyTypeclass PropertyScope(StrEnum):@@ -163,24 +164,8 @@ def is_property_type_restricted(property_type: ast.PropertyType, context: HogQLCdef get_restricted_keys_for_table_type(table_type: ast.Type, context: HogQLContext) -> set[str]:- if not isinstance(table_type, ast.BaseTableType):- return set()-- try:- table = table_type.resolve_database_table(context)- except Exception:- return set()-- if isinstance(table, EventsPersonSubTable):- prop_def_type = PropertyDefinition.Type.PERSON- elif isinstance(table, EventsTable):- prop_def_type = PropertyDefinition.Type.EVENT- elif isinstance(table, (PersonsTable, RawPersonsTable)):- prop_def_type = PropertyDefinition.Type.PERSON- else:- return set()-- return {name for name, property_type in context.restricted_properties or set() if property_type == prop_def_type}+ # Delegates to the single source of truth for property-level access control; see its docstring.+ return restricted_property_keys_for_table_type(table_type, context)def _build_property_comparison_plan(diff --git a/posthog/hogql/restricted_properties.py b/posthog/hogql/restricted_properties.pynew file mode 100644index 000000000000..cf54e7500da9--- /dev/null+++ b/posthog/hogql/restricted_properties.py@@ -0,0 +1,46 @@+import structlog++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.schema.events import EventsPersonSubTable, EventsTable+from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable++logger = structlog.get_logger(__name__)+++def restricted_property_keys_for_table_type(table_type: ast.Type, context: HogQLContext) -> set[str]:+ """Top-level property names restricted by property-level access control for a table, or an empty set.++ Single source of truth shared by the ClickHouse printer (which JSONDropKeys-wraps the blob) and the property+ lowering / physical passes (which decline the materialized-column substitution for a restricted property, leaving+ the JSON-blob read the printer then scrubs to ''). Under-detecting here leaks the materialized value (PII); over-+ detecting only costs a mat-column optimization — so this is the security boundary and must never be reimplemented+ elsewhere.+ """+ if not context.restricted_properties:+ return set()+ if not isinstance(table_type, ast.BaseTableType):+ return set()++ # Deferred: PropertyDefinition pulls in the Django model layer; keep it off this module's import path.+ from products.event_definitions.backend.models.property_definition import PropertyDefinition # noqa: PLC0415++ try:+ table = table_type.resolve_database_table(context)+ except Exception:+ # Fail-open: a resolution error here disables restriction enforcement on every path that consults this+ # function. Unreachable today (resolve_database_table is plain attribute access for all matched table types),+ # but log loudly so a future table type that can raise doesn't silently un-restrict properties.+ logger.warning("restricted_property_table_resolution_failed", table_type=type(table_type).__name__)+ return set()++ if isinstance(table, EventsPersonSubTable):+ prop_def_type = PropertyDefinition.Type.PERSON+ elif isinstance(table, EventsTable):+ prop_def_type = PropertyDefinition.Type.EVENT+ elif isinstance(table, (PersonsTable, RawPersonsTable)):+ prop_def_type = PropertyDefinition.Type.PERSON+ else:+ return set()++ return {name for name, ptype in context.restricted_properties if ptype == prop_def_type}diff --git a/posthog/hogql/test/__snapshots__/test_property_skip_indexes.ambr b/posthog/hogql/test/__snapshots__/test_property_skip_indexes.ambrindex 58613d8f55ba..c535d00e8416 100644--- a/posthog/hogql/test/__snapshots__/test_property_skip_indexes.ambr+++ b/posthog/hogql/test/__snapshots__/test_property_skip_indexes.ambr@@ -3,8 +3,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (equals(events.dmat_string_0, '5')- AND (events.dmat_string_0 IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.dmat_string_0, '5'), isNotNull(events.dmat_string_0)))LIMIT 50000'''# ---@@ -116,9 +115,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '5')- AND notEquals(events.mat_test_prop, '')- AND notEquals(events.mat_test_prop, 'null')))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '5'), notEquals(events.mat_test_prop, ''), notEquals(events.mat_test_prop, 'null')))LIMIT 50000'''# ---@@ -134,9 +131,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '5')- AND notEquals(events.mat_test_prop, '')- AND notEquals(events.mat_test_prop, 'null')))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '5'), notEquals(events.mat_test_prop, ''), notEquals(events.mat_test_prop, 'null')))LIMIT 50000'''# ---@@ -144,9 +139,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (greater(events.mat_test_prop, '5')- AND notEquals(events.mat_test_prop, '')- AND notEquals(events.mat_test_prop, 'null')))+ WHERE and(equals(events.team_id, 99999), and(greater(events.mat_test_prop, '5'), notEquals(events.mat_test_prop, ''), notEquals(events.mat_test_prop, 'null')))LIMIT 50000'''# ---@@ -194,8 +187,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (equals(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -203,7 +195,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_test_prop), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -227,8 +219,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -236,8 +227,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (greater(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(greater(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -245,7 +235,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%5%'), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%5%'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -261,8 +251,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (equals(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -278,8 +267,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -287,8 +275,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (greater(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(greater(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -296,8 +283,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (lessOrEquals(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(lessOrEquals(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -305,8 +291,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (greaterOrEquals(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -314,7 +299,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_test_prop), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_test_prop), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -322,7 +307,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%5%'), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_test_prop, '%5%'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -338,8 +323,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, 5)- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, 5), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -347,8 +331,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, 5.5)- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, 5.5), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -356,8 +339,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, toDateTime64('2024-01-15 10:30:00.000000', 6, 'UTC'))- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, toDateTime64('2024-01-15 10:30:00.000000', 6, 'UTC')), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -365,8 +347,7 @@'''SELECT events.distinct_id AS distinct_idFROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '500')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '500'), isNotNull(events.mat_test_prop)))ORDER BY events.distinct_id ASCLIMIT 100 SETTINGS readonly=2,max_execution_time=60,@@ -386,8 +367,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, 'apple')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, 'apple'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -395,8 +375,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -404,8 +383,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '2024-01-15')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '2024-01-15'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -413,8 +391,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '2024-01-15T10:30:00Z')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '2024-01-15T10:30:00Z'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -422,7 +399,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%value_that_is_long_enough%')), events.mat_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_test_prop, '')), lower('%value_that_is_long_enough%')), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -438,8 +415,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (equals(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -447,8 +423,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_test_prop, '5')- AND (events.mat_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_test_prop, '5'), isNotNull(events.mat_test_prop)))LIMIT 50000'''# ---@@ -496,7 +471,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), ifNull(less(has(events.properties_group_custom, 'test_prop') ? events.properties_group_custom['test_prop'] : null, '5'), 0))+ WHERE and(equals(events.team_id, 99999), ifNull(less(if(has(events.properties_group_custom, 'test_prop'), events.properties_group_custom['test_prop'], NULL), '5'), 0))LIMIT 50000'''# ---@@ -504,7 +479,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), ifNull(ilike(toString(has(events.properties_group_custom, 'test_prop') ? events.properties_group_custom['test_prop'] : null), '%5%'), 0))+ WHERE and(equals(events.team_id, 99999), ifNull(ilike(toString(if(has(events.properties_group_custom, 'test_prop'), events.properties_group_custom['test_prop'], NULL)), '%5%'), 0))LIMIT 50000'''# ---@@ -512,8 +487,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_typed_datetime_prop, toDateTime64('2024-01-05 00:00:00', 6, 'UTC'))- AND (events.mat_typed_datetime_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(ifNull(less(events.mat_typed_datetime_prop, toDateTime64('2024-01-05 00:00:00', 6, 'UTC')), 0), isNotNull(events.mat_typed_datetime_prop)))LIMIT 50000'''# ---@@ -521,8 +495,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_typed_numeric_prop, 5)- AND (events.mat_typed_numeric_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_typed_numeric_prop, 5), isNotNull(events.mat_typed_numeric_prop)))LIMIT 50000'''# ---@@ -530,8 +503,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (equals(events.mat_pp_test_prop, '5')- AND (events.mat_pp_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.mat_pp_test_prop, '5'), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -539,7 +511,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_pp_test_prop), events.mat_pp_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_pp_test_prop), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -555,8 +527,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_pp_test_prop, '5')- AND (events.mat_pp_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_pp_test_prop, '5'), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -564,8 +535,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (equals(events.mat_pp_test_prop, '5')- AND (events.mat_pp_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.mat_pp_test_prop, '5'), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -573,8 +543,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (less(events.mat_pp_test_prop, '5')- AND (events.mat_pp_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(less(events.mat_pp_test_prop, '5'), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -582,8 +551,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (greater(events.mat_pp_test_prop, '5')- AND (events.mat_pp_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(greater(events.mat_pp_test_prop, '5'), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -591,7 +559,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_pp_test_prop), events.mat_pp_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(has(['2', '5'], events.mat_pp_test_prop), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -599,7 +567,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_pp_test_prop, '%5%'), events.mat_pp_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(ilike(events.mat_pp_test_prop, '%5%'), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -607,7 +575,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_pp_test_prop, '')), lower('%value_that_is_long_enough%')), events.mat_pp_test_prop IS NOT NULL))+ WHERE and(equals(events.team_id, 99999), and(like(lower(coalesce(events.mat_pp_test_prop, '')), lower('%value_that_is_long_enough%')), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -615,8 +583,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), (equals(events.mat_pp_test_prop, '5')- AND (events.mat_pp_test_prop IS NOT NULL)))+ WHERE and(equals(events.team_id, 99999), and(equals(events.mat_pp_test_prop, '5'), isNotNull(events.mat_pp_test_prop)))LIMIT 50000'''# ---@@ -648,7 +615,7 @@'''SELECT count() AS `count()`FROM events- WHERE and(equals(events.team_id, 99999), ifNull(less(has(events.person_properties_map_custom, 'test_prop') ? events.person_properties_map_custom['test_prop'] : null, '5'), 0))+ WHERE and(equals(events.team_id, 99999), ifNull(less(if(has(events.person_properties_map_custom, 'test_prop'), events.person_properties_map_custom['test_prop'], NULL), '5'), 0))LIMIT 50000'''# ---@@ -662,8 +629,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), (equals(where_optimization.pmat_test_prop, '5')- AND (where_optimization.pmat_test_prop IS NOT NULL))))))+ WHERE and(equals(where_optimization.team_id, 99999), and(equals(where_optimization.pmat_test_prop, '5'), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(equals(persons.properties___test_prop, '5'), 0)@@ -680,7 +646,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), and(has(['2', '5'], where_optimization.pmat_test_prop), where_optimization.pmat_test_prop IS NOT NULL)))))+ WHERE and(equals(where_optimization.team_id, 99999), and(has(['2', '5'], where_optimization.pmat_test_prop), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE in(persons.properties___test_prop,@@ -698,8 +664,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), (less(where_optimization.pmat_test_prop, '5')- AND (where_optimization.pmat_test_prop IS NOT NULL))))))+ WHERE and(equals(where_optimization.team_id, 99999), and(less(where_optimization.pmat_test_prop, '5'), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(less(persons.properties___test_prop, '5'), 0)@@ -716,8 +681,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), (equals(where_optimization.pmat_test_prop, '5')- AND (where_optimization.pmat_test_prop IS NOT NULL))))))+ WHERE and(equals(where_optimization.team_id, 99999), and(equals(where_optimization.pmat_test_prop, '5'), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(equals(persons.properties___test_prop, '5'), 0)@@ -734,8 +698,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), (less(where_optimization.pmat_test_prop, '5')- AND (where_optimization.pmat_test_prop IS NOT NULL))))))+ WHERE and(equals(where_optimization.team_id, 99999), and(less(where_optimization.pmat_test_prop, '5'), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(less(persons.properties___test_prop, '5'), 0)@@ -752,8 +715,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), (greater(where_optimization.pmat_test_prop, '5')- AND (where_optimization.pmat_test_prop IS NOT NULL))))))+ WHERE and(equals(where_optimization.team_id, 99999), and(greater(where_optimization.pmat_test_prop, '5'), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(greater(persons.properties___test_prop, '5'), 0)@@ -770,7 +732,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), and(ilike(where_optimization.pmat_test_prop, '%5%'), where_optimization.pmat_test_prop IS NOT NULL)))))+ WHERE and(equals(where_optimization.team_id, 99999), and(ilike(where_optimization.pmat_test_prop, '%5%'), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(ilike(toString(persons.properties___test_prop), '%5%'), 0)@@ -787,7 +749,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), and(like(lower(coalesce(where_optimization.pmat_test_prop, '')), lower('%value_that_is_long_enough%')), where_optimization.pmat_test_prop IS NOT NULL)))))+ WHERE and(equals(where_optimization.team_id, 99999), and(like(lower(coalesce(where_optimization.pmat_test_prop, '')), lower('%value_that_is_long_enough%')), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(ilike(toString(persons.properties___test_prop), '%value_that_is_long_enough%'), 0)@@ -804,8 +766,7 @@WHERE and(equals(person.team_id, 99999), in(id,(SELECT where_optimization.id AS idFROM person AS where_optimization- WHERE and(equals(where_optimization.team_id, 99999), (equals(where_optimization.pmat_test_prop, '5')- AND (where_optimization.pmat_test_prop IS NOT NULL))))))+ WHERE and(equals(where_optimization.team_id, 99999), and(equals(where_optimization.pmat_test_prop, '5'), isNotNull(where_optimization.pmat_test_prop))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS personsWHERE ifNull(equals(persons.properties___test_prop, '5'), 0)diff --git a/posthog/hogql/test/__snapshots__/test_query.ambr b/posthog/hogql/test/__snapshots__/test_query.ambrindex fd375780de35..3bcb3eefffae 100644--- a/posthog/hogql/test/__snapshots__/test_query.ambr+++ b/posthog/hogql/test/__snapshots__/test_query.ambr@@ -180,7 +180,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('today', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('today', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')), 0), ifNull(greaterOrEquals(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')), greaterOrEquals(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -272,14 +272,14 @@-- ClickHouseSELECT e.event AS event, s.session_id AS session_idFROM (- SELECT e.event AS event, e.`$session_id` AS `$session_id`+ SELECT e.event AS event, nullIf(nullIf(e.`$session_id`, ''), 'null') AS `properties__$session_id`FROM events AS eWHERE and(equals(e.team_id, 99999), isNotNull(nullIf(nullIf(e.`$session_id`, ''), 'null')))LIMIT 10) AS e LEFT JOIN (SELECT session_replay_events.session_id AS session_idFROM session_replay_eventsWHERE equals(session_replay_events.team_id, 99999)- GROUP BY session_replay_events.session_id) AS s ON equals(s.session_id, nullIf(nullIf(e.`$session_id`, ''), 'null'))+ GROUP BY session_replay_events.session_id) AS s ON equals(s.session_id, e.`properties__$session_id`)LIMIT 10SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -304,14 +304,14 @@-- ClickHouseSELECT e.event AS event, s.session_id AS session_idFROM (- SELECT e.event AS event, e.properties AS properties+ SELECT e.event AS event, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '') AS `properties__$$$session_id`FROM events AS e- WHERE and(equals(e.team_id, 99999), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '')))+ WHERE and(equals(e.team_id, 99999), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_1)s), ''), 'null'), '^"|"$', '')))LIMIT 10) AS e LEFT JOIN (SELECT session_replay_events.session_id AS session_idFROM session_replay_eventsWHERE equals(session_replay_events.team_id, 99999)- GROUP BY session_replay_events.session_id) AS s ON equals(s.session_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_1)s), ''), 'null'), '^"|"$', ''))+ GROUP BY session_replay_events.session_id) AS s ON equals(s.session_id, e.`properties__$$$session_id`)LIMIT 10SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.pynew file mode 100644index 000000000000..334cf9c5e5ef--- /dev/null+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py@@ -0,0 +1,1071 @@+"""ClickHouse pass: read each property from a faster precomputed column when one exists.++Lowering has already turned every `properties.x` read into a `PropertyAccess` node — "pull these keys out of this JSON+blob". This pass looks each one up. If the property is backed by a precomputed column (a materialized column, a dmat+column, or a property-group map), it rewrites the node to read that column instead: the same value, far cheaper than+parsing JSON. Reads with no backing column are left alone, and the printer prints them as the raw JSON extract.++It also rewrites comparisons over a backed property (`=`, `IN`, ranges, `LIKE`, is-null) to compare against the bare+column. ClickHouse can use a skip index on a plain column, but not on a value buried inside a JSON extract or an+`ifNull(...)`, so this is what keeps those queries fast.++Doing this here keeps the printer mechanical — it just prints the node it is given. What matters is identical results and+identical index usage, not identical SQL text, so verify by running the query and checking the skip-index `EXPLAIN`,+never by diffing SQL.++ClickHouse only: it runs after lowering (`prepare_ast_for_printing`) and emits ClickHouse-specific nodes, so it must+never run for the warehouse (Postgres / DuckDB) dialects.++One quirk is deliberate: an is-set check (`x IS NULL` / `x = NULL`) over a materialized property reads the column value,+so it treats both an empty string and the literal text `"null"` as "not set". This over-matches a true "does this key+exist in the blob" test, but tightening it would change query results.+"""++from dataclasses import dataclass+from typing import Literal, cast++from posthog.schema import MaterializationMode, PropertyGroupsMode++from posthog.hogql import ast+from posthog.hogql.base import _T_AST+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.models import DatabaseField+from posthog.hogql.errors import QueryError+from posthog.hogql.functions.mapping import HOGQL_COMPARISON_MAPPING+from posthog.hogql.printer.base import resolve_field_type+from posthog.hogql.printer.clickhouse import AI_BLOOM_FILTER_PROPERTIES, COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING+from posthog.hogql.restricted_properties import restricted_property_keys_for_table_type+from posthog.hogql.type_system import (+ ComparisonCompatibility,+ comparison_compatibility,+ constant_type_from_runtime_type,+ parse_sql_runtime_type,+ runtime_type_from_constant_type,+)+from posthog.hogql.utils import ilike_matches, like_matches+from posthog.hogql.visitor import CloningVisitor++from posthog.clickhouse.materialized_columns import TablesWithMaterializedColumns, get_materialized_column_for_property+from posthog.clickhouse.property_groups import property_groups+from posthog.models.property import PropertyName, TableColumn++# In non-nullable materialized columns these stored strings are treated as NULL.+MAT_COL_NULL_SENTINELS = ["", "null"]++# Leave the $ai_* bloom-filter columns to the printer: its comparison code already keeps them index-eligible+# (`COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING`, imported above so the two lists stay in sync). The value-read side skips+# their nullIf scrubbing for the same reason, via `AI_BLOOM_FILTER_PROPERTIES` (the same columns, named as properties).++_RANGE_OP_TO_CH_NAME: dict[ast.CompareOperationOp, str] = {+ ast.CompareOperationOp.Lt: "less",+ ast.CompareOperationOp.LtEq: "lessOrEquals",+ ast.CompareOperationOp.Gt: "greater",+ ast.CompareOperationOp.GtEq: "greaterOrEquals",+}+++@dataclass(frozen=True)+class MaterializedPropertySource:+ """The one physical column that backs an events/persons `properties.$x` read — which column, and how to read it.++ Either a materialized column, a dmat column, or a property-group map. Carries the index metadata the comparison+ rewrites need to keep that column usable by a skip index.+ """++ kind: Literal["materialized_column", "dmat", "property_group"]+ column: str+ is_nullable: bool+ # The column's physical ClickHouse type (e.g. "Nullable(Float64)"); None means the string default. Typed columns+ # skip the string sentinel scrubbing and can be compared bare when the value side is type-compatible.+ column_type: str | None = None+ # Index metadata the comparison optimizations consult to keep the column index-eligible.+ has_minmax_index: bool = False+ has_ngram_lower_index: bool = False+ has_bloom_filter_index: bool = False+ has_bloom_filter_lower_index: bool = False+++def _unwrap_to_table_type(field_type: ast.FieldType) -> ast.TableType | None:+ """The plain table type behind a field's table type, unwrapping alias and virtual-table layers."""+ table_type: ast.Type | None = field_type.table_type+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.VirtualTableType)):+ table_type = table_type.table_type+ return table_type if isinstance(table_type, ast.TableType) else None+++def resolve_materialized_property_source(+ field_type: ast.FieldType, property_name: str, context: HogQLContext+) -> MaterializedPropertySource | None:+ """The physical column that backs `<events/persons>.<field>.<property_name>`, or None if nothing does.++ Tries the backing columns in priority order — a static materialized column first, then a dmat column, then the first+ property-group map column — using the same registries the old printer used. Returns None when the property has no+ backing column (so it stays a JSON read), when materialization is turned off, or when the property is access-+ restricted.+ """+ if context.modifiers.materializationMode == "disabled":+ return None++ # Property-level access control: a restricted property must never resolve to a backing column, on any path (value+ # read, comparison, key-existence). The column holds the raw value, so a comparison like `WHERE properties.x = 'y'`+ # could otherwise read it and probe the value. Declining here makes the comparison optimizers fall back; the read+ # itself becomes a constant NULL in `_substitute_value_read`.+ if property_name in restricted_property_keys_for_table_type(field_type.table_type, context):+ return None++ table_type = _unwrap_to_table_type(field_type)+ if table_type is None:+ return None++ # The materialized-column registry is keyed by the ClickHouse table name, which isn't always the HogQL name+ # (RawPersonsTable is "raw_persons" in HogQL but "person" in ClickHouse). Use the ClickHouse name, or person+ # properties would miss their materialized column and fall back to a slower JSON read.+ table_name = table_type.table.to_printed_clickhouse(context)++ field = field_type.resolve_database_field(context)+ if not isinstance(field, DatabaseField):+ # A field on a resolved table that doesn't resolve to a real column is a malformed AST. Fail loud, as the old+ # printer did here, rather than silently degrading to a raw JSON read.+ raise QueryError(f"Can't resolve field {field_type.name} on table {table_name}")+ field_name = field.name++ # 1) static materialized column (mat_* / pmat_*)+ materialized_column = get_materialized_column_for_property(+ cast(TablesWithMaterializedColumns, table_name),+ cast(TableColumn, field_name),+ cast(PropertyName, property_name),+ )+ if materialized_column is not None:+ return MaterializedPropertySource(+ kind="materialized_column",+ column=materialized_column.name,+ is_nullable=materialized_column.is_nullable,+ column_type=materialized_column.type,+ has_minmax_index=materialized_column.has_minmax_index,+ has_ngram_lower_index=materialized_column.has_ngram_lower_index,+ has_bloom_filter_index=materialized_column.has_bloom_filter_index,+ has_bloom_filter_lower_index=materialized_column.has_bloom_filter_lower_index,+ )++ # 2) dmat (dynamic materialized) slot — events.properties only, resolved from the property swapper+ if context.property_swapper is not None and table_name == "events" and field_name == "properties":+ property_info = context.property_swapper.event_properties.get(property_name)+ if property_info and (dmat_column := property_info.get("dmat")):+ return MaterializedPropertySource(kind="dmat", column=dmat_column, is_nullable=True)++ # 3) first property-group Map column for the key+ return resolve_property_group_source(field_type, property_name, context)+++def resolve_property_group_source(+ field_type: ast.FieldType, property_name: str, context: HogQLContext+) -> MaterializedPropertySource | None:+ """The first property-group map column for `<events/persons>.<field>.<property_name>`, ignoring materialized columns.++ Used for key-existence (`JSONHas`), which is answered from the property group's keys bloom-filter index even when an+ individually materialized column also exists — that column can't answer key-existence, since it stores '' for both+ "absent" and "empty". `resolve_materialized_property_source` would pick the materialized column first, so JSONHas+ resolves the group directly instead.+ """+ if context.modifiers.propertyGroupsMode not in (PropertyGroupsMode.ENABLED, PropertyGroupsMode.OPTIMIZED):+ return None++ # Same access-control rule as resolve_materialized_property_source: a restricted property never resolves to a group+ # column. This guards the direct callers (JSONHas, property-group comparisons), which bypass that function.+ if property_name in restricted_property_keys_for_table_type(field_type.table_type, context):+ return None++ table_type = _unwrap_to_table_type(field_type)+ if table_type is None:+ return None++ field = field_type.resolve_database_field(context)+ if not isinstance(field, DatabaseField):+ return None++ table_name = table_type.table.to_printed_clickhouse(context)+ for group_column in property_groups.get_property_group_columns(table_name, field.name, property_name):+ return MaterializedPropertySource(kind="property_group", column=group_column, is_nullable=True)+ return None+++# --- helpers to read a PropertyAccess's source column + key path -----------------------------------------------------+#+# A `PropertyAccess`'s own type is just its value type (a nullable String), so everything this pass needs comes from the+# node's structure instead: `node.expr` is the blob `Field` (its `.type` points at the table and column), and+# `node.keys` is the key path (keys[0] is the property name; deeper keys index into the extracted value).+++def _blob_field_type_of(node: ast.PropertyAccess) -> ast.FieldType | None:+ """The source blob column's `FieldType` (`node.expr.type`), the input to `resolve_materialized_property_source`."""+ expr_type = node.expr.type+ return expr_type if isinstance(expr_type, ast.FieldType) else None+++# --- value substitution: rebuild the printer's materialized-column read as AST ----------------------------------------+++def _sentinel(value: str) -> ast.Constant:+ """A fixed scrubbing constant ('' / 'null' / the quote-trim regex / 'true' / 'false'), rendered inline not parameterized.++ `inline_sentinel` makes the printer emit the value inline (escaped), so this AST-built scrub renders identically to the+ `json_extract_trim_quotes` helper's inline string. The printer only honors it for the fixed `INLINE_SENTINEL_LITERALS`+ set. Inlining doesn't affect skip-index eligibility (that depends on the column being bare).+ """+ return ast.Constant(value=value, inline_sentinel=True)+++def _augment_plain_table_type(table_type: ast.TableType, column_name: str, is_nullable: bool) -> ast.TableType:+ table = table_type.table+ if table.has_field(column_name):+ return table_type+ synthetic = DatabaseField(name=column_name, nullable=is_nullable)+ augmented = table.model_copy(update={"fields": {**table.fields, column_name: synthetic}})+ return ast.TableType(table=augmented)+++def _augment_table_type(+ table_type: ast.Type, column_name: str, *, is_nullable: bool+) -> ast.TableType | ast.TableAliasType | None:+ if isinstance(table_type, ast.VirtualTableType):+ # PoE person properties: the physical mat/group columns live on the underlying events table.+ return _augment_table_type(table_type.table_type, column_name, is_nullable=is_nullable)+ if isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):+ inner = table_type.table_type+ if not isinstance(inner, ast.TableType):+ return None+ return ast.TableAliasType(+ alias=table_type.alias, table_type=_augment_plain_table_type(inner, column_name, is_nullable)+ )+ if isinstance(table_type, ast.TableType):+ return _augment_plain_table_type(table_type, column_name, is_nullable)+ return None+++def _synthetic_column_field(field_type: ast.FieldType, column_name: str, *, is_nullable: bool) -> ast.Field | None:+ """A typed `Field` for a physical ClickHouse column that the HogQL schema doesn't know about.++ Materialized / dmat / property-group columns exist on the table but aren't in the HogQL schema, so a plain `Field`+ can't resolve to them. Build a fake `DatabaseField` on a copy of the table and point a fresh `FieldType` at it,+ keeping any table alias so the printed prefix (`events.` / `e.`) is unchanged.+ """+ table_type = _augment_table_type(field_type.table_type, column_name, is_nullable=is_nullable)+ if table_type is None:+ return None+ return ast.Field(+ chain=[column_name],+ type=ast.FieldType(name=column_name, table_type=table_type),+ )+++def _materialized_head_expr(+ source: MaterializedPropertySource,+ field_type: ast.FieldType,+ first_key: str,+ *,+ is_single: bool,+ materialization_mode: MaterializationMode | None,+) -> ast.Expr | None:+ """The read for the top-level key (chain[0]) from a backing column: a property-group map lookup, or a scrubbed column."""+ if source.kind == "property_group":+ # has(map, key) ? map[key] : null — guard the map read so a missing key returns NULL, not the map's '' default.+ has_field = _synthetic_column_field(field_type, source.column, is_nullable=True)+ get_field = _synthetic_column_field(field_type, source.column, is_nullable=True)+ if has_field is None or get_field is None:+ return None+ return ast.Call(+ name="if",+ args=[+ ast.Call(name="has", args=[has_field, ast.Constant(value=first_key)]),+ ast.ArrayAccess(array=get_field, property=ast.Constant(value=first_key)),+ ast.Constant(value=None),+ ],+ )++ column_field = _synthetic_column_field(field_type, source.column, is_nullable=source.is_nullable)+ if column_field is None:+ return None++ # Nullable columns (dmat, nullable mat) and the index-friendly $ai single-key columns are read bare.+ if source.is_nullable or (is_single and first_key in AI_BLOOM_FILTER_PROPERTIES):+ return column_field++ # A typed (non-string) column has no string sentinels to scrub — wrapping it in nullIf(col, '') would not even+ # type-check in ClickHouse — so it is read bare as well.+ if not _is_string_column(source):+ return column_field++ # Non-nullable materialized column: scrub the '' / 'null' string sentinels back to NULL.+ scrubbed_empty = ast.Call(name="nullIf", args=[column_field, _sentinel("")])+ if materialization_mode == MaterializationMode.LEGACY_NULL_AS_STRING:+ return scrubbed_empty+ return ast.Call(name="nullIf", args=[scrubbed_empty, _sentinel("null")])+++def _substitute_value_read(node: ast.PropertyAccess, context: HogQLContext) -> ast.Expr | None:+ """The backing-column read for a `PropertyAccess`, or None to leave it as the JSON extract.++ Picks the column and builds the read (the numeric/boolean cast is not handled here — it already wraps this node).+ Returns a constant NULL for an access-restricted property, or None when the property has no precomputed column+ (materialized, dmat, or property group) to read from — in which case it stays a raw JSON extract.+ """+ field_type = _blob_field_type_of(node)+ # Lowering builds every PropertyAccess with the blob FieldType on `expr` and a non-empty key path. Assert the+ # invariant rather than silently bailing, so a real violation fails loud instead of degrading to a JSON read.+ assert field_type is not None and node.keys++ first_key = str(node.keys[0])+ deeper_keys: list[str | int] = list(node.keys[1:])++ # Access control: a restricted property reads as NULL. The blob path would compute the same value — the printer's+ # JSONDropKeys strips the key, so extracting it always yields '' which scrubs to NULL — so return that constant+ # directly and skip the wasted drop-then-extract. (The column resolvers also decline, so comparisons over a+ # restricted property never read the backing column either; their operand falls through to this same NULL.)+ if first_key in restricted_property_keys_for_table_type(field_type.table_type, context):+ _record_property_usage(context, None)+ return ast.Constant(value=None, type=ast.StringType(nullable=True))++ source = resolve_materialized_property_source(field_type, first_key, context)+ _record_property_usage(context, source.kind if source is not None else None)+ if source is None:+ return None++ head = _materialized_head_expr(+ source,+ field_type,+ first_key,+ is_single=not deeper_keys,+ materialization_mode=context.modifiers.materializationMode,+ )+ if head is None:+ return None+ if not deeper_keys:+ return head+ # Deeper keys read the column value as a JSON string. Emit a PropertyAccess rather than building the extract here:+ # the printer renders that node via `json_extract_trim_quotes` (kafka_engine.py), the one implementation of the+ # extract-and-trim SQL shape.+ return ast.PropertyAccess(expr=head, keys=deeper_keys, type=ast.StringType(nullable=True))+++# --- comparison rewrites: keep the bare column eligible for skip indexes -----------------------------------------------+#+# By default a property comparison reads the materialized column wrapped in null-scrubbing functions+# (replaceRegexpAll(nullIf(nullIf(...)))). ClickHouse can't use the column's skip index through that wrapping, so it+# scans every row. When one side of a comparison is a property with a materialized column (or a property-group map+# entry), these rewrites rebuild the comparison against the bare column instead, restoring the empty/null handling+# inline so the rows are unchanged. The bare column is index-eligible, so ClickHouse can skip granules.+++def _call(name: str, args: list[ast.Expr]) -> ast.Call:+ return ast.Call(name=name, args=args)+++def _const(value: object) -> ast.Constant:+ return ast.Constant(value=value)+++def _lower(expr: ast.Expr) -> ast.Call:+ """`lower(expr)`, typed non-nullable String so the printer doesn't ifNull-wrap a comparison against it."""+ return ast.Call(name="lower", args=[expr], type=ast.StringType(nullable=False))+++def _coalesce_empty(expr: ast.Expr) -> ast.Call:+ """`coalesce(expr, '')`, typed non-nullable String — matches the lower-index expression and prints bare."""+ return ast.Call(name="coalesce", args=[expr, _sentinel("")], type=ast.StringType(nullable=False))+++def _string_pattern_constant(expr: ast.Expr) -> ast.Constant | None:+ return expr if isinstance(expr, ast.Constant) and isinstance(expr.value, str) else None+++def _column_constant_type(source: MaterializedPropertySource) -> ast.ConstantType:+ """The backing column's physical ClickHouse type as a ConstantType; an untyped column is the string default."""+ return constant_type_from_runtime_type(parse_sql_runtime_type(source.column_type or "String"))+++def _is_string_column(source: MaterializedPropertySource) -> bool:+ return isinstance(_column_constant_type(source), ast.StringType)+++# Comparison compatibilities the rewrites accept: provably comparable as-is, or via a cast ClickHouse does cheaply.+_OPTIMIZER_COMPATIBLE_COMPARISONS = {+ ComparisonCompatibility.DEFINITELY_COMPATIBLE,+ ComparisonCompatibility.CHEAP_CAST,+}+++def _record_range_rewrite(context: HogQLContext, result: str) -> None:+ if context.type_observability is None:+ return+ context.type_observability.record_materialized_range_rewrite(result)+ if result.startswith("fired"):+ # A fired rewrite reads the materialized column directly, bypassing the value-substitution path that normally+ # accounts for the materialized access, so record the usage here.+ context.type_observability.record_materialized_property_usage("materialized_column")+++_USAGE_BY_SOURCE_KIND = {+ "materialized_column": "materialized_column",+ "dmat": "dynamic_materialized_column",+ "property_group": "property_group",+}+++def _record_property_usage(context: HogQLContext, kind: str | None) -> None:+ """Record how a property value read was served: from a backing column kind, or "json" when none backs it."""+ if context.type_observability is None:+ return+ context.type_observability.record_materialized_property_usage(_USAGE_BY_SOURCE_KIND.get(kind or "", "json"))+++@dataclass(frozen=True)+class _OptimizableProperty:+ """A single-key property used in a comparison, paired with the physical column that backs it.++ `field_type` is the blob column's type, `key` is the property name, and `source` is the backing column. The methods+ build the column expressions the comparison optimizers compare against.+ """++ field_type: ast.FieldType+ key: str+ source: MaterializedPropertySource++ def bare_column(self) -> ast.Field:+ """The backing column as a bare `Field`, typed non-nullable.++ Non-nullable typing stops the printer from `ifNull`-wrapping the comparison — the wrapping that hides the column+ from skip indexes. A genuinely Nullable column is guarded separately (see `is_not_null`). This doubles as the+ map column for a property group, where a missing key reads as the '' default rather than SQL NULL.+ """+ field = _synthetic_column_field(self.field_type, self.source.column, is_nullable=False)+ assert field is not None # the source was resolved from this same field_type+ return field++ def is_not_null(self) -> ast.Call:+ """`isNotNull(col)` over the nullable read of the column — guards a bare comparison against NULL rows."""+ field = _synthetic_column_field(self.field_type, self.source.column, is_nullable=True)+ assert field is not None+ return _call("isNotNull", [field])++ def group_has(self) -> ast.Call:+ """`has(map_column, key)` — true when the property group contains the key (uses the keys bloom-filter index)."""+ return _call("has", [self.bare_column(), _const(self.key)])++ def group_value(self) -> ast.ArrayAccess:+ """`map_column[key]`, typed non-nullable String — the property's value from the group map.++ A missing key reads as the '' default, never SQL NULL; the non-nullable type keeps `equals(map[key], v)` out of+ an `ifNull` wrapper so the values bloom-filter index still applies.+ """+ return ast.ArrayAccess(array=self.bare_column(), property=_const(self.key), type=ast.StringType(nullable=False))+++class ClickHousePropertyResolver(CloningVisitor):+ """Rewrites lowered `PropertyAccess` reads (and comparisons over them) to read backing columns where they exist.++ After this pass, a backed property is an ordinary column expression; an unbacked (or restricted) one stays a+ `PropertyAccess` and prints as the raw JSON extract.+ """++ def __init__(self, context: HogQLContext) -> None:+ # The AST is printed directly after this pass, so keep resolved types rather than clearing them.+ super().__init__(clear_types=False)+ self.context = context+ # Identity set of the table types in scope for the SELECT currently being visited (its FROM/JOIN chain,+ # including the layers behind alias/virtual wrappers). Guards the comparison rewrites: a rewrite reads a real+ # table column, which is only printable when that table is in the current FROM. A property read that an earlier+ # transform moved behind a subquery (events predicate pushdown) must decline instead.+ self._tables_in_scope: list[set[int]] = []++ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ scope: set[int] = set()+ join: ast.JoinExpr | None = node.select_from+ while join is not None:+ table_type: ast.Type | None = join.table.type if join.table is not None else None+ while table_type is not None:+ scope.add(id(table_type))+ table_type = getattr(table_type, "table_type", None)+ join = join.next_join+ self._tables_in_scope.append(scope)+ try:+ return super().visit_select_query(node)+ finally:+ self._tables_in_scope.pop()++ def _property_table_in_scope(self, field_type: ast.FieldType) -> bool:+ """True if the property's source table is in the current SELECT's FROM/JOIN chain (by object identity)."""+ if not self._tables_in_scope:+ # A bare fragment (within_non_hogql_query) has no SELECT scope, and no transform that could move a read+ # behind a subquery runs on fragments — treat it as in scope.+ return True+ scope = self._tables_in_scope[-1]+ table_type: ast.Type | None = field_type.table_type+ while table_type is not None:+ if id(table_type) in scope:+ return True+ table_type = getattr(table_type, "table_type", None)+ return False++ def _lowered_property_operand(self, expr: ast.Expr) -> ast.PropertyAccess | None:+ """The lowered `properties.$x` behind a comparison operand, or None.++ After lowering, such an operand is a `PropertyAccess` (often wrapped in an `Alias`).+ """+ if isinstance(expr, ast.Alias):+ expr = expr.expr+ if isinstance(expr, ast.PropertyAccess):+ return expr+ return None++ def _single_key_property(self, expr: ast.Expr) -> tuple[ast.FieldType, str] | None:+ """The (blob `FieldType`, property name) of a single-key property operand, or None.++ Only a single-key access (`properties.x`, no deeper `.a.b`) maps to one backing column. A multi-key access reads+ the column and then JSON-extracts deeper, so it can't use the bare-column comparison rewrites.+ """+ node = self._lowered_property_operand(expr)+ if node is not None and len(node.keys) == 1:+ field_type = _blob_field_type_of(node)+ if field_type is not None:+ return field_type, str(node.keys[0])++ # The operand can also carry the property on its resolved type rather than as a bare `PropertyAccess`: a+ # reference to a select alias over a property read (`SELECT properties.x AS a ... WHERE a = 'v'`) resolves+ # through the alias wrapper to the original `PropertyType`, and a boolean/numeric property gets wrapped by the+ # swapper in a cast (`toBool(transform(toString(...)))`) with the `PropertyType` underneath. Read the property+ # identity off the type — that is the resolver's own binding, so a shadowing alias of the same name can never+ # be confused with it (its type points at whatever it actually aliases). Skip joined-subquery properties+ # (lowering skips them too: they print as `alias.field`) and properties whose table is not in the current+ # FROM (a transform moved the read behind a subquery; the bare column would be out of scope).+ prop_type = resolve_field_type(expr)+ if (+ isinstance(prop_type, ast.PropertyType)+ and len(prop_type.chain) == 1+ and prop_type.joined_subquery is None+ and self._property_table_in_scope(prop_type.field_type)+ ):+ return prop_type.field_type, str(prop_type.chain[0])+ return None++ # --- value substitution ---++ def visit_property_access(self, node: ast.PropertyAccess) -> ast.Expr:+ substituted = _substitute_value_read(node, self.context)+ if substituted is not None:+ return substituted+ return super().visit_property_access(node)++ # --- comparison / call rewrites ---++ def visit_call(self, node: ast.Call) -> ast.Expr:+ # `isNull` / `isNotNull` / `JSONHas` on a property-group property can be answered by `has(map, key)` alone,+ # without reading the values subcolumn — so it stays eligible for the keys bloom-filter index.+ optimized = self._optimize_property_group_call(node)+ if optimized is not None:+ return optimized++ # A comparison written in call form (`equals(properties.x, v)`, `ilike(toString(properties.x), p)`,+ # `in(properties.x, (...))`) is still a comparison: route it through visit_compare_operation so the same rewrites+ # fire. Otherwise we'd descend into the args and substitute the value, losing the optimization. Only the plain+ # 2-arg form, no extra params.+ if (+ node.name in HOGQL_COMPARISON_MAPPING+ and len(node.args) == 2+ and node.params is None+ and node.distinct is False+ and node.within_group is None+ and node.order_by is None+ and node.filter_expr is None+ ):+ return self.visit_compare_operation(+ ast.CompareOperation(left=node.args[0], right=node.args[1], op=HOGQL_COMPARISON_MAPPING[node.name])+ )++ return super().visit_call(node)++ def visit_compare_operation(self, node: ast.CompareOperation) -> ast.Expr:+ # Try each skip-index comparison rewrite in order. Each one consumes the property operand and returns the+ # rewritten comparison, so once one matches we must NOT also substitute the value. (session_id is left to the+ # printer — it optimizes a real column, not a property.)+ optimized = (+ self._optimize_property_group_compare(node)+ or self._optimize_materialized_equals(node)+ or self._optimize_materialized_range(node)+ or self._optimize_materialized_ilike(node)+ or self._optimize_materialized_like(node)+ or self._optimize_materialized_in(node)+ or self._optimize_materialized_lower_in(node)+ )+ if optimized is not None:+ return optimized++ # Intentional gap: nothing above rewrites `property = NULL` / `!= NULL`, so it falls through to super() and the+ # surviving PropertyAccess reads the scrubbed materialized column. An is-set check therefore treats both an empty+ # string and the literal text "null" as "not set", which over-matches a true "does this key exist in the blob"+ # test. Left this way deliberately — tightening it would change query results.+ return super().visit_compare_operation(node)++ # --- property operand detection ---++ def _materialized_string_property(self, expr: ast.Expr) -> _OptimizableProperty | None:+ """A single-key string property backed by an individually materialized column, or None.++ Unwraps a `toString(properties.x)` wrapper, requires a single key, skips properties whose resolved type isn't a+ string, and requires a materialized column (not a property group). The plain and `toString(...)` forms both+ resolve to the same lowered property.+ """+ single = self._single_key_property(expr)+ if single is None and isinstance(expr, ast.Call) and expr.name == "toString" and len(expr.args) == 1:+ # Only a direct lowered property read, not toString(toFloat(...)): the inner arg must itself be the property.+ single = self._single_key_property(expr.args[0])+ if single is None:+ return None+ field_type, property_name = single++ if self.context.property_swapper is not None:+ prop_info = self.context.property_swapper.event_properties.get(property_name)+ if prop_info is not None and prop_info.get("type") not in (None, "String"):+ return None++ source = resolve_materialized_property_source(field_type, property_name, self.context)+ if source is None or source.kind not in ("materialized_column", "dmat") or not _is_string_column(source):+ return None+ return _OptimizableProperty(+ field_type=field_type,+ key=property_name,+ source=source,+ )++ def _materialized_property_for_op(self, expr: ast.Expr) -> _OptimizableProperty | None:+ """A single-key materialized-column property (any resolved type), for IN comparisons that don't need a string."""+ single = self._single_key_property(expr)+ if single is None:+ return None+ field_type, property_name = single+ source = resolve_materialized_property_source(field_type, property_name, self.context)+ if source is None or source.kind not in ("materialized_column", "dmat") or not _is_string_column(source):+ return None+ return _OptimizableProperty(+ field_type=field_type,+ key=property_name,+ source=source,+ )++ def _property_group_property(self, expr: ast.Expr) -> _OptimizableProperty | None:+ """A single-key property backed by a property group, only under OPTIMIZED mode."""+ if self.context.modifiers.propertyGroupsMode != PropertyGroupsMode.OPTIMIZED:+ return None+ single = self._single_key_property(expr)+ if single is None:+ return None+ field_type, property_name = single+ source = resolve_materialized_property_source(field_type, property_name, self.context)+ if source is None or source.kind != "property_group":+ return None+ return _OptimizableProperty(+ field_type=field_type,+ key=property_name,+ source=source,+ )++ @staticmethod+ def _is_ai_column(source: MaterializedPropertySource) -> bool:+ return source.column.strip("`\"'") in COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING++ # --- property-group optimizers ---++ def _optimize_property_group_call(self, node: ast.Call) -> ast.Expr | None:+ if self.context.modifiers.propertyGroupsMode != PropertyGroupsMode.OPTIMIZED:+ return None++ if node.name in ("isNull", "isNotNull") and len(node.args) == 1:+ prop = self._property_group_property(node.args[0])+ if prop is None:+ return None+ has_expr = prop.group_has()+ return _call("not", [has_expr]) if node.name == "isNull" else has_expr++ if node.name == "JSONHas" and len(node.args) == 2 and isinstance(node.args[1], ast.Constant):+ # JSONHas(blob, key): the key is the literal second arg, and the first arg is the blob Field. Resolve the+ # property group for that key off the blob's FieldType.+ field_expr = node.args[0]+ field_type = resolve_field_type(field_expr)+ if not isinstance(field_type, ast.FieldType):+ return None+ key = str(node.args[1].value)+ # Key-existence is answered from the property group even when a materialized column also exists, so resolve+ # the group directly — the mat-column-first resolver would otherwise shadow it.+ source = resolve_property_group_source(field_type, key, self.context)+ if source is None or source.kind != "property_group":+ return None+ return _OptimizableProperty(+ field_type=field_type,+ key=key,+ source=source,+ ).group_has()++ return None++ def _optimize_property_group_compare(self, node: ast.CompareOperation) -> ast.Expr | None:+ if self.context.modifiers.propertyGroupsMode != PropertyGroupsMode.OPTIMIZED:+ return None++ if node.op in (ast.CompareOperationOp.Eq, ast.CompareOperationOp.NotEq):+ return self._optimize_property_group_eq(node)+ if node.op == ast.CompareOperationOp.In:+ return self._optimize_property_group_in(node)+ return None++ def _optimize_property_group_eq(self, node: ast.CompareOperation) -> ast.Expr | None:+ prop: _OptimizableProperty | None = None+ constant_expr: ast.Constant | None = None+ if isinstance(node.right, ast.Constant):+ prop = self._property_group_property(node.left)+ constant_expr = node.right+ elif isinstance(node.left, ast.Constant):+ prop = self._property_group_property(node.right)+ constant_expr = node.left+ if prop is None or constant_expr is None:+ return None++ value = constant_expr.value+ if node.op == ast.CompareOperationOp.Eq:+ if value is None:+ # `= NULL` means the key is absent: not(has(map, key)). Avoids reading the values subcolumn.+ return _call("not", [prop.group_has()])+ if value is True:+ # Booleans are stored as the strings 'true'/'false' in the group map; compare against those so the+ # comparison stays index-eligible.+ return _call("equals", [prop.group_value(), _sentinel("true")])+ if value is False:+ return _call("equals", [prop.group_value(), _sentinel("false")])+ if isinstance(constant_expr.type, ast.StringType):+ eq = _call("equals", [prop.group_value(), _const(value)])+ if value == "":+ # '' is also the map's default for an absent key, so also check the key is present.+ return _call("and", [prop.group_has(), eq])+ return eq+ return None++ # NotEq+ if value is None:+ # `!= NULL` means the key is present: has(map, key). Uses the keys index, skips the values subcolumn.+ return prop.group_has()+ return None++ def _optimize_property_group_in(self, node: ast.CompareOperation) -> ast.Expr | None:+ # IN is not commutative; only the left operand can be the property.+ prop = self._property_group_property(node.left)+ if prop is None:+ return None++ if isinstance(node.right, ast.Constant):+ value = node.right.value+ if value is None:+ return None # IN (NULL) is true if the key is absent OR the value is null — can't shortcut+ if value == "":+ return _call("and", [prop.group_has(), _call("equals", [prop.group_value(), _const("")])])+ if isinstance(node.right.type, ast.StringType):+ return _call("equals", [prop.group_value(), _const(value)])+ return None+ if isinstance(node.right, (ast.Tuple, ast.Array)):+ return self._optimize_group_in_with_values(node.right.exprs, prop)+ return None++ def _optimize_group_in_with_values(self, values: list[ast.Expr], prop: _OptimizableProperty) -> ast.Expr | None:+ # Bail on any non-string / empty / NULL value — those can't use the bare-column form.+ string_values: list[str] = []+ for v in values:+ if not isinstance(v, ast.Constant) or v.value == "" or v.value is None or not isinstance(v.value, str):+ return None+ string_values.append(v.value)+ if len(string_values) == 0:+ return _const(False) # IN () is always false+ if len(string_values) == 1:+ return _call("equals", [prop.group_value(), _const(string_values[0])])+ # ClickHouse's transform_null_in setting makes `in(map[key], ...)` skip the keys index; the has() guard restores it.+ in_expr = _call("in", [prop.group_value(), ast.Tuple(exprs=[_const(v) for v in string_values])])+ return _call("and", [prop.group_has(), in_expr])++ # --- individually-materialized-column optimizers ---++ def _optimize_materialized_equals(self, node: ast.CompareOperation) -> ast.Expr | None:+ if node.op not in (ast.CompareOperationOp.Eq, ast.CompareOperationOp.NotEq):+ return None++ prop: _OptimizableProperty | None = None+ constant_expr: ast.Constant | None = None+ if (p := self._materialized_string_property(node.left)) and (c := _string_pattern_constant(node.right)):+ prop, constant_expr = p, c+ elif (p := self._materialized_string_property(node.right)) and (c := _string_pattern_constant(node.left)):+ prop, constant_expr = p, c+ if prop is None or constant_expr is None:+ return None++ if constant_expr.value in MAT_COL_NULL_SENTINELS:+ return None # comparing against '' / 'null' itself: let the normal scrubbed read handle it+ if self._is_ai_column(prop.source):+ return None # the printer handles the $ai columns++ column = prop.bare_column()+ value = _const(constant_expr.value)+ if node.op == ast.CompareOperationOp.Eq:+ eq = _call("equals", [column, value])+ if prop.source.is_nullable:+ return _call("and", [eq, prop.is_not_null()])+ return eq+ # NotEq+ neq = _call("notEquals", [column, value])+ if prop.source.is_nullable:+ return _call("ifNull", [neq, _const(True)])+ return neq++ def _optimize_materialized_range(self, node: ast.CompareOperation) -> ast.Expr | None:+ op_name = _RANGE_OP_TO_CH_NAME.get(node.op)+ if op_name is None:+ return None+ # the column is always the left operand here, so only that side is handled.+ prop = self._materialized_string_property(node.left)+ if prop is None:+ return self._optimize_typed_materialized_range(node, op_name)+ if not isinstance(node.right, ast.Constant) or node.right.value is None:+ _record_range_rewrite(self.context, "skipped")+ return None+ if self._is_ai_column(prop.source):+ _record_range_rewrite(self.context, "skipped")+ return None++ cmp = _call(op_name, [prop.bare_column(), _const(node.right.value)])+ if prop.source.is_nullable:+ _record_range_rewrite(self.context, "fired_compare")+ return _call("and", [cmp, prop.is_not_null()])+ # Non-nullable: exclude the '' / 'null' sentinels inline so the bare comparison stays index-eligible.+ _record_range_rewrite(self.context, "fired_compare")+ clauses: list[ast.Expr] = [cmp]+ clauses.extend(_call("notEquals", [prop.bare_column(), _sentinel(s)]) for s in MAT_COL_NULL_SENTINELS)+ return _call("and", clauses)++ def _optimize_typed_materialized_range(self, node: ast.CompareOperation, op_name: str) -> ast.Expr | None:+ """Range over a property backed by a typed (non-string) materialized column: compare the bare column.++ A typed column stores the property in its real type (e.g. `Nullable(Float64)`, `Nullable(DateTime64)`), so when+ the property's semantic type matches the column and the value side is comparable, the comparison can read the+ bare column — no cast wrapper, no sentinel scrub — which keeps it eligible for the column's minmax index. A+ string value compared against a DateTime column is converted with `toDateTime64(value, 6, tz)` so the column+ side stays bare. Only nullable typed columns rewrite: a non-nullable typed column stores the ClickHouse type+ default for a missing property, and a bare comparison could not tell a real default from a missing value.+ """+ single = self._single_key_property(node.left)+ if single is None:+ return None+ field_type, property_name = single+ source = resolve_materialized_property_source(field_type, property_name, self.context)+ if source is None or source.kind != "materialized_column" or _is_string_column(source):+ return None++ physical = _column_constant_type(source)+ semantic = self._operand_semantic_type(node.left)+ if semantic is None or comparison_compatibility(semantic, physical) not in _OPTIMIZER_COMPATIBLE_COMPARISONS:+ _record_range_rewrite(self.context, "skipped")+ return None++ right_constant = node.right if isinstance(node.right, ast.Constant) else None+ if right_constant is not None and right_constant.value is None:+ _record_range_rewrite(self.context, "skipped")+ return None++ value_type = self._operand_semantic_type(node.right)+ converts_to_datetime = (+ right_constant is not None+ and value_type is not None+ and runtime_type_from_constant_type(physical).family == "datetime"+ and runtime_type_from_constant_type(value_type).family == "string"+ )+ if not converts_to_datetime and (+ value_type is None+ or comparison_compatibility(physical, value_type) not in _OPTIMIZER_COMPATIBLE_COMPARISONS+ ):+ _record_range_rewrite(self.context, "skipped")+ return None++ if not source.is_nullable:+ _record_range_rewrite(self.context, "skipped")+ return None++ right_expr = cast(ast.Expr, self.visit(node.right))+ if converts_to_datetime:+ right_expr = _call("toDateTime64", [right_expr, _const(6), ast.Constant(value=self._project_timezone())])++ column = _OptimizableProperty(field_type=field_type, key=property_name, source=source)+ cmp = _call(op_name, [column.bare_column(), right_expr])+ _record_range_rewrite(self.context, "fired_compare")+ return _call("and", [cmp, column.is_not_null()])++ def _operand_semantic_type(self, expr: ast.Expr) -> ast.ConstantType | None:+ """The semantic type of a comparison operand: the property's registered type for a property read (read off the+ resolver's `PropertyType` binding, which survives the swapper's cast wrapper), or the expression's own resolved+ type. A bare lowered JSON read is semantically a string."""+ if isinstance(expr, ast.Alias):+ expr = expr.expr+ if isinstance(expr, ast.PropertyAccess):+ return expr.type if isinstance(expr.type, ast.ConstantType) else ast.StringType(nullable=True)+ expr_type = resolve_field_type(expr)+ if expr_type is None:+ return None+ try:+ return expr_type.resolve_constant_type(self.context)+ except Exception:+ return None++ def _project_timezone(self) -> str:+ if self.context.modifiers.convertToProjectTimezone is False:+ return "UTC"+ return self.context.database.get_timezone() if self.context.database else "UTC"++ def _optimize_materialized_ilike(self, node: ast.CompareOperation) -> ast.Expr | None:+ if node.op not in (ast.CompareOperationOp.ILike, ast.CompareOperationOp.NotILike):+ return None+ prop = self._materialized_string_property(node.left)+ pattern = _string_pattern_constant(node.right)+ if prop is None or pattern is None:+ return None++ is_ilike = node.op == ast.CompareOperationOp.ILike+ if prop.source.is_nullable:+ if is_ilike:+ if prop.source.has_ngram_lower_index:+ # Match the ngram_lower index expression: like(lower(coalesce(col, '')), lower(pattern)).+ indexed = _lower(_coalesce_empty(prop.bare_column()))+ return _call("and", [_call("like", [indexed, _lower(_const(pattern.value))]), prop.is_not_null()])+ return _call("and", [_call("ilike", [prop.bare_column(), _const(pattern.value)]), prop.is_not_null()])+ return _call("ifNull", [_call("notILike", [prop.bare_column(), _const(pattern.value)]), _const(True)])++ # Non-nullable: bail if the pattern could match a stored sentinel.+ if any(ilike_matches(cast(str, pattern.value), s) for s in MAT_COL_NULL_SENTINELS):+ return None+ if is_ilike:+ if prop.source.has_ngram_lower_index:+ return _call("like", [_lower(prop.bare_column()), _lower(_const(pattern.value))])+ return _call("ilike", [prop.bare_column(), _const(pattern.value)])+ return _call("notILike", [prop.bare_column(), _const(pattern.value)])++ def _optimize_materialized_like(self, node: ast.CompareOperation) -> ast.Expr | None:+ if node.op not in (ast.CompareOperationOp.Like, ast.CompareOperationOp.NotLike):+ return None+ prop = self._materialized_string_property(node.left)+ pattern = _string_pattern_constant(node.right)+ if prop is None or pattern is None:+ return None++ is_like = node.op == ast.CompareOperationOp.Like+ if prop.source.is_nullable:+ if is_like:+ return _call("and", [_call("like", [prop.bare_column(), _const(pattern.value)]), prop.is_not_null()])+ return _call("ifNull", [_call("notLike", [prop.bare_column(), _const(pattern.value)]), _const(True)])++ if any(like_matches(cast(str, pattern.value), s) for s in MAT_COL_NULL_SENTINELS):+ return None+ if is_like:+ return _call("like", [prop.bare_column(), _const(pattern.value)])+ return _call("notLike", [prop.bare_column(), _const(pattern.value)])++ def _optimize_materialized_in(self, node: ast.CompareOperation) -> ast.Expr | None:+ if node.op not in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):+ return None+ prop = self._materialized_property_for_op(node.left)+ if prop is None or self._is_ai_column(prop.source):+ return None++ values = self._extract_string_constants(node.right)+ if not values:+ return None++ if prop.source.is_nullable:+ if node.op == ast.CompareOperationOp.In:+ # ClickHouse's transform_null_in makes in() hard to index; flip to has([...], col) (safe: NULL already excluded).+ array = ast.Array(exprs=[_const(v) for v in values])+ return _call("and", [_call("has", [array, prop.bare_column()]), prop.is_not_null()])+ tup = ast.Tuple(exprs=[_const(v) for v in values])+ return _call("ifNull", [_call("notIn", [prop.bare_column(), tup]), _const(True)])++ # non-nullable: bail if any value is a stored sentinel.+ if any(v in MAT_COL_NULL_SENTINELS for v in values):+ return None+ if node.op == ast.CompareOperationOp.In:+ array = ast.Array(exprs=[_const(v) for v in values])+ return _call("has", [array, prop.bare_column()])+ tup = ast.Tuple(exprs=[_const(v) for v in values])+ return _call("notIn", [prop.bare_column(), tup])++ def _optimize_materialized_lower_in(self, node: ast.CompareOperation) -> ast.Expr | None:+ if node.op not in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):+ return None+ # HogQL `lower` is case-insensitive on the Call name.+ if not (isinstance(node.left, ast.Call) and node.left.name.lower() == "lower" and len(node.left.args) == 1):+ return None+ prop = self._materialized_string_property(node.left.args[0])+ if prop is None or not (prop.source.has_bloom_filter_lower_index or prop.source.has_ngram_lower_index):+ return None+ if self._is_ai_column(prop.source):+ return None++ values = self._extract_lower_in_values(node.right)+ if not values:+ return None++ # Bail if a value could collide with a stored NULL sentinel.+ null_sentinels = [""] if prop.source.is_nullable else MAT_COL_NULL_SENTINELS+ if any(v in null_sentinels for v in values):+ return None++ if prop.source.is_nullable:+ indexed: ast.Expr = _lower(_coalesce_empty(prop.bare_column()))+ else:+ indexed = _lower(prop.bare_column())++ if node.op == ast.CompareOperationOp.In:+ return _call("has", [ast.Array(exprs=[_const(v) for v in values]), indexed])+ return _call("notIn", [indexed, ast.Tuple(exprs=[_const(v) for v in values])])++ @staticmethod+ def _extract_string_constants(node: ast.Expr) -> list[str] | None:+ """A list of string values from an IN right-hand side (single constant or tuple/array of constants)."""+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return [node.value]+ if isinstance(node, (ast.Tuple, ast.Array)):+ values: list[str] = []+ for value in node.exprs:+ if isinstance(value, ast.Constant) and isinstance(value.value, str):+ values.append(value.value)+ else:+ return None+ return values or None+ return None++ @staticmethod+ def _extract_lower_in_values(node: ast.Expr) -> list[str] | None:+ """Like _extract_string_constants but also accepts a constant list (from a `{placeholder}`)."""+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return [node.value]+ if isinstance(node, ast.Constant) and isinstance(node.value, (list, tuple)):+ if not all(isinstance(value, str) for value in node.value):+ return None+ return list(node.value) or None+ if isinstance(node, (ast.Tuple, ast.Array)):+ values: list[str] = []+ for value in node.exprs:+ if isinstance(value, ast.Constant) and isinstance(value.value, str):+ values.append(value.value)+ else:+ return None+ return values or None+ return None+++def clickhouse_property_resolution(node: _T_AST, context: HogQLContext) -> _T_AST:+ """Rewrite every backed lowered `PropertyAccess` (and comparison over it) to read its backing column.++ ClickHouse only. Expects a resolved, swapped, lowered AST, and runs right after `lower_property_access` in the+ ClickHouse print pipeline (see `prepare_ast_for_printing`).+ """+ return cast(_T_AST, ClickHousePropertyResolver(context).visit(node))diff --git a/posthog/hogql/transforms/events_predicate_pushdown.py b/posthog/hogql/transforms/events_predicate_pushdown.pyindex 679f346985db..69315aee8f7a 100644--- a/posthog/hogql/transforms/events_predicate_pushdown.py+++ b/posthog/hogql/transforms/events_predicate_pushdown.py@@ -1,23 +1,54 @@+"""Events predicate pushdown.++Wraps a `FROM events <JOIN…> WHERE p LIMIT n` query's events scan in a pre-filtering subquery so the events table is+read once, filtered and `LIMIT`-bounded, before the joins fan out:++ FROM events <JOIN…> WHERE <p> LIMIT n+ ->+ FROM (SELECT <needed cols> FROM events WHERE <pushable p> LIMIT n) AS events <JOIN…> WHERE <residual p>++It runs *after* logical lowering and *before* the ClickHouse physical passes (see `prepare_ast_for_printing`), so it+operates on the dialect-neutral logical form: property reads are `PropertyAccess`, not yet materialized columns. Two+pieces move events work into the subquery:++1. The pushable predicates (`EventsPredicatePushdownExtractor`) move into the subquery WHERE verbatim — they already+ reference the real events table, so the physical pass optimizes them (materialized columns, skip indexes) in place.+2. Everything the *outer* query still references is handled by `EventsSubexprHoister`: each maximal subexpression that+ depends only on the events table is projected into the subquery and replaced by a reference to that column. The+ physical pass then resolves any `PropertyAccess` / property-group form inside the subquery. Pushdown itself never+ inspects physical columns or special-cases particular functions.++It is a pure optimization: any unexpected error leaves the query untouched (run flat), and every rewrite is+result-equivalent.++Two things are built by hand here, on purpose:++- **The subquery's types.** `_build_subquery` constructs the subquery's `SelectQueryType` directly rather than calling+ `resolve_types`. It has to: `resolve_types` runs before lowering, has no handling for `PropertyAccess`, and clones+ with `clear_types=True` — so re-resolving a subquery that already holds lowered `PropertyAccess` projections would+ wipe their types and break nullability and printing downstream. Teaching the resolver about lowered nodes would cross+ a layering boundary, so the types are assembled here instead.+- **Hoisted-column nullability.** The printer reads a hoisted column's nullability from the subquery's projected column+ type, not as a blanket-nullable subquery column. That is what lets a join key be hoisted like any other column: it+ wraps in `ifNull(...)` only when the value is genuinely nullable.+"""+from typing import castimport structlog-from posthog.schema import HogQLQueryModifiers, PropertyGroupsMode+from posthog.schema import HogQLQueryModifiersfrom posthog.hogql import astfrom posthog.hogql.base import _T_ASTfrom posthog.hogql.constants import LimitContext, get_max_limit_for_contextfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.models import DatabaseField, FieldTraverser+from posthog.hogql.database.models import DatabaseFieldfrom posthog.hogql.database.schema.events import EventsTablefrom posthog.hogql.database.schema.util.where_clause_extractor import EventsPredicatePushdownExtractorfrom posthog.hogql.functions.mapping import find_hogql_aggregation-from posthog.hogql.printer.base import resolve_field_typefrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr-from posthog.clickhouse.materialized_columns import TablesWithMaterializedColumns, get_materialized_column_for_property-from posthog.clickhouse.property_groups import property_groups-from posthog.models.property import PropertyName, TableColumnfrom posthog.settings import TESTlogger = structlog.get_logger(__name__)@@ -42,7 +73,7 @@ def apply_events_predicate_pushdown(node: _T_AST,context: HogQLContext,) -> _T_AST:- """Apply predicate pushdown to events tables with lazy joins. Mutates the AST in place; returns it."""+ """Apply predicate pushdown to eligible `FROM events … JOIN …` queries. Mutates the AST in place; returns it."""top_level_select_ids = _printer_top_level_select_ids(node)EventsPredicatePushdownTransform(context=context, top_level_select_ids=top_level_select_ids).visit(node)return node@@ -68,238 +99,224 @@ class SelectAliasInliner(CloningVisitor):return super().visit_field(node)-class LazyTypeDetector(TraversingVisitor):- """Detects any unresolved LazyJoinType / LazyTableType; pushdown bails if found (the subquery won't have those joins)."""-- def __init__(self):- super().__init__()- self.found_lazy_type = False-- def visit_field(self, node: ast.Field):- super().visit_field(node)- if node.type is not None and self._check_type_for_lazy(node.type):- self.found_lazy_type = True-- def visit_join_expr(self, node: ast.JoinExpr):- super().visit_join_expr(node)- if node.type is not None and self._check_type_for_lazy(node.type):- self.found_lazy_type = True+class _StructuralNormalizer(CloningVisitor):+ """Builds the hoister's structural-identity clone of an events-only expression: type- and location-stripped,+ with every events column leaf rewritten to its resolved database column name. After lowering, two reads off+ different blobs can carry the same chain (`properties` vs poe's `person_properties`, where the blob identity+ lives only in the type), so the chain alone would wrongly identify them; the database name disambiguates.+ Sets `failed` for an unresolvable column so the caller declines."""- def visit_alias(self, node: ast.Alias):- super().visit_alias(node)- if node.type is not None and self._check_type_for_lazy(node.type):- self.found_lazy_type = True+ def __init__(self, hoister: "EventsSubexprHoister"):+ super().__init__(clear_types=True, clear_locations=True)+ self.hoister = hoister+ self.failed = False- def _check_type_for_lazy(self, field_type: ast.Type) -> bool:- if isinstance(field_type, ast.LazyJoinType):- return True- if isinstance(field_type, ast.LazyTableType):- return True- if isinstance(field_type, ast.FieldType):- return self._check_table_type_for_lazy(field_type.table_type)- if isinstance(field_type, ast.PropertyType):- return self._check_type_for_lazy(field_type.field_type)- if isinstance(field_type, ast.SelectQueryAliasType):- if field_type.select_query_type is not None:- return self._check_select_query_type_for_lazy(field_type.select_query_type)- return False-- def _check_table_type_for_lazy(self, table_type: ast.Type | None) -> bool:- if table_type is None:- return False- if isinstance(table_type, ast.LazyJoinType):- return True- if isinstance(table_type, ast.LazyTableType):- return True- if isinstance(table_type, ast.TableAliasType):- return self._check_table_type_for_lazy(table_type.table_type)- if isinstance(table_type, ast.SelectQueryAliasType):- if table_type.select_query_type is not None:- return self._check_select_query_type_for_lazy(table_type.select_query_type)- return False-- def _check_select_query_type_for_lazy(self, query_type: ast.SelectQueryType | ast.SelectSetQueryType) -> bool:- if isinstance(query_type, ast.SelectSetQueryType):- return False- for table_type in query_type.tables.values():- if self._check_table_type_for_lazy(table_type):- return True- for table_type in query_type.anonymous_tables:- if self._check_table_type_for_lazy(table_type):- return True- return False+ def visit_field(self, node: ast.Field) -> ast.Field:+ if self.hoister._is_target_field(node.type):+ assert isinstance(node.type, ast.FieldType)+ name = self.hoister._database_column_name(node.type)+ if name is None:+ self.failed = True+ return ast.Field(chain=[name or ""])+ return cast(ast.Field, super().visit_field(node))-class EventsFieldCollector(TraversingVisitor):- """Collects the direct events columns a query references (with resolved FieldTypes, so the subquery can be- built without re-running resolve_types) and flags non-direct fields / lazy joins that block pushdown."""+class _EventsOnlyScan(TraversingVisitor):+ """Classifies the leaf references in an expression so the hoister can decide whether the whole subtree depends+ only on the target events table. Counts target-table vs foreign field references (a lazy-join or any other+ non-events ref is simply foreign) and flags nested subqueries."""- def __init__(self, target_table: ast.TableType | ast.TableAliasType, context: HogQLContext):+ def __init__(self, hoister: "EventsSubexprHoister"):super().__init__()- self.target_table = target_table- self.context = context- self.collected_fields: dict[str, ast.FieldType] = {}- self.materialized_columns: set[str] = set()- self._group_covered_field_ids: set[int] = set()- self.has_non_direct_fields = False+ self.hoister = hoister+ self.target_refs = 0+ self.foreign_refs = 0+ self.has_subquery = False- def visit_field(self, node: ast.Field):+ def visit_field(self, node: ast.Field) -> None:super().visit_field(node)+ if self.hoister._is_target_field(node.type):+ self.target_refs += 1+ else:+ self.foreign_refs += 1- # Already exposed via its property-group Map column (see visit_call), so skip the redundant blob.- if id(node) in self._group_covered_field_ids:- return-- field_type = node.type+ def visit_select_query(self, node: ast.SelectQuery) -> None:+ self.has_subquery = True- # events.properties.$foo: unwrap to the base column so we collect/re-type it for the inner table.- property_type = field_type if isinstance(field_type, ast.PropertyType) else None- if property_type is not None:- field_type = property_type.field_type+ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:+ self.has_subquery = True- if isinstance(field_type, ast.FieldType):- table_type = field_type.table_type- if self._type_references_lazy_join(table_type):- self.has_non_direct_fields = True- return+class EventsSubexprHoister(CloningVisitor):+ """Rewrites an events query's outer expressions so the work that depends only on the events table moves into the+ pre-filtering subquery.- if self._matches_target_table(table_type):- # Expose the physical mat/dmat/group column the printer reads, not the slow `properties` blob;- # falls through to the blob if the property isn't materialized.- if property_type is not None and self._collect_materialized_column(property_type, field_type):- return+ For each *maximal* subexpression that references only the target events table (its columns and property reads)+ plus constants — a property value read, `JSONHas(properties, k)`, `match(uuid, …)`, `upper(properties.x)`, … — the+ whole subexpression is projected into the subquery under a stable name and the outer occurrence becomes a+ reference to that column. The ClickHouse physical pass, running afterwards, resolves any `PropertyAccess` /+ property-group form *inside the subquery*; pushdown itself never inspects physical columns, mimics the events+ schema, or special-cases particular functions — `JSONHas` is just one events-only expression among many.- db_column_name = self._get_database_column_name(field_type)- if db_column_name:- self.collected_fields[db_column_name] = field_type- else:- self.has_non_direct_fields = True+ A hoisted reference carries the projected column's real nullability (see the module docstring), so a non-nullable+ value stays unwrapped and can serve as a join key, while a nullable property key still wraps correctly.- def visit_call(self, node: ast.Call):- # Expose the property-group Map column for an OPTIMIZED JSONHas(properties, 'k') before recursing, so- # visit_field can skip the redundant blob. Mirrors ClickHousePrinter._get_optimized_property_group_call.- group_column = self._optimized_json_has_group_column(node)- if group_column is not None:- self.materialized_columns.add(group_column)- covered = node.args[0]- while isinstance(covered, ast.Alias):- covered = covered.expr- if isinstance(covered, ast.Field):- self._group_covered_field_ids.add(id(covered))- super().visit_call(node)-- def _optimized_json_has_group_column(self, node: ast.Call) -> str | None:- """The property-group Map column an OPTIMIZED `JSONHas(<events properties>, <const>)` reads, else None."""- if self.context.modifiers.propertyGroupsMode != PropertyGroupsMode.OPTIMIZED:- return None- if node.name != "JSONHas" or len(node.args) != 2 or not isinstance(node.args[1], ast.Constant):- return None- field_type = resolve_field_type(node.args[0])- if not isinstance(field_type, ast.FieldType) or not self._matches_target_table(field_type.table_type):- return None- resolved = self._resolve_events_table_and_column(field_type)- if resolved is None:- return None- table_name, field_name = resolved- for group_column in property_groups.get_property_group_columns(table_name, field_name, str(node.args[1].value)):- return group_column- return None+ Sets `blocked` if a referenced leaf is an unresolvable column, so the caller declines."""- def _resolve_events_table_and_column(self, field_type: ast.FieldType) -> tuple[str, str] | None:- """(events table name, db column name) for a direct column on the target events table, else None."""- field_name = self._get_database_column_name(field_type)- if field_name is None:+ def __init__(+ self,+ target_table: ast.TableType | ast.TableAliasType,+ subquery_ref: ast.SelectQueryAliasType,+ context: HogQLContext,+ ):+ super().__init__(clear_types=False)+ self.target_table = target_table+ self.subquery_ref = subquery_ref+ # Pushdown always builds the ref over a SelectQueryType (never a set query); narrow it for column bookkeeping.+ assert isinstance(subquery_ref.select_query_type, ast.SelectQueryType)+ self.subquery_type = subquery_ref.select_query_type+ self.context = context+ self.projections: dict[str, ast.Expr] = {}+ self.column_types: dict[str, ast.Type] = {}+ self.blocked = False+ self._counter = 0+ self._structures: dict[str, ast.Expr] = {}++ def visit(self, node: ast.AST | None) -> ast.AST:+ # Aliases are transparent: recurse so the inner subexpression is hoisted while the alias — and the output+ # name it carries — stays in the outer query.+ if not isinstance(node, ast.Expr) or isinstance(node, ast.Alias):+ return super().visit(node)++ # The maximal events-only subexpression — a direct column, a property read, or an events-only join key — is+ # projected whole into the subquery and read back as one column. A join key needs no special handling; its+ # nullability rides the projected column's type.+ if self._is_hoistable(node):+ name = self._intern(node)+ if name is not None:+ return ast.Field(chain=[name], type=ast.FieldType(name=name, table_type=self.subquery_ref))++ return super().visit(node)++ def visit_alias(self, node: ast.Alias) -> ast.Alias:+ # The resolver wraps a bare column reference in an alias whose `FieldAliasType` carries the events column's+ # `FieldType` again. Hoisting only the inner expression would leave that wrapper stale, and downstream+ # consumers that resolve through it (`resolve_field_type`) would treat the outer reference as still reading+ # the real events table. Re-point the wrapper at the rewritten expression's type (mirrors lowering's+ # `visit_alias`).+ new_node = cast(ast.Alias, super().visit_alias(node))+ unwrapped: ast.Type | None = new_node.type+ while isinstance(unwrapped, ast.FieldAliasType):+ unwrapped = unwrapped.type+ if (+ isinstance(new_node.type, ast.FieldAliasType)+ and self._is_target_field(unwrapped)+ and new_node.expr.type is not None+ ):+ new_node.type = ast.FieldAliasType(alias=new_node.type.alias, type=new_node.expr.type)+ return new_node++ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ # A nested subquery is its own scope: its events references resolve against its own FROM (even when that is+ # the same events table), so rewriting them to read the outer pre-filtering subquery would cross scopes.+ return cast(ast.SelectQuery, clone_expr(node, clear_types=False))++ def visit_select_set_query(self, node: ast.SelectSetQuery) -> ast.SelectSetQuery:+ return cast(ast.SelectSetQuery, clone_expr(node, clear_types=False))++ def _intern(self, expr: ast.Expr) -> str | None:+ """Record a subquery projection for `expr` and return the column name to reference it by. Structurally+ identical reads share one projection. The preferred name is *not* injective — `properties.a[1]` (array index)+ and `properties.a['1']` (object key) both prefer `properties__a__1`, and `properties.a.b` collides with+ `properties['a__b']` — so a structurally different read whose preferred name is already taken gets a fresh+ synthetic column instead; collapsing the two would silently return the first read's value for the second.+ Returns None (setting `blocked`) for an unresolvable column."""+ # Structural identity compares normalized type-stripped clones (type objects can be cyclic — table types+ # embed query types — so comparing nodes with types attached is unsafe; see `_StructuralNormalizer` for the+ # column-name normalization that disambiguates reads off different blobs).+ normalizer = _StructuralNormalizer(self)+ structure = cast(ast.Expr, normalizer.visit(expr))+ if normalizer.failed:+ self.blocked = Truereturn None- table = field_type.table_type- while isinstance(table, (ast.TableAliasType, ast.VirtualTableType)):- table = table.table_type- if not isinstance(table, ast.TableType):+ for existing_name, existing_structure in self._structures.items():+ if existing_structure == structure:+ return existing_name+ name = self._preferred_name(expr)+ if name is None:+ self.blocked = Truereturn None- return table.table.to_printed_hogql(), field_name-- def _collect_materialized_column(self, property_type: ast.PropertyType, base_field_type: ast.FieldType) -> bool:- """Record the physical column the printer reads for this event property; False (collect the raw blob) when none."""- if self.context.modifiers.materializationMode == "disabled" or not property_type.chain:- return False- resolved = self._resolve_events_table_and_column(base_field_type)- if resolved is None:- return False- table_name, field_name = resolved- column = self._materialized_column_for_property(table_name, field_name, str(property_type.chain[0]))- if column is None:- return False- self.materialized_columns.add(column)- return True-- def _materialized_column_for_property(self, table_name: str, field_name: str, property_name: str) -> str | None:- """The single physical column the printer reads for events.<field>.<property>, or None. Mirrors- BasePrinter._get_all_materialized_property_sources' priority (static column, dmat slot, first group column)."""- materialized_column = get_materialized_column_for_property(- cast(TablesWithMaterializedColumns, table_name),- cast(TableColumn, field_name),- cast(PropertyName, property_name),- )- if materialized_column is not None:- return materialized_column.name-- if self.context.property_swapper is not None and table_name == "events" and field_name == "properties":- prop_info = self.context.property_swapper.event_properties.get(property_name)- if prop_info and prop_info.get("dmat"):- return prop_info["dmat"]-- if self.context.modifiers.propertyGroupsMode in (PropertyGroupsMode.ENABLED, PropertyGroupsMode.OPTIMIZED):- for group_column in property_groups.get_property_group_columns(table_name, field_name, property_name):- return group_column-- return None-- def _type_references_lazy_join(self, table_type: ast.Type | None) -> bool:- if table_type is None:- return False- if isinstance(table_type, ast.LazyJoinType):- return True- if isinstance(table_type, ast.TableAliasType):- return self._type_references_lazy_join(table_type.table_type)- if isinstance(table_type, ast.LazyTableType):- return True- if isinstance(table_type, ast.VirtualTableType):- return self._type_references_lazy_join(table_type.table_type)- return False-- def _get_database_column_name(self, field_type: ast.FieldType) -> str | None:+ if name in self.projections:+ name = self._synthetic_name()+ value_type: ast.Type = expr.type or ast.UnknownType()+ self.projections[name] = clone_expr(expr, clear_types=False)+ self._structures[name] = structure+ self.column_types[name] = value_type+ self.subquery_type.columns[name] = value_type+ return name++ def _preferred_name(self, node: ast.Expr) -> str | None:+ # A property read's name is its source blob column joined with its key path, so `properties.x` and the person+ # blob's `person_properties.x` hoist to separate columns instead of colliding on the bare key `x` (which would+ # read the wrong blob for one of them). A direct column uses its database name; any other events-only+ # subexpression a synthetic internal name (its outer output name rides its alias).+ if isinstance(node, ast.PropertyAccess):+ blob = self._database_column_name(node.expr.type) if isinstance(node.expr.type, ast.FieldType) else None+ if blob is None:+ return None+ return "__".join([blob, *(str(key) for key in node.keys)])+ if isinstance(node, ast.Field) and isinstance(node.type, ast.FieldType):+ return self._database_column_name(node.type)+ return self._synthetic_name()++ def _synthetic_name(self) -> str:+ name = f"__pd_expr_{self._counter}"+ self._counter += 1+ return name++ def _is_target_field(self, node_type: ast.Type | None) -> bool:+ return isinstance(node_type, ast.FieldType) and self._matches_target_table(node_type.table_type)++ def _is_hoistable(self, node: ast.Expr) -> bool:+ """True if `node` depends only on the target events table (its columns / property reads) plus constants — no+ joined-table, lazy, or other foreign reference and no nested subquery — and touches the target at least once+ (so we never project a pure constant)."""+ scan = _EventsOnlyScan(self)+ scan.visit(node)+ return scan.target_refs > 0 and scan.foreign_refs == 0 and not scan.has_subquery++ def _database_column_name(self, field_type: ast.FieldType) -> str | None:try:resolved = field_type.resolve_database_field(self.context)- if isinstance(resolved, FieldTraverser):- return Noneif isinstance(resolved, DatabaseField):return resolved.namereturn Noneexcept Exception as err:- # Fail-safe: treat any resolution failure as non-direct and decline; debug-logged so a resolver- # regression silently disabling pushdown stays visible.+ # Fail-safe: an unresolvable column blocks pushdown rather than risking a wrong subquery; debug-logged so+ # a resolver regression silently disabling pushdown stays visible.logger.debug("events_predicate_pushdown_field_resolution_failed", error=str(err))return Nonedef _matches_target_table(self, table_type: ast.Type | None) -> bool:- if table_type is None:- return False-- unwrapped: ast.Type = table_type- if isinstance(unwrapped, ast.TableAliasType):- unwrapped = unwrapped.table_type- if isinstance(unwrapped, ast.VirtualTableType):- unwrapped = unwrapped.table_type- if isinstance(unwrapped, ast.TableAliasType):+ # Match the specific FROM table, not the EventsTable schema object: a self-join (`events a JOIN events b`)+ # shares one schema object across both sides, so rewriting by object identity would collapse `b`'s columns+ # onto the subquery too. Discriminate by alias (object identity is unreliable — the pipeline's CloningVisitors+ # may have re-instantiated the types since the FROM was captured). Only POE virtual layers are peeled.+ unwrapped: ast.Type | None = table_type+ while isinstance(unwrapped, ast.VirtualTableType):unwrapped = unwrapped.table_type- target: ast.Type = self.target_table+ target = self.target_tableif isinstance(target, ast.TableAliasType):- target = target.table_type-- if isinstance(unwrapped, ast.TableType) and isinstance(target, ast.TableType):- return unwrapped.table is target.table- return table_type is self.target_table or unwrapped is target+ return (+ isinstance(unwrapped, ast.TableAliasType)+ and unwrapped.alias == target.alias+ and isinstance(unwrapped.table_type, ast.TableType)+ and isinstance(target.table_type, ast.TableType)+ and unwrapped.table_type.table is target.table_type.table+ )+ # Unaliased FROM: match the bare events TableType only, never a column reached through some join alias.+ return isinstance(unwrapped, ast.TableType) and unwrapped.table is target.tableclass _ShortCircuitBlockerFinder(TraversingVisitor):@@ -331,11 +348,13 @@ class EventsPredicatePushdownTransform(TraversingVisitor):"""Pushes events WHERE/PREWHERE predicates into a pre-filtering subquery:`FROM events` -> `FROM (SELECT <needed cols> FROM events WHERE <predicates>) AS events`.- Runs after resolve_lazy_tables and applies bottom-up so nested `FROM events` subqueries benefit too."""+ Runs after logical lowering (so property reads are PropertyAccess) and before the ClickHouse physical passes,+ applying bottom-up so nested `FROM events` subqueries benefit too."""- # Join types across which moving an events PREDICATE is result-safe (they preserve the events/left side).- # Broader than _all_joins_preserve_every_row (LEFT only): INNER / CROSS are predicate-safe but can drop an- # events row, so they pass here yet decline at _safe_inner_limit (the single-rule gate always needs it).+ # Join types across which moving an events PREDICATE is result-safe (they preserve the events/left side). This is+ # broader than the all-rows-preserved check (`_all_joins_preserve_every_row`, LEFT only): INNER / CROSS are+ # predicate-safe but can drop an events row, so they pass here yet are rejected when deciding whether to also push+ # the LIMIT (`_safe_inner_limit`)._SAFE_JOIN_TYPES = {"JOIN", "INNER JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "CROSS JOIN"}def __init__(@@ -365,6 +384,15 @@ class EventsPredicatePushdownTransform(TraversingVisitor):"""Apply predicate pushdown to an eligible query. Returns a decline reason, or None if applied."""assert node.select_from is not None+ # The hoister rewrites events references in the select list, residual predicates, HAVING/QUALIFY, and join+ # constraints — but the printer also prints column-CTE bodies and WINDOW clauses. An events reference there+ # would survive un-rewritten and point at a column the pre-filtering subquery doesn't project (ClickHouse:+ # unknown identifier), so decline those shapes outright.+ if node.ctes:+ return "has_ctes"+ if node.window_exprs:+ return "has_window_exprs"+joined_aliases = self._collect_joined_aliases(node)if not joined_aliases:return "no_safe_joined_aliases"@@ -373,12 +401,6 @@ class EventsPredicatePushdownTransform(TraversingVisitor):if not isinstance(events_table_type, (ast.TableType, ast.TableAliasType)):return "from_not_table_type"- # Collect needed columns before extracting/mutating predicates, so we can bail before touching- # node.where and never drop a pushable predicate.- collector = self._collect_needed_columns(node, events_table_type)- if collector is None or (not collector.collected_fields and not collector.materialized_columns):- return "no_collectable_columns"-# Classify a WHERE field that resolves to an alias by what the alias references (e.g. `f(session.x) AS# event` must not be pushed by name).select_aliases = {expr.alias: expr.expr for expr in node.select if isinstance(expr, ast.Alias)}@@ -418,36 +440,48 @@ class EventsPredicatePushdownTransform(TraversingVisitor):if inner_limit is None:return "no_short_circuitable_limit"- # Build the subquery from the outer query's resolved types. The inner events table keeps the outer- # alias so the pushed predicates resolve against it; the printer injects the per-table team_id guard.- events_subquery = self._build_typed_subquery(- collector.collected_fields,- collector.materialized_columns,- events_table_type,- inner_where,- inner_prewhere,- alias=node.select_from.alias,- limit=inner_limit,+ # Hoist the events leaves the outer query still references into the pre-filtering subquery, rewriting each+ # outer reference to read the subquery column. Build the subquery's type/ref first so the rewritten+ # references can point at it; nothing on `node` is mutated until every check below passes.+ new_alias = node.select_from.alias or "events"+ subquery_type = ast.SelectQueryType(columns={}, tables={new_alias: events_table_type})+ subquery_ref = ast.SelectQueryAliasType(alias=new_alias, select_query_type=subquery_type)+ hoister = EventsSubexprHoister(events_table_type, subquery_ref, self.context)++ new_select = [cast(ast.Expr, hoister.visit(column)) for column in node.select]+ new_where = cast(ast.Expr, hoister.visit(new_where)) if new_where is not None else None+ new_having = cast(ast.Expr, hoister.visit(node.having)) if node.having is not None else None+ new_qualify = cast(ast.Expr, hoister.visit(node.qualify)) if node.qualify is not None else None+ rewritten_join_constraints: list[tuple[ast.JoinExpr, ast.Expr]] = []+ join = node.select_from.next_join+ while join is not None:+ if join.constraint is not None and join.constraint.expr is not None:+ rewritten_join_constraints.append((join, cast(ast.Expr, hoister.visit(join.constraint.expr))))+ join = join.next_join++ if hoister.blocked:+ return "non_direct_outer_reference"+ if not hoister.projections:+ return "no_collectable_columns"++ events_subquery = self._build_subquery(+ hoister, events_table_type, inner_where, inner_prewhere, alias=node.select_from.alias, limit=inner_limit)if events_subquery is None:return "subquery_build_failed"- subquery_type = events_subquery.type- assert subquery_type is not None- # Commit: drop the pushed predicates and swap the events table for the subquery, keeping the alias.+ # Commit: install the rewritten outer expressions and swap the events table for the subquery.+ node.select = new_selectnode.where = new_where+ node.having = new_having+ node.qualify = new_qualify+ for join_expr, rewritten in rewritten_join_constraints:+ assert join_expr.constraint is not None+ join_expr.constraint.expr = rewrittennode.prewhere = new_prewhere- original_alias = node.select_from.alias- new_alias = original_alias or "events"node.select_from.table = events_subquerynode.select_from.alias = new_alias-- # Outer field refs keep their original types and resolve against the alias by name.- # TODO: re-point outer field refs so query metadata reflects the rewrite.- node.select_from.type = ast.SelectQueryAliasType(- alias=new_alias,- select_query_type=subquery_type,- )+ node.select_from.type = subquery_refreturn Nonedef _should_apply_pushdown(self, node: ast.SelectQuery) -> bool:@@ -510,6 +544,10 @@ class EventsPredicatePushdownTransform(TraversingVisitor):or node.array_join_list is not Noneor node.limit_with_tiesor node.limit_percent+ # A non-aggregate HAVING / QUALIFY drops rows after the join, exactly like a residual predicate: the+ # first `offset + limit` events no longer cover the outer slice, so a pushed LIMIT could under-produce.+ or node.having is not None+ or node.qualify is not None):return Noneif residual_where is not None or residual_prewhere is not None:@@ -560,23 +598,6 @@ class EventsPredicatePushdownTransform(TraversingVisitor):join = join.next_joinreturn aliases- def _collect_needed_columns(- self, node: ast.SelectQuery, events_table_type: ast.TableType | ast.TableAliasType- ) -> EventsFieldCollector | None:- """Collect the events columns the outer query references; None if it can't be pushed (lazy or non-direct fields)."""- lazy_detector = LazyTypeDetector()- lazy_detector.visit(node)- if lazy_detector.found_lazy_type:- return None-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- if collector.has_non_direct_fields:- return None-- return collector-def _prepare_inner_predicate(self, expr: ast.Expr | None, select_aliases: dict[str, ast.Expr]) -> ast.Expr | None:"""Ready a pushed predicate for the inner subquery (inline SELECT-alias refs, clone), or None if there is none."""if expr is None:@@ -584,64 +605,37 @@ class EventsPredicatePushdownTransform(TraversingVisitor):expr = SelectAliasInliner(select_aliases).visit(expr)return clone_expr(expr)- def _build_typed_subquery(+ def _build_subquery(self,- collected_fields: dict[str, ast.FieldType],- materialized_columns: set[str],+ hoister: EventsSubexprHoister,events_table_type: ast.TableType | ast.TableAliasType,where_clause: ast.Expr | None,- prewhere_clause: ast.Expr | None = None,- alias: str | None = None,- limit: ast.Constant | None = None,+ prewhere_clause: ast.Expr | None,+ alias: str | None,+ limit: ast.Constant | None,) -> ast.SelectQuery | None:- """Build the subquery from the outer query's resolved FieldTypes (avoiding resolve_types, which might- re-resolve lazy joins). Keeps the outer events alias so pushed predicates and the SELECT list match."""+ """Build `SELECT <hoisted projections> FROM events WHERE <pushed predicates> LIMIT n`.++ The hoisted projections and the pushed predicates already reference the original events table type, so the+ subquery reuses it directly as its FROM — no schema mimicry, no synthetic materialized columns. The ClickHouse+ physical pass rewrites the `PropertyAccess` projections to their materialized columns afterwards."""base_table_type: ast.Type = events_table_typeif isinstance(base_table_type, ast.TableAliasType):base_table_type = base_table_type.table_typeif not isinstance(base_table_type, ast.TableType):return None- inner_table_type = self._inner_table_type_with_materialized_columns(base_table_type, materialized_columns)- ref_table_type: ast.TableType | ast.TableAliasType = (- ast.TableAliasType(alias=alias, table_type=inner_table_type) if alias else inner_table_type- )+ events_field = ast.Field(chain=[base_table_type.table.to_printed_hogql()], type=base_table_type)+ select_from = ast.JoinExpr(table=events_field, alias=alias, type=events_table_type)- # One aliased Field per column, so names survive even if PropertySwapper rewrites the inner expr.- select_fields: list[ast.Expr] = []- columns_in_scope: dict[str, ast.Type] = {}-- for col_name in sorted(collected_fields.keys()):- original_field_type = collected_fields[col_name]-- if isinstance(original_field_type.table_type, ast.VirtualTableType):- virtual_table_type = ast.VirtualTableType(- table_type=ref_table_type,- field=original_field_type.table_type.field,- virtual_table=original_field_type.table_type.virtual_table,- )- field_type = ast.FieldType(name=original_field_type.name, table_type=virtual_table_type)- else:- field_type = ast.FieldType(name=col_name, table_type=ref_table_type)-- field_node = ast.Field(chain=[col_name], type=field_type)- alias_node = ast.Alias(alias=col_name, expr=field_node, type=field_type)- select_fields.append(alias_node)- columns_in_scope[col_name] = field_type-- # Expose the raw physical mat/dmat/group columns so the printer's outer references resolve against the- # subquery alias; the outer query re-applies the property semantics.- for col_name in sorted(materialized_columns):- if col_name in columns_in_scope:- continue- field_type = ast.FieldType(name=col_name, table_type=ref_table_type)- field_node = ast.Field(chain=[col_name], type=field_type)- select_fields.append(ast.Alias(alias=col_name, expr=field_node, type=field_type))- columns_in_scope[col_name] = field_type-- events_field = ast.Field(chain=["events"], type=inner_table_type)- select_from = ast.JoinExpr(table=events_field, alias=alias, type=ref_table_type)- select_query_type = ast.SelectQueryType(columns=columns_in_scope, tables={alias or "events": ref_table_type})+ select_fields: list[ast.Expr] = [+ ast.Alias(+ alias=name,+ expr=hoister.projections[name],+ type=ast.FieldAliasType(alias=name, type=hoister.column_types[name]),+ )+ for name in sorted(hoister.projections)+ ]return ast.SelectQuery(select=select_fields,@@ -649,22 +643,5 @@ class EventsPredicatePushdownTransform(TraversingVisitor):where=where_clause,prewhere=prewhere_clause,limit=limit,- type=select_query_type,- )-- def _inner_table_type_with_materialized_columns(- self, base_table_type: ast.TableType, materialized_columns: set[str]- ) -> ast.TableType:- """Inner events table type augmented with synthetic DatabaseFields for the materialized columns (physical- ClickHouse columns, not HogQL schema fields). Uses a copy; the shared table object is never mutated."""- synthetic_fields = {- column: DatabaseField(name=column)- for column in materialized_columns- if not base_table_type.table.has_field(column)- }- if not synthetic_fields:- return base_table_type- augmented_table = base_table_type.table.model_copy(- update={"fields": {**base_table_type.table.fields, **synthetic_fields}}+ type=hoister.subquery_type,)- return ast.TableType(table=augmented_table)diff --git a/posthog/hogql/transforms/logical_property_lowering.py b/posthog/hogql/transforms/logical_property_lowering.pynew file mode 100644index 000000000000..ed77f98a845b--- /dev/null+++ b/posthog/hogql/transforms/logical_property_lowering.py@@ -0,0 +1,80 @@+"""First pass: turn every `properties.x` read into a plain `PropertyAccess` node.++A property read starts life as a `Field` tagged with a `PropertyType` ("this is a property"). This pass rewrites each one+into a `PropertyAccess` — "read this key path out of this JSON blob". It makes no decision about *how* to read the+property and never looks at materialized columns; that keeps it simple and the same for every database backend. After it+runs, each printer just renders the node in its own JSON syntax — the property is no longer something the printer has to+figure out. On ClickHouse a second pass (`clickhouse_property_resolution`) runs next and swaps the node for a faster column+when one exists; the warehouse backends have no second pass, so for them this lowering is the whole story.++It deliberately leaves four things alone, to stay minimal and change nothing about the output:++- Struct / array (data-warehouse) columns — they use different access syntax, so only JSON-blob columns lower here.+- Person/group properties read through a joined subquery — those print as `alias.field`, not as a property read.+- The numeric/boolean cast — on ClickHouse the swapper wraps the property in a cast before this pass runs, so the cast+ simply ends up wrapping the `PropertyAccess` and is carried through untouched.+- Access control — the node still points at the raw blob `Field`, which the ClickHouse printer drops restricted keys+ from later, so a restricted value still collapses to `''`.+"""++from typing import cast++from posthog.hogql import ast+from posthog.hogql.base import _T_AST+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.models import StringJSONDatabaseField+from posthog.hogql.visitor import CloningVisitor+++class LogicalPropertyLowering(CloningVisitor):+ """Replaces JSON-blob `properties.X` Field reads with `PropertyAccess`. Descends every position (CloningVisitor)."""++ def __init__(self, context: HogQLContext) -> None:+ # The lowered AST is printed directly after this pass, so keep resolved types rather than clearing them.+ super().__init__(clear_types=False)+ self.context = context++ def visit_field(self, node: ast.Field) -> ast.Expr:+ lowered = self._lower_property_field(node)+ return lowered if lowered is not None else super().visit_field(node)++ # Note on aliases: an alias over a property read keeps its `FieldAliasType` wrapping the original `PropertyType`.+ # That is the resolver's binding — a reference to the alias carries the same type object — and it is how a later+ # pass tells "alias over property `x`" apart from a shadowing alias of the same name. Only the lowered node itself+ # gets a plain value type below.++ def _lower_property_field(self, node: ast.Field) -> ast.PropertyAccess | None:+ property_type = node.type+ if not isinstance(property_type, ast.PropertyType):+ return None+ # A repointed person/group property is read as a plain aliased column from its joined subquery, not a property.+ if property_type.joined_subquery is not None:+ return None+ chain = property_type.chain+ base_field_type = property_type.field_type+ # Only lower reads off a JSON blob column (`properties` / `person_properties`). Struct/array warehouse columns+ # resolve to a non-JSON database field and keep their existing printer handling.+ if not isinstance(base_field_type.resolve_database_field(self.context), StringJSONDatabaseField):+ return None++ # chain[0] is always the top-level property name (a string). Deeper elements keep their Python type: an integer+ # is an array index that must reach the JSON extract as an integer, not the string "1" (which would be the object+ # key "1").+ keys: list[str | int] = [str(chain[0])]+ keys.extend(link if isinstance(link, int) else str(link) for link in chain[1:])++ # The node's type is its *value* type — the JSON-extract result, a nullable String — not a `PropertyType`. A+ # `PropertyType` here would still mean "this is a property" and send a lowered comparison operand back into the+ # property-handling path we just bypassed. Everything a later pass needs (table, field, property name) is already+ # on `expr` (the blob `Field`, whose `.type` is the source `FieldType`) and `keys`. The type must be nullable so+ # the printer keeps wrapping the read in `ifNull(...)`; a JSON read can always miss the key.+ return ast.PropertyAccess(+ expr=ast.Field(chain=[base_field_type.name], type=base_field_type),+ keys=keys,+ type=ast.StringType(nullable=True),+ )+++def lower_property_access(node: _T_AST, context: HogQLContext) -> _T_AST:+ """Lower JSON-blob property reads to `PropertyAccess`, including the within-non-HogQL (lightweight-DELETE) path."""+ return cast(_T_AST, LogicalPropertyLowering(context).visit(node))diff --git a/posthog/hogql/transforms/test/__snapshots__/test_events_predicate_pushdown.ambr b/posthog/hogql/transforms/test/__snapshots__/test_events_predicate_pushdown.ambrindex 423d87bb10da..035db851447c 100644--- a/posthog/hogql/transforms/test/__snapshots__/test_events_predicate_pushdown.ambr+++ b/posthog/hogql/transforms/test/__snapshots__/test_events_predicate_pushdown.ambr@@ -4,14 +4,14 @@SELECT e.event AS event, e__session.`$session_duration` AS `$session_duration`FROM (- SELECT e.`$session_id` AS `$session_id`, e.event AS event, toTimeZone(e.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, e.event AS eventFROM events AS eWHERE and(equals(e.team_id, 420), greaterOrEquals(e.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), less(e.timestamp, toDateTime64(%(hogql_val_3)s, 6, %(hogql_val_4)s)))LIMIT 50) AS e LEFT JOIN (SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_9)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_10)s)), e__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(e.__pd_expr_0, e__session.session_id_v7)LIMIT 50'''# ---@@ -20,30 +20,30 @@SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.event AS eventFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), less(events.timestamp, toDateTime64(%(hogql_val_3)s, 6, %(hogql_val_4)s)))LIMIT 50) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_9)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_10)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 50'''# ---# name: TestEventsPredicatePushdownTransform.test_bare_timestamp_with_select_alias_pushes_down'''- SELECT events.event AS event, toTimeZone(toTimeZone(events.timestamp, %(hogql_val_10)s), %(hogql_val_11)s) AS timestamp, events__session.`$session_duration` AS `$session_duration`+ SELECT events.event AS event, events.__pd_expr_0 AS timestamp, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toTimeZone(toTimeZone(events.timestamp, %(hogql_val_0)s), %(hogql_val_1)s) AS __pd_expr_0, toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_2)s)) AS __pd_expr_1, events.event AS eventFROM events- WHERE and(equals(events.team_id, 420), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_1)s), toDateTime64(%(hogql_val_2)s, 6, %(hogql_val_3)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_4)s), today()))+ WHERE and(equals(events.team_id, 420), greaterOrEquals(toTimeZone(toTimeZone(events.timestamp, %(hogql_val_3)s), %(hogql_val_4)s), %(hogql_val_5)s), lessOrEquals(toTimeZone(toTimeZone(events.timestamp, %(hogql_val_6)s), %(hogql_val_7)s), today()))LIMIT 50000) AS events LEFT JOIN (- SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7+ SELECT dateDiff(%(hogql_val_8)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_9)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_10)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessions- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(today(), toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_9)s)), events__session.session_id_v7)+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_11)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(today(), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_1, events__session.session_id_v7)LIMIT 50000'''# ---@@ -52,14 +52,14 @@SELECT e.event AS event, e__session.`$session_duration` AS `$session_duration`FROM (- SELECT e.`$session_id` AS `$session_id`, e.event AS event, toTimeZone(e.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, e.event AS eventFROM events AS eWHERE and(equals(e.team_id, 420), greaterOrEquals(e.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))LIMIT 50000) AS e LEFT JOIN (SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_7)s)), e__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(e.__pd_expr_0, e__session.session_id_v7)LIMIT 50000'''# ---@@ -68,14 +68,14 @@SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.event AS eventFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 50000'''# ---@@ -104,16 +104,16 @@# name: TestEventsPredicatePushdownTransform.test_multiple_poe_fields_with_session_join'''- SELECT events.event AS event, events.person_id AS id, events.person_properties AS properties, toTimeZone(events.person_created_at, %(hogql_val_9)s) AS created_at, events__session.`$session_duration` AS `$session_duration`+ SELECT events.event AS event, events.person_id AS id, events.person_properties AS properties, events.__pd_expr_0 AS created_at, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.person_created_at, %(hogql_val_0)s) AS person_created_at, events.person_id AS person_id, events.person_properties AS person_properties, toTimeZone(events.timestamp, %(hogql_val_1)s) AS timestamp+ SELECT toTimeZone(events.person_created_at, %(hogql_val_0)s) AS __pd_expr_0, toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_1)s)) AS __pd_expr_1, events.event AS event, events.person_id AS person_id, events.person_properties AS person_propertiesFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_2)s, 6, %(hogql_val_3)s)))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_8)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_1, events__session.session_id_v7)LIMIT 50000'''# ---@@ -122,14 +122,14 @@SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.event AS eventFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), equals(events.event, %(hogql_val_3)s))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_8)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 50000'''# ---@@ -227,16 +227,16 @@# name: TestEventsPredicatePushdownTransform.test_poe_created_at_with_session_join'''- SELECT events.event AS event, toTimeZone(events.person_created_at, %(hogql_val_9)s) AS created_at, events__session.`$session_duration` AS `$session_duration`+ SELECT events.event AS event, events.__pd_expr_0 AS created_at, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.person_created_at, %(hogql_val_0)s) AS person_created_at, toTimeZone(events.timestamp, %(hogql_val_1)s) AS timestamp+ SELECT toTimeZone(events.person_created_at, %(hogql_val_0)s) AS __pd_expr_0, toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_1)s)) AS __pd_expr_1, events.event AS eventFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_2)s, 6, %(hogql_val_3)s)))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_8)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_1, events__session.session_id_v7)LIMIT 50000'''# ---@@ -245,14 +245,14 @@SELECT events.person_id AS id, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.person_id AS person_id, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.person_id AS person_idFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 50000'''# ---@@ -261,14 +261,14 @@SELECT events.event AS event, events.person_properties AS properties, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, events.person_properties AS person_properties, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.event AS event, events.person_properties AS person_propertiesFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 50000'''# ---@@ -277,13 +277,13 @@SELECT sessions.session_id AS session_id, events.uuid AS uuidFROM (- SELECT events.`$session_id` AS `$session_id`, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp, events.uuid AS uuid+ SELECT events.`$session_id` AS `$session_id`, events.uuid AS uuidFROM events- WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_0)s, 6, %(hogql_val_1)s)))LIMIT 50000) AS events LEFT JOIN (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessions- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_2)s, toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)LIMIT 50000'''@@ -293,13 +293,13 @@SELECT sessions.session_id AS session_id, events.uuid AS uuidFROM (- SELECT events.`$session_id` AS `$session_id`, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp, events.uuid AS uuid+ SELECT events.`$session_id` AS `$session_id`, events.uuid AS uuidFROM events- WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_0)s, 6, %(hogql_val_1)s)))LIMIT 50000) AS events LEFT OUTER JOIN (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessions- WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_2)s, toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)LIMIT 50000'''@@ -313,7 +313,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_4)s)), events__session.session_id_v7)- WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), ifNull(greater(events__session.`$session_duration`, 0), 0))+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), greater(events__session.`$session_duration`, 0))LIMIT 50000'''# ---@@ -322,9 +322,9 @@SELECT events.event AS event, events__person.id AS idFROM (- SELECT events.distinct_id AS distinct_id, events.event AS event, events.person_id AS person_id, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT events.distinct_id AS distinct_id, events.event AS event, events.person_id AS person_idFROM events- WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_0)s, 6, %(hogql_val_1)s)))LIMIT 50000) AS events LEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_idFROM person_distinct_id_overrides@@ -336,7 +336,7 @@FROM personWHERE equals(person.team_id, 420)GROUP BY person.id- HAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, %(hogql_val_3)s)), person.version), 1), plus(now64(6, %(hogql_val_4)s), toIntervalDay(1))))+ HAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, %(hogql_val_2)s)), person.version), 1), plus(now64(6, %(hogql_val_3)s), toIntervalDay(1))))SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)LIMIT 50000'''@@ -348,14 +348,14 @@FROM (SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.event AS eventFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), or(equals(events.event, %(hogql_val_3)s), equals(events.event, %(hogql_val_4)s)))LIMIT 100) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_9)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 100)GROUP BY eventLIMIT 50000diff --git a/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr b/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambrindex bc333a4ebc91..1d113fdd862d 100644--- a/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr+++ b/posthog/hogql/transforms/test/__snapshots__/test_in_cohort.ambr@@ -7,7 +7,7 @@SELECT cohortpeople.person_id AS cohort_person_id, 1 AS matched, cohortpeople.cohort_id AS cohort_idFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, XX), equals(cohortpeople.version, 0))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_0)s), ifNull(equals(__in_cohort.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_0)s), equals(__in_cohort.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -29,7 +29,7 @@SELECT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_idFROM person_static_cohortWHERE and(equals(person_static_cohort.team_id, 99999), in(person_static_cohort.cohort_id, [1, 2, 3, 4, 5 /* ... */]))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(__in_cohort.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(__in_cohort.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -51,7 +51,7 @@SELECT person_static_cohort.person_id AS cohort_person_id, 1 AS matched, person_static_cohort.cohort_id AS cohort_idFROM person_static_cohortWHERE and(equals(person_static_cohort.team_id, 99999), in(person_static_cohort.cohort_id, [1, 2, 3, 4, 5 /* ... */]))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(__in_cohort.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(__in_cohort.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -73,7 +73,7 @@SELECT person_static_cohort.person_id AS person_id, 1 AS matchedFROM person_static_cohortWHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(in_cohort__XX.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -97,7 +97,7 @@WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, XX))GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.versionHAVING greater(sum(cohortpeople.sign), 0)) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(in_cohort__XX.matched, 1), 0), equals(events.event, %(hogql_val_0)s))+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1), equals(events.event, %(hogql_val_0)s))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -121,7 +121,7 @@SELECT person_static_cohort.person_id AS person_id, 1 AS matchedFROM person_static_cohortWHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(in_cohort__XX.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -143,7 +143,7 @@SELECT person_static_cohort.person_id AS person_id, 1 AS matchedFROM person_static_cohortWHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(in_cohort__XX.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -180,7 +180,7 @@WHERE ifNull(equals(persons.properties___test_prop, %(hogql_val_5)s), 0)ORDER BY persons.id ASCSETTINGS optimize_aggregation_in_order=1, join_algorithm='auto'))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_6)s), ifNull(equals(__in_cohort.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_6)s), equals(__in_cohort.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -208,7 +208,7 @@SELECT cohortpeople.person_id AS cohort_person_id, 1 AS matched, cohortpeople.cohort_id AS cohort_idFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), or(and(equals(cohortpeople.cohort_id, XX), equals(cohortpeople.version, 0)), and(equals(cohortpeople.cohort_id, XX), equals(cohortpeople.version, 0))))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_0)s), ifNull(equals(__in_cohort.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_0)s), equals(__in_cohort.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -257,7 +257,7 @@WHERE ifNull(equals(persons.properties___test_prop, %(hogql_val_11)s), 0)ORDER BY persons.id ASCSETTINGS optimize_aggregation_in_order=1, join_algorithm='auto'))) AS __in_cohort ON equals(__in_cohort.cohort_person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_12)s), ifNull(equals(__in_cohort.matched, 1), 0))+ WHERE and(equals(events.team_id, 99999), equals(events.event, %(hogql_val_12)s), equals(__in_cohort.matched, 1))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -290,7 +290,7 @@WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, XX))GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.versionHAVING greater(sum(cohortpeople.sign), 0)) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(in_cohort__XX.matched, 1), 0), equals(events.event, %(hogql_val_0)s))+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1), equals(events.event, %(hogql_val_0)s))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -326,7 +326,7 @@WHERE ifNull(equals(persons.properties___test_prop, %(hogql_val_5)s), 0)ORDER BY persons.id ASCSETTINGS optimize_aggregation_in_order=1, join_algorithm='auto'))) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(in_cohort__XX.matched, 1), 0), equals(events.event, %(hogql_val_6)s))+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1), equals(events.event, %(hogql_val_6)s))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -359,7 +359,7 @@SELECT person_static_cohort.person_id AS person_id, 1 AS matchedFROM person_static_cohortWHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, XX))) AS in_cohort__XX ON equals(in_cohort__XX.person_id, events.person_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(in_cohort__XX.matched, 1), 0), equals(events.event, %(hogql_val_0)s))+ WHERE and(equals(events.team_id, 99999), equals(in_cohort__XX.matched, 1), equals(events.event, %(hogql_val_0)s))LIMIT 100SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0diff --git a/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambr b/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambrindex 1d5d61891ce9..0bd576755675 100644--- a/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambr+++ b/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambr@@ -4,14 +4,14 @@SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.event AS eventFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), less(events.timestamp, toDateTime64(%(hogql_val_3)s, 6, %(hogql_val_4)s)), equals(events.event, %(hogql_val_5)s), isNotNull(events.`$session_id`))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_6)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_7)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_8)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_9)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_10)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_11)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 50000'''# ---@@ -24,7 +24,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_4)s)), events__session.session_id_v7)- WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), ifNull(greater(events__session.`$session_duration`, 0), 0))+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), greater(events__session.`$session_duration`, 0))LIMIT 50000'''# ---@@ -33,14 +33,14 @@SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`FROM (- SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, events.event AS eventFROM eventsWHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), less(events.timestamp, toDateTime64(%(hogql_val_3)s, 6, %(hogql_val_4)s)))LIMIT 50000) AS events LEFT JOIN (SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_9)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_10)s)), events__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.__pd_expr_0, events__session.session_id_v7)LIMIT 50000'''# ---@@ -49,14 +49,14 @@SELECT e.event AS event, e__session.`$session_duration` AS `$session_duration`FROM (- SELECT e.`$session_id` AS `$session_id`, e.event AS event, toTimeZone(e.timestamp, %(hogql_val_0)s) AS timestamp+ SELECT toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_0)s)) AS __pd_expr_0, e.event AS eventFROM events AS eWHERE and(equals(e.team_id, 420), greaterOrEquals(e.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), equals(e.event, %(hogql_val_3)s))LIMIT 50000) AS e LEFT JOIN (SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))- GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_8)s)), e__session.session_id_v7)+ GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(e.__pd_expr_0, e__session.session_id_v7)LIMIT 50000'''# ---diff --git a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py b/posthog/hogql/transforms/test/test_events_predicate_pushdown.pyindex a31c379b517b..28ca5e946445 100644--- a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py+++ b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py@@ -1,5 +1,6 @@+import reimport json-from typing import Any+from typing import Any, castfrom uuid import uuid4import pytest@@ -33,12 +34,12 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.resolver import resolve_typesfrom posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.hogql.transforms.events_predicate_pushdown import (- EventsFieldCollector,EventsPredicatePushdownTransform,- LazyTypeDetector,+ EventsSubexprHoister,_printer_top_level_select_ids,)-from posthog.hogql.transforms.lazy_tables import resolve_lazy_tables+from posthog.hogql.transforms.logical_property_lowering import lower_property_access+from posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.client import sync_executefrom posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition@@ -106,11 +107,11 @@ class TestEventsPredicatePushdownTransform(BaseTest):def test_unexpected_internal_error_degrades_to_flat_query(self):# Pushdown is a pure optimization: an unexpected raise inside the rewrite must leave the query intact- # (run flat), never break it. Force a raise in _build_typed_subquery (called before any mutation) and+ # (run flat), never break it. Force a raise in _build_subquery (called before any mutation) and# assert the printed SQL matches the un-pushed flat form.select = "SELECT event, session.$session_duration FROM events WHERE timestamp >= '2024-01-01' LIMIT 10"flat = self._print_select(select, modifiers=HogQLQueryModifiers(pushDownPredicates=False))- with patch.object(EventsPredicatePushdownTransform, "_build_typed_subquery", side_effect=RuntimeError("boom")):+ with patch.object(EventsPredicatePushdownTransform, "_build_subquery", side_effect=RuntimeError("boom")):guarded = self._print_select(select, modifiers=HogQLQueryModifiers(pushDownPredicates=True))assert guarded == flat, f"expected flat fallback on internal error:\nflat={flat}\nguarded={guarded}"assert ") AS events LEFT JOIN" not in guarded, f"the events scan must not be wrapped on fallback:\n{guarded}"@@ -360,6 +361,33 @@ class TestEventsPredicatePushdownTransform(BaseTest):"nested subquery with an explicit LIMIT should be pushed:\n" + printed)+ def test_pushdown_array_index_vs_object_key_stay_distinct(self):+ # `properties.a[1]` (array index) and `properties.a['1']` (object key) are different extractions that share+ # one preferred name (`properties__a__1`); they must hoist to separate projections, or the second read+ # silently returns the first's value.+ printed = self._print_select(+ "SELECT properties.a[1] AS i, properties.a['1'] AS k, session.$session_duration "+ "FROM events WHERE timestamp >= '2024-01-01' LIMIT 10"+ )+ assert ") AS events LEFT JOIN" in printed, f"expected pushdown to fire:\n{printed}"+ match_i = re.search(r"SELECT (.*?) AS i,", printed)+ match_k = re.search(r" AS i, (.*?) AS k,", printed)+ assert match_i and match_k, printed+ assert match_i.group(1) != match_k.group(1), f"distinct reads collapsed onto one projection:\n{printed}"++ def test_pushdown_nested_key_vs_flat_double_underscore_key_stay_distinct(self):+ # Nested `properties.a.b` and a flat property literally named `a__b` share the preferred name+ # `properties__a__b` but are different reads; they must hoist to separate projections.+ printed = self._print_select(+ "SELECT properties.a.b AS x, properties['a__b'] AS y, session.$session_duration "+ "FROM events WHERE timestamp >= '2024-01-01' LIMIT 10"+ )+ assert ") AS events LEFT JOIN" in printed, f"expected pushdown to fire:\n{printed}"+ match_x = re.search(r"SELECT (.*?) AS x,", printed)+ match_y = re.search(r" AS x, (.*?) AS y,", printed)+ assert match_x and match_y, printed+ assert match_x.group(1) != match_y.group(1), f"distinct reads collapsed onto one projection:\n{printed}"+class TestOuterWhereAssignment:"""Verify that _apply_pushdown assigns outer_where back to node.where."""@@ -763,193 +791,134 @@ class TestEventsPredicatePushdownTransformUnit:assert aliases == set()-class TestLazyTypeDetector(BaseTest):- """Tests for LazyTypeDetector using real HogQL queries.-- A LazyJoinType / LazyTableType in the AST means lazy join resolution hasn't completed, so predicate- pushdown should be skipped.- """+class TestEventsSubexprHoister(BaseTest):+ """The hoister rewrites an events query's outer leaves into references to the pre-filtering subquery, recording+ which columns / property values the subquery must project. It runs on the lowered AST (property value reads are+ `PropertyAccess`); a lazy-join or other non-events reference is simply left in the outer query."""def setUp(self):super().setUp()self.database = Database.create_for(team=self.team)self.context = HogQLContext(team_id=self.team.pk, database=self.database, enable_select_queries=True)- def _resolve_query(self, query: str) -> ast.SelectQuery:- """Parse and resolve types for a query (without lazy table resolution)."""- parsed = parse_select(query)- resolved = resolve_types(parsed, self.context, dialect="clickhouse")- assert isinstance(resolved, ast.SelectQuery)- return resolved-- def test_detects_lazy_join_from_session_field(self):- """Query accessing session.$session_duration has LazyJoinType before lazy resolution."""- # session is a LazyJoin on events, so resolve_types produces a LazyJoinType- node = self._resolve_query("SELECT session.$session_duration FROM events")-- detector = LazyTypeDetector()- detector.visit(node)-- assert detector.found_lazy_type is True-- def test_detects_lazy_join_from_person_field(self):- """Query accessing person.id has LazyJoinType before lazy resolution."""- node = self._resolve_query("SELECT person.id FROM events")-- detector = LazyTypeDetector()- detector.visit(node)-- assert detector.found_lazy_type is True-- def test_no_lazy_type_for_direct_events_columns(self):- """Query with only direct events columns has no lazy types."""- node = self._resolve_query("SELECT event, timestamp, distinct_id FROM events")-- detector = LazyTypeDetector()- detector.visit(node)-- assert detector.found_lazy_type is False-- def test_no_lazy_type_after_lazy_table_resolution(self):- """After resolve_lazy_tables, there should be no lazy types in the main query fields."""- resolved = self._resolve_query(- "SELECT event, session.$session_duration FROM events WHERE timestamp > '2024-01-01'"+ def _run(self, query: str) -> tuple[EventsSubexprHoister, list[ast.Expr], ast.SelectQueryAliasType]:+ resolved = resolve_types(parse_select(query), self.context, dialect="clickhouse")+ lowered = lower_property_access(resolved, self.context)+ assert isinstance(lowered, ast.SelectQuery) and lowered.select_from is not None+ from_type = lowered.select_from.type+ assert isinstance(from_type, (ast.TableType, ast.TableAliasType))+ subquery_ref = ast.SelectQueryAliasType(+ alias="events", select_query_type=ast.SelectQueryType(columns={}, tables={}))- resolve_lazy_tables(resolved, "clickhouse", [], self.context)-- # Check only the SELECT fields (not the joined subqueries which may have their own structure)- detector = LazyTypeDetector()- for field in resolved.select:- detector.visit(field)-- assert detector.found_lazy_type is False---class TestEventsFieldCollector(BaseTest):- """Tests for EventsFieldCollector using real HogQL queries.-- EventsFieldCollector collects the events database columns a query needs and detects non-direct fields- (PropertyType, LazyJoinType) that prevent safe pushdown.- """-- def setUp(self):- super().setUp()- self.database = Database.create_for(team=self.team)- self.context = HogQLContext(team_id=self.team.pk, database=self.database, enable_select_queries=True)-- def _resolve_query(self, query: str) -> tuple[ast.SelectQuery, ast.TableType | ast.TableAliasType]:- """Parse, resolve types, and return query with events table type."""- parsed = parse_select(query)- resolved = resolve_types(parsed, self.context, dialect="clickhouse")- assert isinstance(resolved, ast.SelectQuery)- assert resolved.select_from is not None- events_table_type = resolved.select_from.type- assert isinstance(events_table_type, (ast.TableType, ast.TableAliasType))- return resolved, events_table_type-- def test_collects_direct_database_columns(self):- """Direct events columns like event, timestamp are collected."""- node, events_table_type = self._resolve_query("SELECT event, timestamp FROM events WHERE distinct_id = 'user1'")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert "event" in collector.collected_fields- assert "timestamp" in collector.collected_fields- assert "distinct_id" in collector.collected_fields- assert collector.has_non_direct_fields is False-- def test_property_access_collects_base_column(self):- # Accessing properties.$browser collects the base `properties` column so the property filter- # can be pushed and re-typed to the inner events table, rather than flagging it as non-direct.- node, events_table_type = self._resolve_query("SELECT properties.$browser FROM events")+ hoister = EventsSubexprHoister(from_type, subquery_ref, self.context)+ rewritten = [cast(ast.Expr, hoister.visit(item)) for item in lowered.select]+ return hoister, rewritten, subquery_ref- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert "properties" in collector.collected_fields- assert collector.has_non_direct_fields is False-- def test_lazy_join_field_triggers_non_direct_flag(self):- """Accessing session.$session_duration (lazy join) triggers has_non_direct_fields."""- node, events_table_type = self._resolve_query("SELECT session.$session_duration FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert collector.has_non_direct_fields is True-- def test_session_id_from_events_is_direct_column(self):- """$session_id on events is a direct column (not a property access)."""- node, events_table_type = self._resolve_query("SELECT `$session_id` FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- # $session_id is a direct column on events table- assert "$session_id" in collector.collected_fields- assert collector.has_non_direct_fields is False+ @staticmethod+ def _references_subquery(node: ast.Expr, subquery_ref: ast.SelectQueryAliasType) -> bool:+ found = False++ class _Finder(TraversingVisitor):+ def visit_field(self, n: ast.Field) -> None:+ nonlocal found+ if isinstance(n.type, ast.FieldType) and n.type.table_type is subquery_ref:+ found = True+ super().visit_field(n)++ _Finder().visit(node)+ return found++ def test_direct_columns_are_projected(self):+ hoister, _, _ = self._run("SELECT event, timestamp FROM events WHERE distinct_id = 'u1'")+ assert {"event", "timestamp"} <= set(hoister.projections)+ assert hoister.blocked is False++ def test_direct_column_is_projected_under_its_database_name(self):+ # A direct column is hoisted under its database name and the outer occurrence reads the subquery column;+ # the printer resolves its nullability through the subquery column type, so it stays a usable join key.+ hoister, rewritten, subquery_ref = self._run("SELECT event FROM events")+ assert "event" in hoister.projections+ assert self._references_subquery(rewritten[0], subquery_ref) is True++ def test_property_is_projected_under_its_dunder_name(self):+ # The name is `<blob column>__<key>`, so reads off different blobs never collide on a bare key.+ hoister, _, _ = self._run("SELECT properties.$browser FROM events")+ assert "properties__$browser" in hoister.projections+ assert hoister.blocked is False++ def test_nested_property_uses_dunder_joined_name(self):+ hoister, _, _ = self._run("SELECT properties.a.b FROM events")+ assert "properties__a__b" in hoister.projections++ def test_property_reference_is_rewritten_to_subquery(self):+ # The outer occurrence of a property read becomes a reference to the subquery column the physical pass fills.+ _, rewritten, subquery_ref = self._run("SELECT properties.$browser FROM events")+ assert self._references_subquery(rewritten[0], subquery_ref) is True++ def test_joined_table_field_is_not_projected(self):+ # session.* is a lazy join, never the target events table; the hoister leaves it for the outer query.+ hoister, _, _ = self._run("SELECT event FROM events")+ assert "session_duration" not in hoister.projections and "$session_duration" not in hoister.projectionsdef test_poe_properties_collected_as_person_properties(self):- """poe.properties (VirtualTable) resolves to database column person_properties."""- node, events_table_type = self._resolve_query("SELECT poe.properties FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert "person_properties" in collector.collected_fields- assert collector.has_non_direct_fields is False+ # poe.properties (VirtualTable) resolves to database column person_properties.+ hoister, _, _ = self._run("SELECT poe.properties FROM events")+ assert "person_properties" in hoister.projections+ assert hoister.blocked is Falsedef test_poe_id_collected_as_person_id(self):- """poe.id (VirtualTable) resolves to database column person_id."""- node, events_table_type = self._resolve_query("SELECT poe.id FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert "person_id" in collector.collected_fields- assert collector.has_non_direct_fields is False+ # poe.id (VirtualTable) resolves to database column person_id.+ hoister, _, _ = self._run("SELECT poe.id FROM events")+ assert "person_id" in hoister.projections+ assert hoister.blocked is Falsedef test_poe_created_at_collected_as_person_created_at(self):- """poe.created_at (VirtualTable) resolves to database column person_created_at."""- node, events_table_type = self._resolve_query("SELECT poe.created_at FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert "person_created_at" in collector.collected_fields- assert collector.has_non_direct_fields is False+ # poe.created_at (VirtualTable) resolves to database column person_created_at.+ hoister, _, _ = self._run("SELECT poe.created_at FROM events")+ assert "person_created_at" in hoister.projections+ assert hoister.blocked is Falsedef test_poe_field_type_has_virtual_table_type(self):- """Collected poe field has VirtualTableType as its table_type."""- node, events_table_type = self._resolve_query("SELECT poe.properties FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- field_type = collector.collected_fields["person_properties"]+ # The projected poe field keeps its VirtualTableType (the physical pass peels it to person_properties).+ hoister, _, _ = self._run("SELECT poe.properties FROM events")+ field_type = hoister.column_types["person_properties"]+ assert isinstance(field_type, ast.FieldType)assert isinstance(field_type.table_type, ast.VirtualTableType)def test_poe_mixed_with_direct_columns(self):- """VirtualTable fields and direct columns are both collected."""- node, events_table_type = self._resolve_query("SELECT event, poe.id, timestamp FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert "event" in collector.collected_fields- assert "person_id" in collector.collected_fields- assert "timestamp" in collector.collected_fields- assert collector.has_non_direct_fields is False+ # VirtualTable fields and direct columns are both projected.+ hoister, _, _ = self._run("SELECT event, poe.id, timestamp FROM events")+ assert {"event", "person_id", "timestamp"} <= set(hoister.projections)+ assert hoister.blocked is Falsedef test_poe_revenue_analytics_lazy_join_triggers_non_direct(self):- """poe.revenue_analytics is a LazyJoin inside VirtualTable, so it triggers the non-direct flag."""- node, events_table_type = self._resolve_query("SELECT poe.revenue_analytics.revenue FROM events")-- collector = EventsFieldCollector(events_table_type, self.context)- collector.visit(node)-- assert collector.has_non_direct_fields is True+ # poe.revenue_analytics is a LazyJoin inside VirtualTable, not an events column, so it is foreign — left in+ # the outer query (an empty projection set makes the full transform decline pushdown), never hoisted.+ hoister, rewritten, subquery_ref = self._run("SELECT poe.revenue_analytics.revenue FROM events")+ assert hoister.projections == {}+ assert self._references_subquery(rewritten[0], subquery_ref) is False++ def test_poe_property_and_event_property_same_key_project_separately(self):+ # `properties.url` reads the event blob; `poe.properties.url` reads `person_properties`. They share the key+ # `url` but must hoist to separate columns — collapsing them onto one silently read the wrong blob for one.+ hoister, _, _ = self._run("SELECT properties.url, poe.properties.url FROM events")+ assert "properties__url" in hoister.projections+ assert "person_properties__url" in hoister.projections+ assert hoister.blocked is False++ def test_different_reads_colliding_on_preferred_name_get_separate_projections(self):+ # `properties.a.b` and `properties['a__b']` both prefer the name `properties__a__b` but are different reads;+ # the second must get a fresh synthetic column instead of silently reusing the first's projection.+ hoister, _, _ = self._run("SELECT properties.a.b, properties['a__b'] FROM events")+ assert "properties__a__b" in hoister.projections+ assert "__pd_expr_0" in hoister.projections+ assert hoister.projections["properties__a__b"] != hoister.projections["__pd_expr_0"]++ def test_identical_computed_expressions_share_one_projection(self):+ # Structurally identical non-leaf expressions dedupe onto a single synthetic projection.+ hoister, _, _ = self._run("SELECT upper(event), upper(event) FROM events")+ synthetic = [name for name in hoister.projections if name.startswith("__pd_expr_")]+ assert len(synthetic) == 1class TestSavedQueryWithLazyJoins(BaseTest):@@ -1735,6 +1704,24 @@ class TestEventsPredicatePushdownMaterializedExecution(_PushdownExecutionTestBas)self._assert_equivalent(select, expected_rows=3)+ def test_exec_materialized_property_as_join_key_exposes_mat_column(self):+ # A materialized property used as the events-side join key. The key expression stays in the ON (a subquery+ # column would read as nullable and break join-key detection), so the physical pass rewrites the ON's+ # property to `events.mat_tier`, which the subquery must expose — without it the ON references `mat_tier`+ # against a subquery alias that lacks it (Unknown identifier). This asserts the exposure on the printed SQL;+ # end-to-end execution of a property join key is covered by test_query.test_join_with_property_materialized.+ with materialized("events", "tier") as mat_col:+ self._create_data()+ select = (+ "SELECT events.event AS ae, p.id FROM events "+ "LEFT JOIN persons p ON p.properties.tier = events.properties.tier "+ "WHERE events.timestamp >= '2024-01-01' AND events.timestamp < '2024-01-08' LIMIT 50"+ )+ subquery = self._events_subquery(self._print_pushdown_sql(select))+ assert mat_col.name in subquery, (+ f"expected the materialized column exposed for the property join key:\n{subquery}"+ )+def test_exec_materialized_property_in_order_by_declines(self):# A materialized property in ORDER BY: any ORDER BY blocks the inner LIMIT, so the pushdown declines# and the query runs flat. Results must stay equivalent.@@ -1918,7 +1905,7 @@ class TestEventsPredicatePushdownPropertyGroupsExecution(_PushdownExecutionTestBassert len(with_pushdown or []) == 2 # only u1's two events have the tier propertydef test_exec_property_type_uses_property_group_column(self):- # `properties.tier` (a PropertyType, not JSONHas) under OPTIMIZED is read from the property-group+ # `properties.tier` (a lowered PropertyAccess value read, not JSONHas) under OPTIMIZED is read from the property-group# Map column by the printer; the collector's PropertyType path must expose it too. Distinct code# path from the JSONHas tests above (visit_field/_collect_materialized_column, not visit_call).self._create_data()@@ -1950,6 +1937,20 @@ class TestEventsPredicatePushdownPropertyGroupsExecution(_PushdownExecutionTestB)assert len(with_pushdown or []) == 3 # u1's two events (has tier) and u2's event (no tier)+ def test_exec_having_on_property_alias_stays_correct(self):+ # A non-aggregate HAVING drops rows after the join, so `_safe_inner_limit` declines the pushdown (a pushed+ # LIMIT could under-produce). The query compiles flat; the comparison on the alias must still resolve to the+ # property correctly and match the same rows with the modifier on and off. (If the decline is ever relaxed,+ # the tables-in-scope guard is the second barrier: it stops the alias comparison from being rewritten to a+ # bare events column the subquery doesn't project.)+ self._create_data()+ select = (+ f"SELECT properties.tier AS t, session.$session_duration AS d "+ f"FROM events WHERE {self._RANGE} HAVING t = 'pro' LIMIT 50"+ )+ with_pushdown = self._assert_results_equivalent(select)+ assert len(with_pushdown) == 2 # u1's two tier='pro' events+class TestEventsPredicatePushdownDmatExecution(_PushdownExecutionTestBase):"""Pushdown must expose dmat (dynamic materialized) columns in the subquery too.diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 734e4eae758a..b4665730eeb8 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -20,6 +20,7 @@ from parameterized import parameterizedfrom posthog.hogql import astfrom posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Databasefrom posthog.hogql.modifiers import HogQLQueryModifiersfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_ast@@ -31,7 +32,9 @@ from posthog.hogql.property_planner import (plan_property_comparison,)from posthog.hogql.query import execute_hogql_query+from posthog.hogql.resolver import resolve_typesfrom posthog.hogql.test.utils import pretty_print_in_tests+from posthog.hogql.transforms.property_types import build_property_swapperfrom posthog.hogql.type_system import ComparisonCompatibilityfrom posthog.models import PropertyDefinition@@ -127,12 +130,32 @@ class TestPropertyTypes(BaseTest):select: str,restricted_properties: set[tuple[str, int]] | None = None,) -> PropertyComparisonPlan:- context, prepared = self._prepare_select(select, restricted_properties=restricted_properties)- comparison = cast(ast.CompareOperation, prepared.where)+ context, resolved = self._resolve_select(select, restricted_properties=restricted_properties)+ comparison = cast(ast.CompareOperation, resolved.where)plan = plan_property_comparison(comparison, context)assert plan is not Nonereturn plan+ def _resolve_select(+ self,+ select: str,+ restricted_properties: set[tuple[str, int]] | None = None,+ ) -> tuple[HogQLContext, ast.SelectQuery]:+ """Resolve types and build the property-swapper registry without preparing further.++ The planner is an analysis over the resolved AST; the prepared AST has already been lowered past the point+ where property reads are recognizable (they become bare physical-column expressions), so the planner must be+ fed its actual pipeline-position input.+ """+ expr = parse_select(select)+ context = HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True)+ if restricted_properties is not None:+ context.restricted_properties = restricted_properties+ context.database = Database.create_for(context.team_id, modifiers=context.modifiers, team=context.team)+ node = cast(ast.SelectQuery, resolve_types(expr, context, dialect="clickhouse"))+ build_property_swapper(node, context)+ return context, node+def _prepare_select(self,select: str,@@ -257,8 +280,8 @@ class TestPropertyTypes(BaseTest):assert plan.minmax_blocker == PropertyMinmaxBlocker.NO_MINMAX_INDEXdef test_property_type_resolve_constant_type_uses_property_metadata(self) -> None:- context, prepared = self._prepare_select("select count() from events where properties.$screen_width < 5")- comparison = cast(ast.CompareOperation, prepared.where)+ context, resolved = self._resolve_select("select count() from events where properties.$screen_width < 5")+ comparison = cast(ast.CompareOperation, resolved.where)plan = plan_property_comparison(comparison, context)assert plan is not Nonediff --git a/posthog/hogql/visitor.py b/posthog/hogql/visitor.pyindex e3debd05f169..890d35351c1c 100644--- a/posthog/hogql/visitor.py+++ b/posthog/hogql/visitor.py@@ -133,6 +133,9 @@ class TraversingVisitor(Visitor[None]):for expr in node.exprs:self.visit(expr)+ def visit_property_access(self, node: ast.PropertyAccess):+ self.visit(node.expr)+def visit_lambda(self, node: ast.Lambda):self.visit(node.expr)@@ -709,6 +712,15 @@ class CloningVisitor(Visitor[Any]):exprs=[self.visit(expr) for expr in node.exprs],)+ def visit_property_access(self, node: ast.PropertyAccess):+ return ast.PropertyAccess(+ start=None if self.clear_locations else node.start,+ end=None if self.clear_locations else node.end,+ type=None if self.clear_types else node.type,+ expr=self.visit(node.expr),+ keys=list(node.keys),+ )+def visit_lambda(self, node: ast.Lambda):return ast.Lambda(start=None if self.clear_locations else node.start,@@ -760,6 +772,7 @@ class CloningVisitor(Visitor[Any]):end=None if self.clear_locations else node.end,type=None if self.clear_types else node.type,value=node.value,+ inline_sentinel=node.inline_sentinel,)def visit_keyword(self, node: ast.Keyword):diff --git a/posthog/hogql_queries/ai/test/__snapshots__/test_actors_property_taxonomy_query_runner.ambr b/posthog/hogql_queries/ai/test/__snapshots__/test_actors_property_taxonomy_query_runner.ambrindex 4da8a5b0cca2..97f12265c662 100644--- a/posthog/hogql_queries/ai/test/__snapshots__/test_actors_property_taxonomy_query_runner.ambr+++ b/posthog/hogql_queries/ai/test/__snapshots__/test_actors_property_taxonomy_query_runner.ambr@@ -18,7 +18,7 @@groups.group_key) AS groups ARRAYJOIN arrayEnumerate([toString(groups.properties___industry)]) AS prop_index,[toString(groups.properties___industry)] AS prop_value- WHERE and(isNotNull(prop_value), ifNull(equals(groups.index, 0), 0))+ WHERE and(isNotNull(prop_value), equals(groups.index, 0))ORDER BY groups.created_at DESC)GROUP BY prop_indexORDER BY prop_index ASC@@ -55,7 +55,7 @@groups.group_key) AS groups ARRAYJOIN arrayEnumerate([toString(groups.`properties___does not exist`)]) AS prop_index,[toString(groups.`properties___does not exist`)] AS prop_value- WHERE and(isNotNull(prop_value), ifNull(equals(groups.index, 0), 0))+ WHERE and(isNotNull(prop_value), equals(groups.index, 0))ORDER BY groups.created_at DESC)GROUP BY prop_indexORDER BY prop_index ASC@@ -92,7 +92,7 @@groups.group_key) AS groups ARRAYJOIN arrayEnumerate([toString(groups.properties___employee_count)]) AS prop_index,[toString(groups.properties___employee_count)] AS prop_value- WHERE and(isNotNull(prop_value), ifNull(equals(groups.index, 0), 0))+ WHERE and(isNotNull(prop_value), equals(groups.index, 0))ORDER BY groups.created_at DESC)GROUP BY prop_indexORDER BY prop_index ASCdiff --git a/posthog/hogql_queries/groups/test/__snapshots__/test_groups_query_runner.ambr b/posthog/hogql_queries/groups/test/__snapshots__/test_groups_query_runner.ambrindex b0acf29d18e3..8f60cb5b30a6 100644--- a/posthog/hogql_queries/groups/test/__snapshots__/test_groups_query_runner.ambr+++ b/posthog/hogql_queries/groups/test/__snapshots__/test_groups_query_runner.ambr@@ -11,7 +11,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -43,7 +43,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -102,7 +102,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.index, 0), 0), ifNull(greater(accurateCastOrNull(groups.properties___arr, 'Float64'), 100.0), 0))+ WHERE and(equals(groups.index, 0), ifNull(greater(accurateCastOrNull(groups.properties___arr, 'Float64'), 100.0), 0))ORDER BY groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -131,7 +131,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY groups.created_at DESCLIMIT 11OFFSET 2 SETTINGS readonly=2,@@ -162,7 +162,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY accurateCastOrNull(groups.properties___arr, 'Float64') DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -193,7 +193,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY accurateCastOrNull(groups.properties___arr, 'Float64') ASCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -221,7 +221,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY coalesce(groups.properties___name, groups.key) DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -253,7 +253,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -309,7 +309,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.index, 0), 0), ifNull(equals(groups.properties___name, 'org0.inc'), 0))+ WHERE and(equals(groups.index, 0), ifNull(equals(groups.properties___name, 'org0.inc'), 0))ORDER BY groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -338,7 +338,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.index, 0), 0), or(ifNull(ilike(groups.properties___name, '%org2%'), 0), ilike(toString(groups.key), '%org2%')))+ WHERE and(equals(groups.index, 0), or(ifNull(ilike(groups.properties___name, '%org2%'), 0), ilike(toString(groups.key), '%org2%')))ORDER BY multiIf(ifNull(ilike(coalesce(groups.properties___name, groups.key), 'org2'), 0), 0, ifNull(ilike(coalesce(groups.properties___name, groups.key), 'org2%'), 0), 1, 2) ASC, groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -369,7 +369,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.index, 0), 0), or(ifNull(ilike(groups.properties___name, '%test%'), 0), ilike(toString(groups.key), '%test%')))+ WHERE and(equals(groups.index, 0), or(ifNull(ilike(groups.properties___name, '%test%'), 0), ilike(toString(groups.key), '%test%')))ORDER BY groups.properties___arr DESC,multiIf(ifNull(ilike(coalesce(groups.properties___name, groups.key), 'test'), 0), 0, ifNull(ilike(coalesce(groups.properties___name, groups.key), 'test%'), 0), 1, 2) ASCLIMIT 11@@ -428,7 +428,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.index, 0), 0), or(ifNull(ilike(groups.properties___name, '%test%'), 0), ilike(toString(groups.key), '%test%')))+ WHERE and(equals(groups.index, 0), or(ifNull(ilike(groups.properties___name, '%test%'), 0), ilike(toString(groups.key), '%test%')))ORDER BY multiIf(ifNull(ilike(coalesce(groups.properties___name, groups.key), 'test'), 0), 0, ifNull(ilike(coalesce(groups.properties___name, groups.key), 'test%'), 0), 1, 2) ASC, groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -457,7 +457,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.index, 0), 0), or(ifNull(ilike(groups.properties___name, '%api%'), 0), ilike(toString(groups.key), '%api%')))+ WHERE and(equals(groups.index, 0), or(ifNull(ilike(groups.properties___name, '%api%'), 0), ilike(toString(groups.key), '%api%')))ORDER BY multiIf(ifNull(ilike(coalesce(groups.properties___name, groups.key), 'api'), 0), 0, ifNull(ilike(coalesce(groups.properties___name, groups.key), 'api%'), 0), 1, 2) ASC, groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,@@ -489,7 +489,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)+ WHERE equals(groups.index, 0)ORDER BY groups.created_at DESCLIMIT 11OFFSET 0 SETTINGS readonly=2,diff --git a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_correlation.ambr b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_correlation.ambrindex eb67f86ff43f..b7c2cdbcadd0 100644--- a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_correlation.ambr+++ b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_correlation.ambr@@ -3013,7 +3013,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_props+ WHERE equals(groups.index, 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_propsGROUP BY (aggregation_target_with_props.prop).1, (aggregation_target_with_props.prop).2HAVING notIn((aggregation_target_with_props.prop).1, [])LIMIT 100@@ -3458,7 +3458,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_props+ WHERE equals(groups.index, 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_propsGROUP BY (aggregation_target_with_props.prop).1, (aggregation_target_with_props.prop).2HAVING notIn((aggregation_target_with_props.prop).1, [])LIMIT 100@@ -4149,7 +4149,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_props+ WHERE equals(groups.index, 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_propsGROUP BY (aggregation_target_with_props.prop).1, (aggregation_target_with_props.prop).2HAVING notIn((aggregation_target_with_props.prop).1, [])LIMIT 100@@ -4594,7 +4594,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE ifNull(equals(groups.index, 0), 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_props+ WHERE equals(groups.index, 0)) AS groups_0 ON equals(funnel_actors.actor_id, groups_0.key)) AS aggregation_target_with_propsGROUP BY (aggregation_target_with_props.prop).1, (aggregation_target_with_props.prop).2HAVING notIn((aggregation_target_with_props.prop).1, [])LIMIT 100diff --git a/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambr b/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambrindex a2b35b68bee8..da374388ea67 100644--- a/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambr+++ b/posthog/hogql_queries/insights/test/__snapshots__/test_insight_actors_query_runner.ambr@@ -202,7 +202,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(equals(num_intervals, 7), 0)) AS source+ WHERE equals(num_intervals, 7)) AS sourceINNER JOIN(SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'name'), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, 'US/Pacific')), 1) AS properties___name,groups.group_type_index AS index,@@ -253,7 +253,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(equals(num_intervals, 2), 0)) AS source+ WHERE equals(num_intervals, 2)) AS sourceINNER JOIN(SELECT person.id AS id,replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name@@ -280,7 +280,7 @@GROUP BY aggregation_target, start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(equals(num_intervals, 2), 0)) AS source)))+ WHERE equals(num_intervals, 2)) AS source)))GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'US/Pacific'), person.version), plus(now64(6, 'US/Pacific'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, source.actor_id)ORDER BY persons.properties___name ASC SETTINGS optimize_aggregation_in_order=1,diff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_formula.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_formula.ambrindex 50f6e6a99c8c..46432b12e0c9 100644--- a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_formula.ambr+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_formula.ambr@@ -43,7 +43,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -89,7 +89,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -134,7 +134,7 @@# name: TestFormula.test_breakdown_aggregated'''SELECT sum(total) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -174,7 +174,7 @@# name: TestFormula.test_breakdown_aggregated.1'''SELECT avg(total) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -225,7 +225,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -249,7 +249,7 @@ORDER BY day_start ASC,breakdown_value ASC)GROUP BY breakdown_value- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)+ ORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)WHERE isNotNull(breakdown_value)GROUP BY breakdown_valueORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC@@ -271,7 +271,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -295,7 +295,7 @@ORDER BY day_start ASC,breakdown_value ASC)GROUP BY breakdown_value- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)+ ORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)WHERE isNotNull(breakdown_value)GROUP BY breakdown_valueORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC@@ -317,7 +317,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -351,7 +351,7 @@ORDER BY day_start ASC,breakdown_value ASC)GROUP BY breakdown_value- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)+ ORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)WHERE isNotNull(breakdown_value)GROUP BY breakdown_valueORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC@@ -373,7 +373,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -407,7 +407,7 @@ORDER BY day_start ASC,breakdown_value ASC)GROUP BY breakdown_value- ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)+ ORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)WHERE isNotNull(breakdown_value)GROUP BY breakdown_valueORDER BY if(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 2, if(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC@@ -429,7 +429,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -492,7 +492,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -555,7 +555,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -601,7 +601,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -647,7 +647,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -693,7 +693,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -1060,7 +1060,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(e.`$session_id_uuid`, e__session.session_id_v7)- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'session start'), ifNull(greater(e__session.`$session_duration`, 12.0), 0))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'session start'), greater(e__session.`$session_duration`, 12.0))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -1128,7 +1128,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(e.`$session_id_uuid`, e__session.session_id_v7)- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, '$autocapture'), ifNull(less(e__session.`$session_duration`, 30.0), 0))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, '$autocapture'), less(e__session.`$session_duration`, 30.0))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -1165,7 +1165,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(e.`$session_id_uuid`, e__session.session_id_v7)- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'session start'), ifNull(greater(e__session.`$session_duration`, 500.0), 0))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), equals(e.event, 'session start'), greater(e__session.`$session_duration`, 500.0))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)diff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambrindex d2c11d603cec..df46761c394b 100644--- a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambr+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends.ambr@@ -133,7 +133,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -280,7 +280,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -334,7 +334,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -380,7 +380,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -426,7 +426,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -472,7 +472,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-22 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -517,7 +517,7 @@# name: TestTrends.test_breakdown_weekly_active_users_aggregated'''SELECT sum(total) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -551,12 +551,12 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-11 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-11 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-11 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestamp,e.actor_id,breakdown_valueORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-11 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-11 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-11 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-11 23:59:59', 'UTC'))))GROUP BY breakdown_value)GROUP BY breakdown_valueORDER BY breakdown_value ASC)@@ -658,7 +658,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -708,11 +708,11 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestamp,breakdown_valueORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')))))GROUP BY day_start,breakdown_valueORDER BY day_start ASC,@@ -740,7 +740,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -803,7 +803,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -876,7 +876,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -929,7 +929,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -982,7 +982,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -1035,7 +1035,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -1397,7 +1397,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -1445,11 +1445,11 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(30)), assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(30))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(30))))GROUP BY d.timestamp,breakdown_valueORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')))))GROUP BY day_start,breakdown_valueORDER BY day_start ASC,@@ -1477,7 +1477,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -1525,11 +1525,11 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(30)), assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(30))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(30))))GROUP BY d.timestamp,breakdown_value_1ORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')))))GROUP BY day_start,breakdown_value_1ORDER BY day_start ASC,@@ -1744,7 +1744,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -2426,10 +2426,10 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-29 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestampORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-29 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')))))GROUP BY day_startORDER BY day_start ASC)ORDER BY arraySum(total) DESC@@ -2482,7 +2482,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-29 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-29 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-05 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -3300,7 +3300,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-07-01 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -3365,7 +3365,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-07-01 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -3509,7 +3509,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -3572,7 +3572,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -3654,10 +3654,10 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(30)), assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(30))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(30))))GROUP BY d.timestampORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')))))GROUP BY day_startORDER BY day_start ASC)ORDER BY arraySum(total) DESC@@ -3698,10 +3698,10 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestampORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')))))GROUP BY day_startORDER BY day_start ASC)ORDER BY arraySum(total) DESC@@ -3723,7 +3723,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-24 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2019-12-31 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -4021,7 +4021,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -4314,7 +4314,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -4374,7 +4374,7 @@# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown'''SELECT sum(total) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -4425,7 +4425,7 @@# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown.1'''SELECT sum(total) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -4476,7 +4476,7 @@# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown.2'''SELECT sum(total) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -4527,7 +4527,7 @@# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown.3'''SELECT sum(total) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -4926,7 +4926,7 @@# name: TestTrends.test_trends_count_per_user_average_aggregated_with_event_property_breakdown_with_sampling'''SELECT sum(total) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -5556,7 +5556,7 @@# name: TestTrends.test_trends_person_breakdown_with_session_property_single_aggregate_math_and_breakdown'''SELECT sum(total) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -5624,7 +5624,7 @@# name: TestTrends.test_trends_person_breakdown_with_session_property_single_aggregate_math_and_breakdown.1'''SELECT sum(total) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 26), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 26), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT count AS total,breakdown_value AS breakdown_value,@@ -5868,7 +5868,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfWeek(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), 0), toIntervalWeek(number)), range(0, plus(coalesce(dateDiff('week', toStartOfWeek(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), 0), toStartOfWeek(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), 0))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -5928,7 +5928,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -5988,7 +5988,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfWeek(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), 0), toIntervalWeek(number)), range(0, plus(coalesce(dateDiff('week', toStartOfWeek(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), 0), toStartOfWeek(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), 0))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -6048,7 +6048,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- arrayMap(i -> if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_value+ arrayMap(i -> if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', i), breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2019-12-28 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-04 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -6127,10 +6127,10 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestampORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-08 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')))))GROUP BY day_startORDER BY day_start ASC)ORDER BY arraySum(total) DESC@@ -6254,11 +6254,11 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-11 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestamp,e.actor_idORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-11 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-11 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC'))))LIMIT 50000 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -6295,11 +6295,11 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestamp,e.actor_idORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC'))))LIMIT 50000 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -6336,11 +6336,11 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestamp,e.actor_idORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-18 23:59:59', 'UTC'))))LIMIT 50000 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -6385,10 +6385,10 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestampORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-08 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-19 23:59:59', 'UTC')))))GROUP BY day_startORDER BY day_start ASC)ORDER BY arraySum(total) DESC@@ -6544,10 +6544,10 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestampFROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestampORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-12 23:59:59', 'UTC')))))GROUP BY day_startORDER BY day_start ASC)ORDER BY arraySum(total) DESC@@ -6654,10 +6654,10 @@CROSS JOIN(SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 17:00:00', 'UTC')), toIntervalHour(1)), toIntervalHour(numbers.number)) AS timestampFROM numbers(dateDiff('hour', minus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 06:00:00', 'UTC')), toIntervalHour(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2020-01-09 17:00:00', 'UTC')))) AS numbers) AS d- WHERE and(ifNull(lessOrEquals(e.timestamp, d.timestamp), 0), ifNull(greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))), 0))+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))GROUP BY d.timestampORDER BY d.timestamp ASC)- WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 06:00:00', 'UTC')), toIntervalHour(1))), 0), ifNull(lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-09 17:00:00', 'UTC'))), 0)))+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-01-09 06:00:00', 'UTC')), toIntervalHour(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2020-01-09 17:00:00', 'UTC')))))GROUP BY day_startORDER BY day_start ASC)ORDER BY arraySum(total) DESCdiff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends_data_warehouse_query.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends_data_warehouse_query.ambrindex 4578c61527c1..f47747f83989 100644--- a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends_data_warehouse_query.ambr+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_trends_data_warehouse_query.ambr@@ -3,7 +3,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2023-01-07 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -73,7 +73,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2023-01-07 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -148,7 +148,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2023-01-07 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -200,7 +200,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2023-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2023-01-07 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -513,7 +513,7 @@(SELECT posthog_test_test_table_1.id AS id,posthog_test_test_table_1.prop_1 AS e__person__posthog_test_test_table_1___prop_1FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql.datawarehouse.trendquery/posthog_test_test_table_1/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `prop_1` String, `prop_2` String, `created` DateTime64(3, \'UTC\')') AS posthog_test_test_table_1) AS e__person__posthog_test_test_table_1 ON equals(e__person.e__person___properties___email, e__person__posthog_test_test_table_1.e__person__posthog_test_test_table_1___prop_1)- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2022-12-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2023-01-07 23:59:59', 'UTC'))), equals(e.event, '$pageview'), ifNull(equals(e__person__posthog_test_test_table_1.id, 'false'), 0))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2022-12-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2023-01-07 23:59:59', 'UTC'))), equals(e.event, '$pageview'), equals(e__person__posthog_test_test_table_1.id, 'false'))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)diff --git a/posthog/hogql_queries/test/__snapshots__/test_session_profile_query.ambr b/posthog/hogql_queries/test/__snapshots__/test_session_profile_query.ambrindex 8adfc2394cfc..9eb7eb925988 100644--- a/posthog/hogql_queries/test/__snapshots__/test_session_profile_query.ambr+++ b/posthog/hogql_queries/test/__snapshots__/test_session_profile_query.ambr@@ -28,7 +28,7 @@GROUP BYraw_sessions_v3.session_id_v7) AS sessionsWHERE- ifNull(equals(sessions.session_id, %(hogql_val_77)s), 0)+ equals(sessions.session_id, %(hogql_val_77)s)LIMIT 1'''# ---@@ -55,7 +55,7 @@GROUP BYraw_sessions.session_id_v7) AS sessionsWHERE- and(ifNull(greaterOrEquals(sessions.`$start_timestamp`, parseDateTime64BestEffort(%(hogql_val_10)s, 6, %(hogql_val_11)s)), 0), ifNull(lessOrEquals(sessions.`$start_timestamp`, parseDateTime64BestEffort(%(hogql_val_12)s, 6, %(hogql_val_13)s)), 0), ifNull(equals(sessions.session_id, %(hogql_val_14)s), 0))+ and(greaterOrEquals(sessions.`$start_timestamp`, parseDateTime64BestEffort(%(hogql_val_10)s, 6, %(hogql_val_11)s)), lessOrEquals(sessions.`$start_timestamp`, parseDateTime64BestEffort(%(hogql_val_12)s, 6, %(hogql_val_13)s)), equals(sessions.session_id, %(hogql_val_14)s))LIMIT 1'''# ---diff --git a/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr b/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambrindex 9ea89a08daa5..59d8f91490d6 100644--- a/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr+++ b/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr@@ -31,7 +31,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -79,7 +79,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -125,7 +125,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -171,7 +171,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY __person_lookup.properties___email ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -217,7 +217,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -253,7 +253,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -355,7 +355,7 @@WHERE and(globalIn(sessions.session_id,(SELECT DISTINCT events.`$session_id` AS `$session_id`FROM events- WHERE and(equals(events.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://example.com/pricing'), 0), greater(events.timestamp, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'))))), ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(equals(events.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://example.com/pricing'), 0), greater(events.timestamp, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'))))), less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -401,7 +401,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(equals(__person_lookup.properties___email, '[email protected]'), 0), ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(ifNull(equals(__person_lookup.properties___email, '[email protected]'), 0), less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -447,7 +447,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(ilike(__person_lookup.properties___email, '%alice%'), 0), ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(ifNull(ilike(__person_lookup.properties___email, '%alice%'), 0), less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -494,7 +494,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(equals(__person_lookup.properties___name, 'Person alice'), 0), ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(ifNull(equals(__person_lookup.properties___name, 'Person alice'), 0), less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -523,7 +523,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(greaterOrEquals(sessions.`$session_duration`, 0.0), 0), ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(greaterOrEquals(sessions.`$session_duration`, 0.0), less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -571,7 +571,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id)) DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -621,7 +621,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -667,7 +667,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -715,7 +715,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -763,7 +763,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id)) ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -809,7 +809,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -855,7 +855,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -911,7 +911,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -941,7 +941,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.`$start_timestamp` DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -990,7 +990,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -1019,7 +1019,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -1067,7 +1067,7 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -1103,7 +1103,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-03 23:59:59.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-02 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-03 23:59:59.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-02 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-03 23:59:59.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-02 00:00:00.000000', 6, 'UTC')))ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -1211,7 +1211,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASCLIMIT 3OFFSET 1 SETTINGS readonly=2,@@ -1239,7 +1239,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 15:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 15:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 15:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))GROUP BY sessions.distinct_idORDER BY count() DESCLIMIT 101@@ -1268,7 +1268,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 15:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 15:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 15:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.`$start_timestamp` ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -1300,7 +1300,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.`$start_timestamp` DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -1329,7 +1329,7 @@FROM raw_sessionsWHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC'), toIntervalDay(3))))GROUP BY raw_sessions.session_id_v7) AS sessions- WHERE and(ifNull(greater(sessions.`$session_duration`, 300), 0), ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')), 0))+ WHERE and(greater(sessions.`$session_duration`, 300), less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))ORDER BY sessions.session_id ASCLIMIT 101OFFSET 0 SETTINGS readonly=2,diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex 1785462be684..5a92e9c8f2aa 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -5650,7 +5650,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE and(ifNull(equals(console_logs_log_entries.level, 'info'), 0), ilike(toString(console_logs_log_entries.message), '%message 5%')))))+ WHERE and(equals(console_logs_log_entries.level, 'info'), ilike(toString(console_logs_log_entries.message), '%message 5%')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -5866,7 +5866,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'error'), 0))))+ WHERE equals(console_logs_log_entries.level, 'error'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -5914,7 +5914,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -5962,7 +5962,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -6010,7 +6010,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'warn'), 0))))+ WHERE equals(console_logs_log_entries.level, 'warn'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -6058,7 +6058,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'warn'), 0))))+ WHERE equals(console_logs_log_entries.level, 'warn'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -6106,7 +6106,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -6202,7 +6202,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -7578,7 +7578,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE and(ifNull(equals(console_logs_log_entries.level, 'warn'), 0), ifNull(equals(console_logs_log_entries.message, 'random'), 0)))))+ WHERE and(equals(console_logs_log_entries.level, 'warn'), equals(console_logs_log_entries.message, 'random')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -7626,7 +7626,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE and(ifNull(equals(console_logs_log_entries.level, 'info'), 0), ifNull(equals(console_logs_log_entries.message, 'random'), 0)))))+ WHERE and(equals(console_logs_log_entries.level, 'info'), equals(console_logs_log_entries.message, 'random')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -7674,7 +7674,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'warn'), 0))))+ WHERE equals(console_logs_log_entries.level, 'warn'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -7722,7 +7722,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.message, 'random'), 0))))+ WHERE equals(console_logs_log_entries.message, 'random'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -7770,7 +7770,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE or(ifNull(equals(console_logs_log_entries.level, 'warn'), 0), ifNull(equals(console_logs_log_entries.message, 'random'), 0)))))+ WHERE or(equals(console_logs_log_entries.level, 'warn'), equals(console_logs_log_entries.message, 'random')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13364,7 +13364,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE and(ifNull(equals(console_logs_log_entries.level, 'info'), 0), ilike(toString(console_logs_log_entries.message), '%message 5%')))))+ WHERE and(equals(console_logs_log_entries.level, 'info'), ilike(toString(console_logs_log_entries.message), '%message 5%')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13580,7 +13580,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'error'), 0))))+ WHERE equals(console_logs_log_entries.level, 'error'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13628,7 +13628,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13676,7 +13676,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13724,7 +13724,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'warn'), 0))))+ WHERE equals(console_logs_log_entries.level, 'warn'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13772,7 +13772,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'warn'), 0))))+ WHERE equals(console_logs_log_entries.level, 'warn'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13820,7 +13820,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -13916,7 +13916,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'info'), 0))))+ WHERE equals(console_logs_log_entries.level, 'info'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-01-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -15292,7 +15292,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE and(ifNull(equals(console_logs_log_entries.level, 'warn'), 0), ifNull(equals(console_logs_log_entries.message, 'random'), 0)))))+ WHERE and(equals(console_logs_log_entries.level, 'warn'), equals(console_logs_log_entries.message, 'random')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -15340,7 +15340,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE and(ifNull(equals(console_logs_log_entries.level, 'info'), 0), ifNull(equals(console_logs_log_entries.message, 'random'), 0)))))+ WHERE and(equals(console_logs_log_entries.level, 'info'), equals(console_logs_log_entries.message, 'random')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -15388,7 +15388,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS levelFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.level, 'warn'), 0))))+ WHERE equals(console_logs_log_entries.level, 'warn'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -15436,7 +15436,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE ifNull(equals(console_logs_log_entries.message, 'random'), 0))))+ WHERE equals(console_logs_log_entries.message, 'random'))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -15484,7 +15484,7 @@(SELECT log_entries.log_source_id AS log_source_id, log_entries.level AS level, log_entries.message AS messageFROM log_entriesWHERE and(equals(log_entries.team_id, 99999), equals(log_entries.log_source, 'session_replay'))) AS console_logs_log_entries- WHERE or(ifNull(equals(console_logs_log_entries.level, 'warn'), 0), ifNull(equals(console_logs_log_entries.message, 'random'), 0)))))+ WHERE or(equals(console_logs_log_entries.level, 'warn'), equals(console_logs_log_entries.message, 'random')))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambrindex a7a22a3f7307..16965eb11020 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr@@ -58,7 +58,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_1 ON equals(cohort_1.person_id, pdi.person_id)- WHERE or(ifNull(equals(cohort_0.matched, 1), 0), ifNull(equals(cohort_1.matched, 1), 0)))))+ WHERE or(equals(cohort_0.matched, 1), equals(cohort_1.matched, 1)))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -180,7 +180,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0))))+ WHERE equals(cohort_0.matched, 1))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -352,7 +352,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0))))+ WHERE equals(cohort_0.matched, 1))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -423,7 +423,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0)))))+ WHERE equals(cohort_0.matched, 1)))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -484,7 +484,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0)))))+ WHERE equals(cohort_0.matched, 1)))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -548,7 +548,7 @@(SELECT person_static_cohort.person_id AS person_id, 1 AS matchedFROM person_static_cohortWHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0))))+ WHERE equals(cohort_0.matched, 1))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -656,7 +656,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0))))+ WHERE equals(cohort_0.matched, 1))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -1247,7 +1247,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0))))+ WHERE equals(cohort_0.matched, 1))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,@@ -1365,7 +1365,7 @@(SELECT cohortpeople.person_id AS person_id, 1 AS matchedFROM cohortpeopleWHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))) AS cohort_0 ON equals(cohort_0.person_id, pdi.person_id)- WHERE ifNull(equals(cohort_0.matched, 1), 0))))+ WHERE equals(cohort_0.matched, 1))))GROUP BY s.session_idHAVING and(greaterOrEquals(expiry_time, toDateTime64('2021-08-21 20:00:00.000000', 6, 'UTC')), equals(max(s.is_deleted), 0))ORDER BY start_time DESC,diff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambrindex 2b1b699829e2..900b71ea0ece 100644--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambr+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambr@@ -33,7 +33,7 @@WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(events.`mat_$exception_issue_id`, 'UUID')), '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))GROUP BY breakdown_property,breakdown_value))- WHERE ifNull(lessOrEquals(row_number, 3), 0)+ WHERE lessOrEquals(row_number, 3)ORDER BY breakdown_property ASC,count DESCLIMIT 100 SETTINGS readonly=2,@@ -84,7 +84,7 @@WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(events.`mat_$exception_issue_id`, 'UUID')), '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))GROUP BY breakdown_property,breakdown_value))- WHERE ifNull(lessOrEquals(row_number, 3), 0)+ WHERE lessOrEquals(row_number, 3)ORDER BY breakdown_property ASC,count DESCLIMIT 100 SETTINGS readonly=2,@@ -135,7 +135,7 @@WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(events.`mat_$exception_issue_id`, 'UUID')), '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))GROUP BY breakdown_property,breakdown_value))- WHERE ifNull(lessOrEquals(row_number, 3), 0)+ WHERE lessOrEquals(row_number, 3)ORDER BY breakdown_property ASC,count DESCLIMIT 100 SETTINGS readonly=2,@@ -186,7 +186,7 @@WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(if(not(empty(events__exception_issue_override.issue_id)), events__exception_issue_override.issue_id, accurateCastOrNull(events.`mat_$exception_issue_id`, 'UUID')), '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))GROUP BY breakdown_property,breakdown_value))- WHERE ifNull(lessOrEquals(row_number, 3), 0)+ WHERE lessOrEquals(row_number, 3)ORDER BY breakdown_property ASC,count DESCLIMIT 100 SETTINGS readonly=2,diff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambrindex eafd186ecd53..821d04bd847d 100644--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambr+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambr@@ -645,7 +645,7 @@WHERE and(equals(system__error_tracking_issue_assignments.team_id, 99999), in(system__error_tracking_issue_assignments.issue_id,(SELECT issue_ids.issue_id AS issue_idFROM issue_ids)))) AS assignment ON equals(assignment.issue_id, issues.id)- WHERE ifNull(greaterOrEquals(fp.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0)+ WHERE greaterOrEquals(fp.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC'))ORDER BY last_seen DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -729,7 +729,7 @@WHERE and(equals(system__error_tracking_issue_assignments.team_id, 99999), in(system__error_tracking_issue_assignments.issue_id,(SELECT issue_ids.issue_id AS issue_idFROM issue_ids)))) AS assignment ON equals(assignment.issue_id, issues.id)- WHERE ifNull(less(fp.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC')), 0)+ WHERE less(fp.first_seen, parseDateTime64BestEffort('2020-01-10T10:11:00+00:00', 6, 'UTC'))ORDER BY last_seen DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -1262,7 +1262,7 @@WHERE and(equals(system__error_tracking_issue_assignments.team_id, 99999), in(system__error_tracking_issue_assignments.issue_id,(SELECT issue_ids.issue_id AS issue_idFROM issue_ids)))) AS assignment ON equals(assignment.issue_id, issues.id)- WHERE ifNull(equals(issues.name, 'TypeError'), 0)+ WHERE equals(issues.name, 'TypeError')ORDER BY last_seen DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -2255,7 +2255,7 @@WHERE and(equals(system__error_tracking_issue_assignments.team_id, 99999), in(system__error_tracking_issue_assignments.issue_id,(SELECT issue_ids.issue_id AS issue_idFROM issue_ids)))) AS assignment ON equals(assignment.issue_id, issues.id)- WHERE ifNull(equals(issues.status, 'active'), 0)+ WHERE equals(issues.status, 'active')ORDER BY last_seen DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,@@ -2339,7 +2339,7 @@WHERE and(equals(system__error_tracking_issue_assignments.team_id, 99999), in(system__error_tracking_issue_assignments.issue_id,(SELECT issue_ids.issue_id AS issue_idFROM issue_ids)))) AS assignment ON equals(assignment.issue_id, issues.id)- WHERE ifNull(equals(issues.status, 'resolved'), 0)+ WHERE equals(issues.status, 'resolved')ORDER BY last_seen DESCLIMIT 101OFFSET 0 SETTINGS readonly=2,diff --git a/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_trends_query_runner.ambr b/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_trends_query_runner.ambrindex 66d902aa1127..446aae87911a 100644--- a/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_trends_query_runner.ambr+++ b/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_trends_query_runner.ambr@@ -3,7 +3,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)@@ -55,7 +55,7 @@'''SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayFill(x -> ifNull(greater(x, 0), 0), arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex 689e1ed98006..376973588531 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -14,7 +14,7 @@WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.team_id, 99999), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'group'), ''), 'null'), '^"|"$', ''), tuple('0', '1', '2', '3'))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE and(ifNull(equals(persons.team_id, 99999), 0), in(persons.properties___group, tuple('0', '1', '2', '3')))+ WHERE and(equals(persons.team_id, 99999), in(persons.properties___group, tuple('0', '1', '2', '3')))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -53,7 +53,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.team_id, 99999), 0), ifNull(equals(groups.index, 0), 0), ifNull(equals(groups.key, 'special-workspace'), 0))+ WHERE and(equals(groups.team_id, 99999), equals(groups.index, 0), equals(groups.key, 'special-workspace'))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -89,7 +89,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.team_id, 99999), 0), ifNull(equals(groups.index, 0), 0), ifNull(ilike(groups.key, '%org:%'), 0))+ WHERE and(equals(groups.team_id, 99999), equals(groups.index, 0), ilike(groups.key, '%org:%'))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -117,7 +117,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.team_id, 99999), 0), ifNull(equals(groups.index, 0), 0), in(groups.properties___industry, tuple('0', '1', '2', '3')))+ WHERE and(equals(groups.team_id, 99999), equals(groups.index, 0), in(groups.properties___industry, tuple('0', '1', '2', '3')))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -154,7 +154,7 @@WHERE equals(groups.team_id, 99999)GROUP BY groups.group_type_index,groups.group_key) AS groups- WHERE and(ifNull(equals(groups.team_id, 99999), 0), ifNull(equals(groups.index, 0), 0), and(in(groups.properties___industry, tuple('0', '1', '2', '3', '4')), in(groups.properties___industry, tuple('2', '3', '4', '5', '6'))))+ WHERE and(equals(groups.team_id, 99999), equals(groups.index, 0), and(in(groups.properties___industry, tuple('0', '1', '2', '3', '4')), in(groups.properties___industry, tuple('2', '3', '4', '5', '6'))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -218,13 +218,13 @@WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE and(ifNull(equals(persons.team_id, 99999), 0), and(in(persons.id,- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0)))), in(persons.id,- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))))))+ WHERE and(equals(persons.team_id, 99999), and(in(persons.id,+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0)))), in(persons.id,+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -269,10 +269,10 @@WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999)))), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'group'), ''), 'null'), '^"|"$', ''), tuple('1', '2', '4', '5', '6'))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE and(ifNull(equals(persons.team_id, 99999), 0), and(in(persons.id,- (SELECT person_static_cohort.person_id AS person_id- FROM person_static_cohort- WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999)))), in(persons.properties___group, tuple('1', '2', '4', '5', '6'))))+ WHERE and(equals(persons.team_id, 99999), and(in(persons.id,+ (SELECT person_static_cohort.person_id AS person_id+ FROM person_static_cohort+ WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999)))), in(persons.properties___group, tuple('1', '2', '4', '5', '6'))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -329,13 +329,13 @@WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE and(ifNull(equals(persons.team_id, 99999), 0), and(in(persons.id,- (SELECT person_static_cohort.person_id AS person_id- FROM person_static_cohort- WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999)))), in(persons.id,- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))))))+ WHERE and(equals(persons.team_id, 99999), and(in(persons.id,+ (SELECT person_static_cohort.person_id AS person_id+ FROM person_static_cohort+ WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999)))), in(persons.id,+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -365,7 +365,7 @@WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.team_id, 99999), or(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'group'), ''), 'null'), '^"|"$', ''), 'none'), 0), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'group'), ''), 'null'), '^"|"$', ''), tuple('1', '2', '3')))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE and(ifNull(equals(persons.team_id, 99999), 0), or(ifNull(equals(persons.properties___group, 'none'), 0), in(persons.properties___group, tuple('1', '2', '3'))))+ WHERE and(equals(persons.team_id, 99999), or(ifNull(equals(persons.properties___group, 'none'), 0), in(persons.properties___group, tuple('1', '2', '3'))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -419,10 +419,10 @@WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0))))))))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons- WHERE and(ifNull(equals(persons.team_id, 99999), 0), in(persons.id,- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0)))))+ WHERE and(equals(persons.team_id, 99999), in(persons.id,+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999), equals(cohortpeople.version, 0)))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,diff --git a/products/marketing_analytics/backend/hogql_queries/test_adapters.py b/products/marketing_analytics/backend/hogql_queries/test_adapters.pyindex ae69caaf1b13..e456d3b52fcc 100644--- a/products/marketing_analytics/backend/hogql_queries/test_adapters.py+++ b/products/marketing_analytics/backend/hogql_queries/test_adapters.py@@ -3,7 +3,7 @@ from collections.abc import Callablefrom dataclasses import dataclass, replacefrom datetime import datetimefrom pathlib import Path-from typing import ClassVar, Union+from typing import ClassVar, Union, castimport pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin@@ -2609,11 +2609,14 @@ class TestMarketingAnalyticsAdapters(ClickhouseTestMixin, BaseTest):# ================================================================@parameterized.expand(- [- ("simple_column", "campaign_name", ast.Field),- ("constant_source", "const:linkedin", ast.Constant),- ("constant_currency", "const:USD", ast.Constant),- ]+ cast(+ list[tuple[str, str, type[ast.Expr]]],+ [+ ("simple_column", "campaign_name", ast.Field),+ ("constant_source", "const:linkedin", ast.Constant),+ ("constant_currency", "const:USD", ast.Constant),+ ],+ ))def test_resolve_field_or_constant(self, _name, field_value, expected_type):table = self._create_mock_table("test_table", "aws")diff --git a/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr b/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambrindex 0a382a4a3bc1..4a6d94a06272 100644--- a/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr+++ b/products/product_analytics/backend/api/test/__snapshots__/test_insight.ambr@@ -243,7 +243,7 @@/* user_id:0 request:_snapshot_ */SELECT groupArray(1)(date)[1] AS date,arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,- if(ifNull(ifNull(greaterOrEquals(row_number, 25), 0), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_valueFROM(SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)diff --git a/products/product_analytics/backend/hogql_queries/paths/test/__snapshots__/test_paths_query_runner_ee.ambr b/products/product_analytics/backend/hogql_queries/paths/test/__snapshots__/test_paths_query_runner_ee.ambrindex b10016d177cc..806cfa5e8103 100644--- a/products/product_analytics/backend/hogql_queries/paths/test/__snapshots__/test_paths_query_runner_ee.ambr+++ b/products/product_analytics/backend/hogql_queries/paths/test/__snapshots__/test_paths_query_runner_ee.ambr@@ -1158,8 +1158,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(path_dropoff_key, '2_step two'), 0), ifNull(equals(path_dropoff_key, path_key), isNull(path_dropoff_key)- and isNull(path_key)))+ WHERE and(equals(path_dropoff_key, '2_step two'), equals(path_dropoff_key, path_key))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -1280,7 +1279,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE ifNull(equals(path_key, '2_step two'), 0)+ WHERE equals(path_key, '2_step two')GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -1522,8 +1521,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(path_dropoff_key, '3_step three'), 0), ifNull(equals(path_dropoff_key, path_key), isNull(path_dropoff_key)- and isNull(path_key)))+ WHERE and(equals(path_dropoff_key, '3_step three'), equals(path_dropoff_key, path_key))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -1644,7 +1642,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE ifNull(equals(path_key, '3_step three'), 0)+ WHERE equals(path_key, '3_step three')GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -1886,8 +1884,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(path_dropoff_key, '4_step four'), 0), ifNull(equals(path_dropoff_key, path_key), isNull(path_dropoff_key)- and isNull(path_key)))+ WHERE and(equals(path_dropoff_key, '4_step four'), equals(path_dropoff_key, path_key))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -2008,7 +2005,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE ifNull(equals(path_key, '4_step four'), 0)+ WHERE equals(path_key, '4_step four')GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -2348,7 +2345,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE ifNull(equals(path_key, '2_/2'), 0)+ WHERE equals(path_key, '2_/2')GROUP BY person_id) AS sourceINNER JOIN(SELECT tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1) AS created_at,@@ -2381,7 +2378,7 @@GROUP BY person_id) ARRAYJOIN session_paths AS path_time_tuple, arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple, arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE ifNull(equals(path_key, '2_/2'), 0)+ WHERE equals(path_key, '2_/2')GROUP BY person_id) AS source)))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, source.actor_id)@@ -2530,8 +2527,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(path_dropoff_key, '2_/2'), 0), ifNull(equals(path_dropoff_key, path_key), isNull(path_dropoff_key)- and isNull(path_key)))+ WHERE and(equals(path_dropoff_key, '2_/2'), equals(path_dropoff_key, path_key))GROUP BY person_id) AS sourceINNER JOIN(SELECT tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1) AS created_at,@@ -2564,8 +2560,7 @@GROUP BY person_id) ARRAYJOIN session_paths AS path_time_tuple, arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple, arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(path_dropoff_key, '2_/2'), 0), ifNull(equals(path_dropoff_key, path_key), isNull(path_dropoff_key)- and isNull(path_key)))+ WHERE and(equals(path_dropoff_key, '2_/2'), equals(path_dropoff_key, path_key))GROUP BY person_id) AS source)))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, source.actor_id)@@ -2690,8 +2685,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(path_dropoff_key, '3_/3'), 0), ifNull(equals(path_dropoff_key, path_key), isNull(path_dropoff_key)- and isNull(path_key)))+ WHERE and(equals(path_dropoff_key, '3_/3'), equals(path_dropoff_key, path_key))GROUP BY person_id) AS sourceINNER JOIN(SELECT tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1) AS created_at,@@ -2724,8 +2718,7 @@GROUP BY person_id) ARRAYJOIN session_paths AS path_time_tuple, arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple, arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(path_dropoff_key, '3_/3'), 0), ifNull(equals(path_dropoff_key, path_key), isNull(path_dropoff_key)- and isNull(path_key)))+ WHERE and(equals(path_dropoff_key, '3_/3'), equals(path_dropoff_key, path_key))GROUP BY person_id) AS source)))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, source.actor_id)@@ -2874,7 +2867,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE ifNull(equals(path_key, '2_/2'), 0)+ WHERE equals(path_key, '2_/2')GROUP BY person_id) AS sourceINNER JOIN(SELECT tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1) AS created_at,@@ -2907,7 +2900,7 @@GROUP BY person_id) ARRAYJOIN session_paths AS path_time_tuple, arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple, arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE ifNull(equals(path_key, '2_/2'), 0)+ WHERE equals(path_key, '2_/2')GROUP BY person_id) AS source)))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons ON equals(persons.id, source.actor_id)@@ -3208,8 +3201,8 @@arrayEnumerate(limited_path_timings) AS event_in_session_indexWHERE and(ifNull(greater(start_target_index,0), 0), ifNull(greater(end_target_index,- 0), 0)))) WHERE ifNull(equals(path_key,- '2_/2'), 0)+ 0), 0)))) WHERE equals(path_key,+ '2_/2')GROUP BY person_id) AS sourceINNER JOIN (SELECT tupleElement(argMax(tuple(toTimeZone(person.created_at,@@ -3467,8 +3460,8 @@arrayEnumerate(limited_path_timings) AS event_in_session_indexWHERE and(ifNull(greater(start_target_index,0), 0), ifNull(greater(end_target_index,- 0), 0)))) WHERE ifNull(equals(path_key,- '2_/2'), 0)+ 0), 0)))) WHERE equals(path_key,+ '2_/2')GROUP BY person_id) AS source)))GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at,@@ -3806,7 +3799,7 @@JOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_indexWHERE and(ifNull(greater(start_target_index, 0), 0), ifNull(greater(end_target_index, 0), 0))))- WHERE and(ifNull(equals(last_path_key, '1_/5'), 0), ifNull(equals(path_key, '2_/about'), 0))+ WHERE and(ifNull(equals(last_path_key, '1_/5'), 0), equals(path_key, '2_/about'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -4028,7 +4021,7 @@JOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_indexWHERE and(ifNull(greater(start_target_index, 0), 0), ifNull(greater(end_target_index, 0), 0))))- WHERE and(ifNull(equals(last_path_key, '3_...'), 0), ifNull(equals(path_key, '4_/5'), 0))+ WHERE and(ifNull(equals(last_path_key, '3_...'), 0), equals(path_key, '4_/5'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -4411,7 +4404,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(last_path_key, '1_/1'), 0), ifNull(equals(path_key, '2_/2'), 0))+ WHERE and(ifNull(equals(last_path_key, '1_/1'), 0), equals(path_key, '2_/2'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -4532,7 +4525,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(last_path_key, '2_/2'), 0), ifNull(equals(path_key, '3_/3'), 0))+ WHERE and(ifNull(equals(last_path_key, '2_/2'), 0), equals(path_key, '3_/3'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -4740,7 +4733,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(last_path_key, '2_/2'), 0), ifNull(equals(path_key, '3_/3'), 0))+ WHERE and(ifNull(equals(last_path_key, '2_/2'), 0), equals(path_key, '3_/3'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -4948,7 +4941,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(last_path_key, '1_/1'), 0), ifNull(equals(path_key, '2_/2'), 0))+ WHERE and(ifNull(equals(last_path_key, '1_/1'), 0), equals(path_key, '2_/2'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -5069,7 +5062,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(last_path_key, '2_/2'), 0), ifNull(equals(path_key, '3_/3'), 0))+ WHERE and(ifNull(equals(last_path_key, '2_/2'), 0), equals(path_key, '3_/3'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101@@ -5190,7 +5183,7 @@arrayEnumerate(session_paths) AS session_index) ARRAYJOIN limited_path_timings AS joined_path_tuple,arrayEnumerate(limited_path_timings) AS event_in_session_index))- WHERE and(ifNull(equals(last_path_key, '3_/3'), 0), ifNull(equals(path_key, '4_/4'), 0))+ WHERE and(ifNull(equals(last_path_key, '3_/3'), 0), equals(path_key, '4_/4'))GROUP BY person_id) AS sourceORDER BY source.id ASCLIMIT 101diff --git a/products/product_analytics/backend/hogql_queries/stickiness/test/__snapshots__/test_stickiness_query_runner.ambr b/products/product_analytics/backend/hogql_queries/stickiness/test/__snapshots__/test_stickiness_query_runner.ambrindex aa259fa96150..3dfefe64cb77 100644--- a/products/product_analytics/backend/hogql_queries/stickiness/test/__snapshots__/test_stickiness_query_runner.ambr+++ b/products/product_analytics/backend/hogql_queries/stickiness/test/__snapshots__/test_stickiness_query_runner.ambr@@ -21,7 +21,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(greaterOrEquals(num_intervals, 1), 0)+ WHERE greaterOrEquals(num_intervals, 1)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -58,7 +58,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(greaterOrEquals(num_intervals, 2), 0)+ WHERE greaterOrEquals(num_intervals, 2)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -95,7 +95,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(greaterOrEquals(num_intervals, 3), 0)+ WHERE greaterOrEquals(num_intervals, 3)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -132,7 +132,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(equals(num_intervals, 1), 0)+ WHERE equals(num_intervals, 1)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -169,7 +169,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(equals(num_intervals, 2), 0)+ WHERE equals(num_intervals, 2)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -206,7 +206,7 @@start_of_intervalHAVING greater(count(), 0))GROUP BY aggregation_target)- WHERE ifNull(equals(num_intervals, 3), 0)+ WHERE equals(num_intervals, 3)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,diff --git a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_gross_revenue_query_runner.ambr b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_gross_revenue_query_runner.ambrindex 834422fc5806..f166279f24dc 100644--- a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_gross_revenue_query_runner.ambr+++ b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_gross_revenue_query_runner.ambr@@ -353,7 +353,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -559,7 +559,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -615,7 +615,7 @@GROUP BY child_meta.customer_id) AS resolved ON equals(resolved.customer_id, outer.id)) AS innerORDER BY timestamp DESCLIMIT 1 BY id) AS revenue_analytics_customer ON equals(revenue_analytics_revenue_item.customer_id, revenue_analytics_customer.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), equals(revenue_analytics_customer.country, 'US'))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_customer.country, 'US'))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -766,7 +766,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -917,7 +917,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -1132,7 +1132,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1193,7 +1193,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -1358,7 +1358,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -1509,7 +1509,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -1660,7 +1660,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -1811,7 +1811,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -1963,7 +1963,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -2128,7 +2128,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -2279,7 +2279,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -2444,7 +2444,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), equals(revenue_analytics_product.name, 'Product C'))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_product.name, 'Product C'))GROUP BY breakdown_by,period_startORDER BY amount DESC,@@ -2609,7 +2609,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), equals(revenue_analytics_product.name, 'Product C'))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), equals(revenue_analytics_product.name, 'Product C'))GROUP BY breakdown_by,period_startORDER BY amount DESC,diff --git a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_metrics_query_runner.ambr b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_metrics_query_runner.ambrindex fea4d12a0c5a..454c8b3638e1 100644--- a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_metrics_query_runner.ambr+++ b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_metrics_query_runner.ambr@@ -6,7 +6,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -30,7 +30,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -113,7 +113,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -202,7 +202,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -226,7 +226,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -310,7 +310,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -445,60 +445,60 @@# name: TestRevenueAnalyticsMetricsQueryRunner.test_with_country_filter'''SELECT subquery.breakdown_by AS breakdown_by,- subquery.period_start AS period_start,- sum(subquery.subscription_count) AS subscription_count,- sum(subquery.new_subscription_count) AS new_subscription_count,- sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id,- ifNull(greaterOrEquals(subquery.subscription_count,- 1), 0)) AS customer_count,- countIf(subquery.customer_id,- subquery.is_new_customer) AS new_customer_count,- countIf(subquery.customer_id,- subquery.is_churned_customer) AS churned_customer_count,- ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count,- 0)), 0,- divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0,- 'Decimal64(10)')) AS arpu,- multiIf(equals(customer_count,- 0), accurateCastOrNull(0,- 'Decimal64(10)'), equals(churned_customer_count,- 0), NULL,- divideDecimal(arpu,- accurateCastOrNull(divide(churned_customer_count,- customer_count), 'Decimal64(10)'))) AS ltv+ subquery.period_start AS period_start,+ sum(subquery.subscription_count) AS subscription_count,+ sum(subquery.new_subscription_count) AS new_subscription_count,+ sum(subquery.churned_subscription_count) AS churned_subscription_count,+ countIf(subquery.customer_id,+ greaterOrEquals(subquery.subscription_count,+ 1)) AS customer_count,+ countIf(subquery.customer_id,+ subquery.is_new_customer) AS new_customer_count,+ countIf(subquery.customer_id,+ subquery.is_churned_customer) AS churned_customer_count,+ ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count,+ 0)), 0,+ divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0,+ 'Decimal64(10)')) AS arpu,+ multiIf(equals(customer_count,+ 0), accurateCastOrNull(0,+ 'Decimal64(10)'), equals(churned_customer_count,+ 0), NULL,+ divideDecimal(arpu,+ accurateCastOrNull(divide(churned_customer_count,+ customer_count), 'Decimal64(10)'))) AS ltvFROM (SELECT revenue_analytics_subscription.source_label AS breakdown_by,- revenue_analytics_subscription.customer_id AS customer_id,- toStartOfMonth(toDateTime(arrayJoin(['2024-11-01 00:00:00', '2024-12-01 00:00:00', '2025-01-01 00:00:00', '2025-02-01 00:00:00', '2025-03-01 00:00:00', '2025-04-01 00:00:00', '2025-05-01 00:00:00']), 'UTC')) AS period_start,- countIf(DISTINCT revenue_analytics_subscription.id,- and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,- 'UTC')), period_start), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), period_start)))) AS subscription_count,- countIf(DISTINCT revenue_analytics_subscription.id,- and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,- 'UTC')), date_add(period_start,- toIntervalMonth(-1))), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), date_add(period_start,- toIntervalMonth(-1)))))) AS prev_subscription_count,- countIf(DISTINCT revenue_analytics_subscription.id,- equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,- 'UTC')), period_start)) AS new_subscription_count,- countIf(DISTINCT revenue_analytics_subscription.id,- equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), date_add(period_start,- toIntervalMonth(-1)))) AS churned_subscription_count,- and(equals(prev_subscription_count,- 0), greater(subscription_count,- 0)) AS is_new_customer,- and(greater(churned_subscription_count,- 0), equals(churned_subscription_count,- prev_subscription_count)) AS is_churned_customer,- sumIf(revenue_analytics_revenue_item.amount,- equals(toStartOfMonth(toTimeZone(revenue_analytics_revenue_item.timestamp,- 'UTC')), period_start)) AS revenue+ revenue_analytics_subscription.customer_id AS customer_id,+ toStartOfMonth(toDateTime(arrayJoin(['2024-11-01 00:00:00', '2024-12-01 00:00:00', '2025-01-01 00:00:00', '2025-02-01 00:00:00', '2025-03-01 00:00:00', '2025-04-01 00:00:00', '2025-05-01 00:00:00']), 'UTC')) AS period_start,+ countIf(DISTINCT revenue_analytics_subscription.id,+ and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,+ 'UTC')), period_start), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), period_start)))) AS subscription_count,+ countIf(DISTINCT revenue_analytics_subscription.id,+ and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,+ 'UTC')), date_add(period_start,+ toIntervalMonth(-1))), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), date_add(period_start,+ toIntervalMonth(-1)))))) AS prev_subscription_count,+ countIf(DISTINCT revenue_analytics_subscription.id,+ equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,+ 'UTC')), period_start)) AS new_subscription_count,+ countIf(DISTINCT revenue_analytics_subscription.id,+ equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), date_add(period_start,+ toIntervalMonth(-1)))) AS churned_subscription_count,+ and(equals(prev_subscription_count,+ 0), greater(subscription_count,+ 0)) AS is_new_customer,+ and(greater(churned_subscription_count,+ 0), equals(churned_subscription_count,+ prev_subscription_count)) AS is_churned_customer,+ sumIf(revenue_analytics_revenue_item.amount,+ equals(toStartOfMonth(toTimeZone(revenue_analytics_revenue_item.timestamp,+ 'UTC')), period_start)) AS revenueFROM (SELECT subscription_id AS id,'revenue_analytics.events.purchase' AS source_label,@@ -507,193 +507,193 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days,- today()), 0), NULL,- max_timestamp) AS ended_at,- NULL AS metadata+ if(greater(max_timestamp_plus_dropoff_days,+ today()), NULL,+ max_timestamp) AS ended_at,+ NULL AS metadataFROM (SELECT events__person.id AS person_id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'subscription'), ''), 'null'), '^"|"$',- '') AS subscription_id,- min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'product'), ''), 'null'), '^"|"$',- '')) AS product_id,- min(toTimeZone(events.timestamp,- 'UTC')) AS min_timestamp,- max(toTimeZone(events.timestamp,- 'UTC')) AS max_timestamp,- addDays(max_timestamp,- 45.0) AS max_timestamp_plus_dropoff_days+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'subscription'), ''), 'null'), '^"|"$',+ '') AS subscription_id,+ min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'product'), ''), 'null'), '^"|"$',+ '')) AS product_id,+ min(toTimeZone(events.timestamp,+ 'UTC')) AS min_timestamp,+ max(toTimeZone(events.timestamp,+ 'UTC')) AS max_timestamp,+ addDays(max_timestamp,+ 45.0) AS max_timestamp_plus_dropoff_daysFROM eventsLEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,person_distinct_id_overrides.distinct_id AS distinct_idFROM person_distinct_id_overridesWHERE equals(person_distinct_id_overrides.team_id,- 99999)+ 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id,- events__override.distinct_id)+ events__override.distinct_id)LEFT JOIN (SELECT person.id AS idFROM personWHERE equals(person.team_id,- 99999)+ 99999)GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at,- 'UTC')), person.version), 1), plus(now64(6,- 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id,- events.person_id), events__person.id)+ 'UTC')), person.version), 1), plus(now64(6,+ 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id,+ events.person_id), events__person.id)WHERE and(equals(events.team_id,- 99999), and(1,- isNotNull(subscription_id)))+ 99999), and(1,+ isNotNull(subscription_id)))GROUP BY subscription_id,person_id)ORDER BY started_at DESC) AS revenue_analytics_subscriptionLEFT JOIN (SELECT toString(events.uuid) AS id,- toString(events.uuid) AS invoice_item_id,- 'revenue_analytics.events.purchase' AS source_label,- toTimeZone(events.timestamp,- 'UTC') AS timestamp,- timestamp AS created_at,- isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'subscription'), ''), 'null'), '^"|"$',- '')) AS is_recurring,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'product'), ''), 'null'), '^"|"$',- '') AS product_id,- toString(if(not(empty(events__override.distinct_id)), events__override.person_id,- events.person_id)) AS customer_id,- events.`$group_0` AS group_0_key,- events.`$group_1` AS group_1_key,- events.`$group_2` AS group_2_key,- events.`$group_3` AS group_3_key,- events.`$group_4` AS group_4_key,- NULL AS invoice_id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'subscription'), ''), 'null'), '^"|"$',- '') AS subscription_id,- toString(events.`$session_id`) AS session_id,- events.event AS event_name,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'coupon'), ''), 'null'), '^"|"$',- '') AS coupon,- coupon AS coupon_id,- upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'currency'), ''), 'null'), '^"|"$',- '')) AS original_currency,- accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'revenue'), ''), 'null'), '^"|"$',- ''), 'Decimal64(10)') AS original_amount,- 1 AS enable_currency_aware_divider,- if(enable_currency_aware_divider,- accurateCastOrNull(1,- 'Decimal64(10)'), accurateCastOrNull(100,- 'Decimal64(10)')) AS currency_aware_divider,- divideDecimal(original_amount,- currency_aware_divider) AS currency_aware_amount,- 'GBP' AS currency,- if(isNull(upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'currency'), ''), 'null'), '^"|"$',- ''))), accurateCastOrNull(currency_aware_amount,- 'Decimal64(10)'), if(equals(upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'currency'), ''), 'null'), '^"|"$',- '')), 'GBP'), toDecimal64(currency_aware_amount,- 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'currency'), ''), 'null'), '^"|"$',- '')), toDate(toTimeZone(events.timestamp,- 'UTC')), toDecimal64(0,- 10)) = 0,- toDecimal64(0,- 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount,- 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'currency'), ''), 'null'), '^"|"$',- '')), toDate(toTimeZone(events.timestamp,- 'UTC')), toDecimal64(0,- 10)) = 0,- toDecimal64(1,- 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,- 'currency'), ''), 'null'), '^"|"$',- '')), toDate(toTimeZone(events.timestamp,- 'UTC')), toDecimal64(0,- 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- 'GBP',- toDate(toTimeZone(events.timestamp,- 'UTC')), toDecimal64(0,- 10)))))) AS amount+ toString(events.uuid) AS invoice_item_id,+ 'revenue_analytics.events.purchase' AS source_label,+ toTimeZone(events.timestamp,+ 'UTC') AS timestamp,+ timestamp AS created_at,+ isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'subscription'), ''), 'null'), '^"|"$',+ '')) AS is_recurring,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'product'), ''), 'null'), '^"|"$',+ '') AS product_id,+ toString(if(not(empty(events__override.distinct_id)), events__override.person_id,+ events.person_id)) AS customer_id,+ events.`$group_0` AS group_0_key,+ events.`$group_1` AS group_1_key,+ events.`$group_2` AS group_2_key,+ events.`$group_3` AS group_3_key,+ events.`$group_4` AS group_4_key,+ NULL AS invoice_id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'subscription'), ''), 'null'), '^"|"$',+ '') AS subscription_id,+ toString(events.`$session_id`) AS session_id,+ events.event AS event_name,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'coupon'), ''), 'null'), '^"|"$',+ '') AS coupon,+ coupon AS coupon_id,+ upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'currency'), ''), 'null'), '^"|"$',+ '')) AS original_currency,+ accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'revenue'), ''), 'null'), '^"|"$',+ ''), 'Decimal64(10)') AS original_amount,+ 1 AS enable_currency_aware_divider,+ if(enable_currency_aware_divider,+ accurateCastOrNull(1,+ 'Decimal64(10)'), accurateCastOrNull(100,+ 'Decimal64(10)')) AS currency_aware_divider,+ divideDecimal(original_amount,+ currency_aware_divider) AS currency_aware_amount,+ 'GBP' AS currency,+ if(isNull(upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'currency'), ''), 'null'), '^"|"$',+ ''))), accurateCastOrNull(currency_aware_amount,+ 'Decimal64(10)'), if(equals(upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'currency'), ''), 'null'), '^"|"$',+ '')), 'GBP'), toDecimal64(currency_aware_amount,+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'currency'), ''), 'null'), '^"|"$',+ '')), toDate(toTimeZone(events.timestamp,+ 'UTC')), toDecimal64(0,+ 10)) = 0,+ toDecimal64(0,+ 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount,+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'currency'), ''), 'null'), '^"|"$',+ '')), toDate(toTimeZone(events.timestamp,+ 'UTC')), toDecimal64(0,+ 10)) = 0,+ toDecimal64(1,+ 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ upper(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties,+ 'currency'), ''), 'null'), '^"|"$',+ '')), toDate(toTimeZone(events.timestamp,+ 'UTC')), toDecimal64(0,+ 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ 'GBP',+ toDate(toTimeZone(events.timestamp,+ 'UTC')), toDecimal64(0,+ 10)))))) AS amountFROM eventsLEFT OUTER JOIN (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,person_distinct_id_overrides.distinct_id AS distinct_idFROM person_distinct_id_overridesWHERE equals(person_distinct_id_overrides.team_id,- 99999)+ 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id,- events__override.distinct_id)+ events__override.distinct_id)WHERE and(equals(events.team_id,- 99999), and(equals(events.event,- 'purchase'), 1,- isNotNull(amount)))+ 99999), and(equals(events.event,+ 'purchase'), 1,+ isNotNull(amount)))ORDER BY timestamp DESC) AS revenue_analytics_revenue_item ON equals(revenue_analytics_subscription.id,- revenue_analytics_revenue_item.subscription_id)+ revenue_analytics_revenue_item.subscription_id)LEFT JOIN (SELECT toString(persons.id) AS id,- 'revenue_analytics.events.purchase' AS source_label,- persons.created_at AS timestamp,- persons.properties___name AS name,- persons.properties___email AS email,- persons.properties___phone AS phone,- persons.properties___address AS address,- persons.properties___metadata AS metadata,- persons.`properties___$geoip_country_name` AS country,- formatDateTime(toStartOfMonth(persons.created_at), '%Y-%m') AS cohort,- NULL AS initial_coupon,- NULL AS initial_coupon_id+ 'revenue_analytics.events.purchase' AS source_label,+ persons.created_at AS timestamp,+ persons.properties___name AS name,+ persons.properties___email AS email,+ persons.properties___phone AS phone,+ persons.properties___address AS address,+ persons.properties___metadata AS metadata,+ persons.`properties___$geoip_country_name` AS country,+ formatDateTime(toStartOfMonth(persons.created_at), '%Y-%m') AS cohort,+ NULL AS initial_coupon,+ NULL AS initial_coupon_idFROM (SELECT person.id AS id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,- 'name'), ''), 'null'), '^"|"$',- '') AS properties___name,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,- 'email'), ''), 'null'), '^"|"$',- '') AS properties___email,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,- 'phone'), ''), 'null'), '^"|"$',- '') AS properties___phone,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,- 'address'), ''), 'null'), '^"|"$',- '') AS properties___address,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,- 'metadata'), ''), 'null'), '^"|"$',- '') AS properties___metadata,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,- '$geoip_country_name'), ''), 'null'), '^"|"$',- '') AS `properties___$geoip_country_name`,- toTimeZone(person.created_at,- 'UTC') AS created_at+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,+ 'name'), ''), 'null'), '^"|"$',+ '') AS properties___name,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,+ 'email'), ''), 'null'), '^"|"$',+ '') AS properties___email,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,+ 'phone'), ''), 'null'), '^"|"$',+ '') AS properties___phone,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,+ 'address'), ''), 'null'), '^"|"$',+ '') AS properties___address,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,+ 'metadata'), ''), 'null'), '^"|"$',+ '') AS properties___metadata,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties,+ '$geoip_country_name'), ''), 'null'), '^"|"$',+ '') AS `properties___$geoip_country_name`,+ toTimeZone(person.created_at,+ 'UTC') AS created_atFROM personWHERE and(equals(person.team_id,- 99999), in(tuple(person.id,- person.version), (+ 99999), in(tuple(person.id,+ person.version), (SELECT person.id AS id,- max(person.version) AS version+ max(person.version) AS versionFROM person WHERE equals(person.team_id,- 99999)+ 99999)GROUP BY person.idHAVING and(equals(argMax(person.is_deleted,- person.version), 0), less(argMax(toTimeZone(person.created_at,- 'UTC'), person.version), plus(now64(6,- 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons+ person.version), 0), less(argMax(toTimeZone(person.created_at,+ 'UTC'), person.version), plus(now64(6,+ 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS personsINNER JOIN (SELECT DISTINCT events__person.id AS person_idFROM events@@ -702,109 +702,109 @@person_distinct_id_overrides.distinct_id AS distinct_idFROM person_distinct_id_overridesWHERE equals(person_distinct_id_overrides.team_id,- 99999)+ 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id,- events__override.distinct_id)+ events__override.distinct_id)LEFT JOIN (SELECT person.id AS idFROM personWHERE equals(person.team_id,- 99999)+ 99999)GROUP BY person.idHAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at,- 'UTC')), person.version), 1), plus(now64(6,- 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id,- events.person_id), events__person.id)+ 'UTC')), person.version), 1), plus(now64(6,+ 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id,+ events.person_id), events__person.id)WHERE equals(events.team_id,- 99999)) AS events ON equals(persons.id,- events.person_id)+ 99999)) AS events ON equals(persons.id,+ events.person_id)ORDER BY persons.created_at DESC) AS revenue_analytics_customer ON equals(revenue_analytics_subscription.customer_id,- revenue_analytics_customer.id)+ revenue_analytics_customer.id)WHERE equals(revenue_analytics_customer.country,- 'US')+ 'US')GROUP BY revenue_analytics_subscription.customer_id,- breakdown_by,- period_start+ breakdown_by,+ period_startORDER BY revenue_analytics_subscription.customer_id ASC,- breakdown_by ASC,- period_start ASC) AS subquery+ breakdown_by ASC,+ period_start ASC) AS subqueryGROUP BY subquery.breakdown_by,- subquery.period_start+ subquery.period_startORDER BY subquery.breakdown_by ASC,- subquery.period_start ASC,- subscription_count DESC,- customer_count DESC+ subquery.period_start ASC,+ subscription_count DESC,+ customer_count DESCLIMIT 10000UNION ALLSELECT subquery.breakdown_by AS breakdown_by,- subquery.period_start AS period_start,- sum(subquery.subscription_count) AS subscription_count,- sum(subquery.new_subscription_count) AS new_subscription_count,- sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id,- ifNull(greaterOrEquals(subquery.subscription_count,- 1), 0)) AS customer_count,- countIf(subquery.customer_id,- subquery.is_new_customer) AS new_customer_count,- countIf(subquery.customer_id,- subquery.is_churned_customer) AS churned_customer_count,- ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count,- 0)), 0,- divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0,- 'Decimal64(10)')) AS arpu,- multiIf(equals(customer_count,- 0), accurateCastOrNull(0,- 'Decimal64(10)'), equals(churned_customer_count,- 0), NULL,- divideDecimal(arpu,- accurateCastOrNull(divide(churned_customer_count,- customer_count), 'Decimal64(10)'))) AS ltv+ subquery.period_start AS period_start,+ sum(subquery.subscription_count) AS subscription_count,+ sum(subquery.new_subscription_count) AS new_subscription_count,+ sum(subquery.churned_subscription_count) AS churned_subscription_count,+ countIf(subquery.customer_id,+ greaterOrEquals(subquery.subscription_count,+ 1)) AS customer_count,+ countIf(subquery.customer_id,+ subquery.is_new_customer) AS new_customer_count,+ countIf(subquery.customer_id,+ subquery.is_churned_customer) AS churned_customer_count,+ ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count,+ 0)), 0,+ divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0,+ 'Decimal64(10)')) AS arpu,+ multiIf(equals(customer_count,+ 0), accurateCastOrNull(0,+ 'Decimal64(10)'), equals(churned_customer_count,+ 0), NULL,+ divideDecimal(arpu,+ accurateCastOrNull(divide(churned_customer_count,+ customer_count), 'Decimal64(10)'))) AS ltvFROM (SELECT revenue_analytics_subscription.source_label AS breakdown_by,- revenue_analytics_subscription.customer_id AS customer_id,- toStartOfMonth(toDateTime(arrayJoin(['2024-11-01 00:00:00', '2024-12-01 00:00:00', '2025-01-01 00:00:00', '2025-02-01 00:00:00', '2025-03-01 00:00:00', '2025-04-01 00:00:00', '2025-05-01 00:00:00']), 'UTC')) AS period_start,- countIf(DISTINCT revenue_analytics_subscription.id,- and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,- 'UTC')), period_start), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), period_start)))) AS subscription_count,- countIf(DISTINCT revenue_analytics_subscription.id,- and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,- 'UTC')), date_add(period_start,- toIntervalMonth(-1))), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), date_add(period_start,- toIntervalMonth(-1)))))) AS prev_subscription_count,- countIf(DISTINCT revenue_analytics_subscription.id,- equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,- 'UTC')), period_start)) AS new_subscription_count,- countIf(DISTINCT revenue_analytics_subscription.id,- equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,- 'UTC')), date_add(period_start,- toIntervalMonth(-1)))) AS churned_subscription_count,- and(equals(prev_subscription_count,- 0), greater(subscription_count,- 0)) AS is_new_customer,- and(greater(churned_subscription_count,- 0), equals(churned_subscription_count,- prev_subscription_count)) AS is_churned_customer,- sumIf(revenue_analytics_revenue_item.amount,- equals(toStartOfMonth(revenue_analytics_revenue_item.timestamp), period_start)) AS revenue+ revenue_analytics_subscription.customer_id AS customer_id,+ toStartOfMonth(toDateTime(arrayJoin(['2024-11-01 00:00:00', '2024-12-01 00:00:00', '2025-01-01 00:00:00', '2025-02-01 00:00:00', '2025-03-01 00:00:00', '2025-04-01 00:00:00', '2025-05-01 00:00:00']), 'UTC')) AS period_start,+ countIf(DISTINCT revenue_analytics_subscription.id,+ and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,+ 'UTC')), period_start), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), period_start)))) AS subscription_count,+ countIf(DISTINCT revenue_analytics_subscription.id,+ and(lessOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,+ 'UTC')), date_add(period_start,+ toIntervalMonth(-1))), or(isNull(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), greaterOrEquals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), date_add(period_start,+ toIntervalMonth(-1)))))) AS prev_subscription_count,+ countIf(DISTINCT revenue_analytics_subscription.id,+ equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.started_at,+ 'UTC')), period_start)) AS new_subscription_count,+ countIf(DISTINCT revenue_analytics_subscription.id,+ equals(toStartOfMonth(toTimeZone(revenue_analytics_subscription.ended_at,+ 'UTC')), date_add(period_start,+ toIntervalMonth(-1)))) AS churned_subscription_count,+ and(equals(prev_subscription_count,+ 0), greater(subscription_count,+ 0)) AS is_new_customer,+ and(greater(churned_subscription_count,+ 0), equals(churned_subscription_count,+ prev_subscription_count)) AS is_churned_customer,+ sumIf(revenue_analytics_revenue_item.amount,+ equals(toStartOfMonth(revenue_analytics_revenue_item.timestamp), period_start)) AS revenueFROM (SELECT posthog_test_stripe_subscription.id AS id,- 'stripe.posthog_test' AS source_label,- JSONExtractString(posthog_test_stripe_subscription.plan,- 'id') AS plan_id,- JSONExtractString(posthog_test_stripe_subscription.plan,- 'product') AS product_id,- posthog_test_stripe_subscription.customer AS customer_id,- posthog_test_stripe_subscription.status AS status,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6,- 'UTC') AS started_at,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6,- 'UTC') AS ended_at,- posthog_test_stripe_subscription.metadata AS metadata+ 'stripe.posthog_test' AS source_label,+ JSONExtractString(posthog_test_stripe_subscription.plan,+ 'id') AS plan_id,+ JSONExtractString(posthog_test_stripe_subscription.plan,+ 'product') AS product_id,+ posthog_test_stripe_subscription.customer AS customer_id,+ posthog_test_stripe_subscription.status AS status,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6,+ 'UTC') AS started_at,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6,+ 'UTC') AS ended_at,+ posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv','object_storage_root_user','object_storage_root_password',@@ -812,113 +812,113 @@'`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS revenue_analytics_subscriptionLEFT JOIN (SELECT if(ifNull(greater(invoice.period_months,- 1), 0), concat(ifNull(toString(invoice.invoice_item_id), ''), '_',- ifNull(toString(invoice.month_index), '')), invoice.invoice_item_id) AS id,- invoice.invoice_item_id AS invoice_item_id,- 'stripe.posthog_test' AS source_label,- addMonths(invoice.timestamp,- invoice.month_index) AS timestamp,- invoice.created_at AS created_at,- ifNull(notEmpty(invoice.subscription_id), 0) AS is_recurring,- invoice.product_id AS product_id,- invoice.customer_id AS customer_id,- NULL AS group_0_key,- NULL AS group_1_key,- NULL AS group_2_key,- NULL AS group_3_key,- NULL AS group_4_key,- invoice.id AS invoice_id,- invoice.subscription_id AS subscription_id,- NULL AS session_id,- NULL AS event_name,- JSONExtractString(invoice.discount,- 'coupon',- 'name') AS coupon,- JSONExtractString(invoice.discount,- 'coupon',- 'id') AS coupon_id,- upper(invoice.currency) AS original_currency,- accurateCastOrNull(invoice.amount_captured,- 'Decimal64(10)') AS original_amount,- in(original_currency,- ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,- if(enable_currency_aware_divider,- accurateCastOrNull(1,- 'Decimal64(10)'), accurateCastOrNull(100,- 'Decimal64(10)')) AS currency_aware_divider,- divideDecimal(original_amount,- currency_aware_divider) AS currency_aware_amount,- 'GBP' AS currency,- divideDecimal(if(equals(original_currency,- currency), toDecimal64(currency_aware_amount,- 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- original_currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10)) = 0,- toDecimal64(0,- 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount,- 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- original_currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10)) = 0,- toDecimal64(1,- 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- original_currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10))))), accurateCastOrNull(invoice.period_months,- 'Decimal64(10)')) AS amount+ 1), 0), concat(ifNull(toString(invoice.invoice_item_id), ''), '_',+ ifNull(toString(invoice.month_index), '')), invoice.invoice_item_id) AS id,+ invoice.invoice_item_id AS invoice_item_id,+ 'stripe.posthog_test' AS source_label,+ addMonths(invoice.timestamp,+ invoice.month_index) AS timestamp,+ invoice.created_at AS created_at,+ ifNull(notEmpty(invoice.subscription_id), 0) AS is_recurring,+ invoice.product_id AS product_id,+ invoice.customer_id AS customer_id,+ NULL AS group_0_key,+ NULL AS group_1_key,+ NULL AS group_2_key,+ NULL AS group_3_key,+ NULL AS group_4_key,+ invoice.id AS invoice_id,+ invoice.subscription_id AS subscription_id,+ NULL AS session_id,+ NULL AS event_name,+ JSONExtractString(invoice.discount,+ 'coupon',+ 'name') AS coupon,+ JSONExtractString(invoice.discount,+ 'coupon',+ 'id') AS coupon_id,+ upper(invoice.currency) AS original_currency,+ accurateCastOrNull(invoice.amount_captured,+ 'Decimal64(10)') AS original_amount,+ in(original_currency,+ ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,+ if(enable_currency_aware_divider,+ accurateCastOrNull(1,+ 'Decimal64(10)'), accurateCastOrNull(100,+ 'Decimal64(10)')) AS currency_aware_divider,+ divideDecimal(original_amount,+ currency_aware_divider) AS currency_aware_amount,+ 'GBP' AS currency,+ divideDecimal(if(equals(original_currency,+ currency), toDecimal64(currency_aware_amount,+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ original_currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10)) = 0,+ toDecimal64(0,+ 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount,+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ original_currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10)) = 0,+ toDecimal64(1,+ 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ original_currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10))))), accurateCastOrNull(invoice.period_months,+ 'Decimal64(10)')) AS amountFROM (SELECT posthog_test_stripe_invoice.id AS id,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,- 'UTC') AS created_at,- posthog_test_stripe_invoice.customer AS customer_id,- posthog_test_stripe_invoice.subscription AS subscription_id,- posthog_test_stripe_invoice.discount AS discount,- arrayJoin(JSONExtractArrayRaw(assumeNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(posthog_test_stripe_invoice.lines,- 'data'), ''), 'null'), '^"|"$',- '')))) AS data,- JSONExtractString(data,- 'id') AS invoice_item_id,- JSONExtractUInt(data,- 'amount') AS amount_before_discount,- coalesce(arraySum(arrayMap(x -> JSONExtractInt(x,- 'amount'), JSONExtractArrayRaw(data,- 'discount_amounts'))), 0) AS discount_amount,- greatest(minus(amount_before_discount,- discount_amount), 0) AS amount_captured,- JSONExtractString(data,- 'currency') AS currency,- JSONExtractString(data,- 'price',- 'product') AS product_id,- fromUnixTimestamp(JSONExtractUInt(data,- 'period',- 'start')) AS period_start,- fromUnixTimestamp(JSONExtractUInt(data,- 'period',- 'end')) AS period_end,- greatest(toInt16(round(divide(dateDiff('day',- ifNull(period_start,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,- 'UTC')), ifNull(period_end,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,- 'UTC'))), 30.44))), 1) AS period_months,- arrayJoin(range(0,- period_months)) AS month_index,- ifNull(period_start,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,- 'UTC')) AS timestamp+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,+ 'UTC') AS created_at,+ posthog_test_stripe_invoice.customer AS customer_id,+ posthog_test_stripe_invoice.subscription AS subscription_id,+ posthog_test_stripe_invoice.discount AS discount,+ arrayJoin(JSONExtractArrayRaw(assumeNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(posthog_test_stripe_invoice.lines,+ 'data'), ''), 'null'), '^"|"$',+ '')))) AS data,+ JSONExtractString(data,+ 'id') AS invoice_item_id,+ JSONExtractUInt(data,+ 'amount') AS amount_before_discount,+ coalesce(arraySum(arrayMap(x -> JSONExtractInt(x,+ 'amount'), JSONExtractArrayRaw(data,+ 'discount_amounts'))), 0) AS discount_amount,+ greatest(minus(amount_before_discount,+ discount_amount), 0) AS amount_captured,+ JSONExtractString(data,+ 'currency') AS currency,+ JSONExtractString(data,+ 'price',+ 'product') AS product_id,+ fromUnixTimestamp(JSONExtractUInt(data,+ 'period',+ 'start')) AS period_start,+ fromUnixTimestamp(JSONExtractUInt(data,+ 'period',+ 'end')) AS period_end,+ greatest(toInt16(round(divide(dateDiff('day',+ ifNull(period_start,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,+ 'UTC')), ifNull(period_end,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,+ 'UTC'))), 30.44))), 1) AS period_months,+ arrayJoin(range(0,+ period_months)) AS month_index,+ ifNull(period_start,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,+ 'UTC')) AS timestampFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv','object_storage_root_user','object_storage_root_password',@@ -927,118 +927,118 @@WHERE posthog_test_stripe_invoice.paid) AS invoiceUNION ALLSELECT posthog_test_stripe_charge.id AS id,- id AS invoice_item_id,- 'stripe.posthog_test' AS source_label,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_charge.created), 6,- 'UTC') AS timestamp,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_charge.created), 6,- 'UTC') AS created_at,- 0 AS is_recurring,- NULL AS product_id,- posthog_test_stripe_charge.customer AS customer_id,- NULL AS group_0_key,- NULL AS group_1_key,- NULL AS group_2_key,- NULL AS group_3_key,- NULL AS group_4_key,- posthog_test_stripe_charge.invoice AS invoice_id,- NULL AS subscription_id,- NULL AS session_id,- NULL AS event_name,- NULL AS coupon,- NULL AS coupon_id,- upper(posthog_test_stripe_charge.currency) AS original_currency,- accurateCastOrNull(posthog_test_stripe_charge.amount_captured,- 'Decimal64(10)') AS original_amount,- in(original_currency,- ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,- if(enable_currency_aware_divider,- accurateCastOrNull(1,- 'Decimal64(10)'), accurateCastOrNull(100,- 'Decimal64(10)')) AS currency_aware_divider,- divideDecimal(original_amount,- currency_aware_divider) AS currency_aware_amount,- 'GBP' AS currency,- if(equals(original_currency,- currency), toDecimal64(currency_aware_amount,- 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- original_currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10)) = 0,- toDecimal64(0,- 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount,- 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- original_currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10)) = 0,- toDecimal64(1,- 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- original_currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,- 'rate',- currency,- toDate(ifNull(timestamp, toDateTime(0,- 'UTC'))), toDecimal64(0,- 10))))) AS amount+ id AS invoice_item_id,+ 'stripe.posthog_test' AS source_label,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_charge.created), 6,+ 'UTC') AS timestamp,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_charge.created), 6,+ 'UTC') AS created_at,+ 0 AS is_recurring,+ NULL AS product_id,+ posthog_test_stripe_charge.customer AS customer_id,+ NULL AS group_0_key,+ NULL AS group_1_key,+ NULL AS group_2_key,+ NULL AS group_3_key,+ NULL AS group_4_key,+ posthog_test_stripe_charge.invoice AS invoice_id,+ NULL AS subscription_id,+ NULL AS session_id,+ NULL AS event_name,+ NULL AS coupon,+ NULL AS coupon_id,+ upper(posthog_test_stripe_charge.currency) AS original_currency,+ accurateCastOrNull(posthog_test_stripe_charge.amount_captured,+ 'Decimal64(10)') AS original_amount,+ in(original_currency,+ ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,+ if(enable_currency_aware_divider,+ accurateCastOrNull(1,+ 'Decimal64(10)'), accurateCastOrNull(100,+ 'Decimal64(10)')) AS currency_aware_divider,+ divideDecimal(original_amount,+ currency_aware_divider) AS currency_aware_amount,+ 'GBP' AS currency,+ if(equals(original_currency,+ currency), toDecimal64(currency_aware_amount,+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ original_currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10)) = 0,+ toDecimal64(0,+ 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount,+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ original_currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10)) = 0,+ toDecimal64(1,+ 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ original_currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,+ 'rate',+ currency,+ toDate(ifNull(timestamp, toDateTime(0,+ 'UTC'))), toDecimal64(0,+ 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv','object_storage_root_user','object_storage_root_password','CSVWithNames','`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status,- 'succeeded'))) AS revenue_analytics_revenue_item ON equals(revenue_analytics_subscription.id,- revenue_analytics_revenue_item.subscription_id)+ 'succeeded'))) AS revenue_analytics_revenue_item ON equals(revenue_analytics_subscription.id,+ revenue_analytics_revenue_item.subscription_id)LEFT JOIN (SELECT inner.id AS id,- inner.source_label AS source_label,- inner.timestamp AS timestamp,- inner.name AS name,- inner.email AS email,- inner.phone AS phone,- inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata,- 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,- '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,- '{}'), k), JSONExtractKeys(ifNull(inner.metadata,- '{}')))), map('posthog_person_distinct_id_source',- 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id,- ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,- '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,- '{}'), k), JSONExtractKeys(ifNull(inner.metadata,- '{}')))), map('posthog_person_distinct_id',- inner.resolved_distinct_id,- 'posthog_person_distinct_id_source',- inner.resolved_source))), inner.metadata)) AS metadata,- inner.country AS country,- inner.cohort AS cohort,- inner.initial_coupon AS initial_coupon,- inner.initial_coupon_id AS initial_coupon_id+ inner.source_label AS source_label,+ inner.timestamp AS timestamp,+ inner.name AS name,+ inner.email AS email,+ inner.phone AS phone,+ inner.address AS address,+ if(notEquals(JSONExtractString(inner.metadata,+ 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,+ '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,+ '{}'), k), JSONExtractKeys(ifNull(inner.metadata,+ '{}')))), map('posthog_person_distinct_id_source',+ 'customer'))), if(notEquals(inner.resolved_distinct_id,+ ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,+ '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,+ '{}'), k), JSONExtractKeys(ifNull(inner.metadata,+ '{}')))), map('posthog_person_distinct_id',+ inner.resolved_distinct_id,+ 'posthog_person_distinct_id_source',+ inner.resolved_source))), inner.metadata)) AS metadata,+ inner.country AS country,+ inner.cohort AS cohort,+ inner.initial_coupon AS initial_coupon,+ inner.initial_coupon_id AS initial_coupon_idFROM (SELECT outer.id AS id,- 'stripe.posthog_test' AS source_label,- parseDateTime64BestEffortOrNull(toString(outer.created), 6,- 'UTC') AS timestamp,- outer.name AS name,- outer.email AS email,- outer.phone AS phone,- outer.address AS address,- outer.metadata AS metadata,- JSONExtractString(address,- 'country') AS country,- cohort_inner.cohort AS cohort,- cohort_inner.initial_coupon AS initial_coupon,- cohort_inner.initial_coupon_id AS initial_coupon_id,- ifNull(resolved.resolved_distinct_id,- '') AS resolved_distinct_id,- ifNull(resolved.resolved_source,- '') AS resolved_source+ 'stripe.posthog_test' AS source_label,+ parseDateTime64BestEffortOrNull(toString(outer.created), 6,+ 'UTC') AS timestamp,+ outer.name AS name,+ outer.email AS email,+ outer.phone AS phone,+ outer.address AS address,+ outer.metadata AS metadata,+ JSONExtractString(address,+ 'country') AS country,+ cohort_inner.cohort AS cohort,+ cohort_inner.initial_coupon AS initial_coupon,+ cohort_inner.initial_coupon_id AS initial_coupon_id,+ ifNull(resolved.resolved_distinct_id,+ '') AS resolved_distinct_id,+ ifNull(resolved.resolved_source,+ '') AS resolved_sourceFROM (SELECT *FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_customers/posthog_test_stripe_customer/*.csv',@@ -1048,96 +1048,96 @@'`id` String, `name` String, `email` String, `phone` String, `address` String, `created` DateTime, `metadata` String')) AS outerLEFT JOIN (SELECT invoice.customer AS customer_id,- formatDateTime(toStartOfMonth(min(parseDateTime64BestEffortOrNull(toString(invoice.created), 6,- 'UTC'))), '%Y-%m') AS cohort,- argMin(JSONExtractString(invoice.discount,- 'coupon',- 'name'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6,- 'UTC')) AS initial_coupon,- argMin(JSONExtractString(invoice.discount,- 'coupon',- 'id'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6,- 'UTC')) AS initial_coupon_id+ formatDateTime(toStartOfMonth(min(parseDateTime64BestEffortOrNull(toString(invoice.created), 6,+ 'UTC'))), '%Y-%m') AS cohort,+ argMin(JSONExtractString(invoice.discount,+ 'coupon',+ 'name'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6,+ 'UTC')) AS initial_coupon,+ argMin(JSONExtractString(invoice.discount,+ 'coupon',+ 'id'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6,+ 'UTC')) AS initial_coupon_idFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv','object_storage_root_user','object_storage_root_password','CSVWithNames','`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS invoiceGROUP BY invoice.customer) AS cohort_inner ON equals(cohort_inner.customer_id,- outer.id)+ outer.id)LEFT JOIN (SELECT child_meta.customer_id AS customer_id,- argMax(child_meta.distinct_id,- child_meta.created_at) AS resolved_distinct_id,- argMax(child_meta.source_ref,- child_meta.created_at) AS resolved_source+ argMax(child_meta.distinct_id,+ child_meta.created_at) AS resolved_distinct_id,+ argMax(child_meta.source_ref,+ child_meta.created_at) AS resolved_sourceFROM (SELECT posthog_test_stripe_subscription.customer AS customer_id,- JSONExtractString(posthog_test_stripe_subscription.metadata,- 'posthog_person_distinct_id') AS distinct_id,- concat('subscription',- '::',- ifNull(toString(posthog_test_stripe_subscription.id), '')) AS source_ref,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6,- 'UTC') AS created_at+ JSONExtractString(posthog_test_stripe_subscription.metadata,+ 'posthog_person_distinct_id') AS distinct_id,+ concat('subscription',+ '::',+ ifNull(toString(posthog_test_stripe_subscription.id), '')) AS source_ref,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6,+ 'UTC') AS created_atFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv','object_storage_root_user','object_storage_root_password','CSVWithNames','`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscriptionWHERE notEquals(JSONExtractString(posthog_test_stripe_subscription.metadata,- 'posthog_person_distinct_id'), '')+ 'posthog_person_distinct_id'), '')UNION ALLSELECT posthog_test_stripe_charge.customer AS customer_id,- JSONExtractString(posthog_test_stripe_charge.metadata,- 'posthog_person_distinct_id') AS distinct_id,- concat('charge',- '::',- ifNull(toString(posthog_test_stripe_charge.id), '')) AS source_ref,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_charge.created), 6,- 'UTC') AS created_at+ JSONExtractString(posthog_test_stripe_charge.metadata,+ 'posthog_person_distinct_id') AS distinct_id,+ concat('charge',+ '::',+ ifNull(toString(posthog_test_stripe_charge.id), '')) AS source_ref,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_charge.created), 6,+ 'UTC') AS created_atFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv','object_storage_root_user','object_storage_root_password','CSVWithNames','`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE notEquals(JSONExtractString(posthog_test_stripe_charge.metadata,- 'posthog_person_distinct_id'), '')+ 'posthog_person_distinct_id'), '')UNION ALLSELECT posthog_test_stripe_invoice.customer AS customer_id,- JSONExtractString(posthog_test_stripe_invoice.metadata,- 'posthog_person_distinct_id') AS distinct_id,- concat('invoice',- '::',- ifNull(toString(posthog_test_stripe_invoice.id), '')) AS source_ref,- parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,- 'UTC') AS created_at+ JSONExtractString(posthog_test_stripe_invoice.metadata,+ 'posthog_person_distinct_id') AS distinct_id,+ concat('invoice',+ '::',+ ifNull(toString(posthog_test_stripe_invoice.id), '')) AS source_ref,+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,+ 'UTC') AS created_atFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv','object_storage_root_user','object_storage_root_password','CSVWithNames','`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS posthog_test_stripe_invoiceWHERE notEquals(JSONExtractString(posthog_test_stripe_invoice.metadata,- 'posthog_person_distinct_id'), '')) AS child_meta+ 'posthog_person_distinct_id'), '')) AS child_metaGROUP BY child_meta.customer_id) AS resolved ON equals(resolved.customer_id,- outer.id)) AS inner+ outer.id)) AS innerORDER BY timestamp DESCLIMIT 1 BY id) AS revenue_analytics_customer ON equals(revenue_analytics_subscription.customer_id,- revenue_analytics_customer.id)+ revenue_analytics_customer.id)WHERE equals(revenue_analytics_customer.country,- 'US')+ 'US')GROUP BY revenue_analytics_subscription.customer_id,- breakdown_by,- period_start+ breakdown_by,+ period_startORDER BY revenue_analytics_subscription.customer_id ASC,- breakdown_by ASC,- period_start ASC) AS subquery+ breakdown_by ASC,+ period_start ASC) AS subqueryGROUP BY subquery.breakdown_by,- subquery.period_start+ subquery.period_startORDER BY subquery.breakdown_by ASC,- subquery.period_start ASC,- subscription_count DESC,- customer_count DESC+ subquery.period_start ASC,+ subscription_count DESC,+ customer_count DESCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -1160,7 +1160,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -1184,7 +1184,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -1267,7 +1267,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -1405,7 +1405,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -1429,7 +1429,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -1512,7 +1512,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -1650,7 +1650,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -1674,7 +1674,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -1766,7 +1766,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -1909,7 +1909,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -1933,7 +1933,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -2016,7 +2016,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2154,7 +2154,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2178,7 +2178,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -2261,7 +2261,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2399,7 +2399,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2423,7 +2423,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -2507,7 +2507,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2646,7 +2646,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2670,7 +2670,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -2754,7 +2754,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2893,7 +2893,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -2917,7 +2917,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -3001,7 +3001,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3140,7 +3140,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3164,7 +3164,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -3248,7 +3248,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3387,7 +3387,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3411,7 +3411,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -3505,7 +3505,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3650,7 +3650,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3674,7 +3674,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -3767,7 +3767,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3911,7 +3911,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,@@ -3935,7 +3935,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -4028,7 +4028,7 @@sum(subquery.subscription_count) AS subscription_count,sum(subquery.new_subscription_count) AS new_subscription_count,sum(subquery.churned_subscription_count) AS churned_subscription_count,- countIf(subquery.customer_id, ifNull(greaterOrEquals(subquery.subscription_count, 1), 0)) AS customer_count,+ countIf(subquery.customer_id, greaterOrEquals(subquery.subscription_count, 1)) AS customer_count,countIf(subquery.customer_id, subquery.is_new_customer) AS new_customer_count,countIf(subquery.customer_id, subquery.is_churned_customer) AS churned_customer_count,ifNull(accurateCastOrNull(if(or(isNull(customer_count), equals(customer_count, 0)), 0, divide(sum(subquery.revenue), customer_count)), 'Decimal64(10)'), accurateCastOrNull(0, 'Decimal64(10)')) AS arpu,diff --git a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_mrr_query_runner.ambr b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_mrr_query_runner.ambrindex 6efd76e35e80..15ed14f17794 100644--- a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_mrr_query_runner.ambr+++ b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_mrr_query_runner.ambr@@ -32,7 +32,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -51,13 +51,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -86,13 +86,13 @@SELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (SELECT '' AS id, '' AS source_label, '' AS plan_id, '' AS product_id, '' AS customer_id, '' AS status, toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS started_at, toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS ended_at, '' AS metadata- WHERE 0) AS subscription WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE 0) AS subscription WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -131,7 +131,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -150,13 +150,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -193,13 +193,13 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -238,7 +238,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -284,13 +284,13 @@HAVING and(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), less(tupleElement(argMax(tuple(toTimeZone(person.created_at, 'UTC')), person.version), 1), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)WHERE equals(events.team_id, 99999)) AS events ON equals(persons.id, events.person_id)ORDER BY persons.created_at DESC) AS revenue_analytics_customer ON equals(revenue_analytics_revenue_item.customer_id, revenue_analytics_customer.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), equals(revenue_analytics_customer.country, 'US'))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_customer.country, 'US'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -329,7 +329,7 @@FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscriptionWHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_itemLEFT JOIN (- SELECT inner.id AS id, inner.source_label AS source_label, inner.timestamp AS timestamp, inner.name AS name, inner.email AS email, inner.phone AS phone, inner.address AS address, if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata, inner.country AS country, inner.cohort AS cohort, inner.initial_coupon AS initial_coupon, inner.initial_coupon_id AS initial_coupon_id+ SELECT inner.id AS id, inner.source_label AS source_label, inner.timestamp AS timestamp, inner.name AS name, inner.email AS email, inner.phone AS phone, inner.address AS address, if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata, inner.country AS country, inner.cohort AS cohort, inner.initial_coupon AS initial_coupon, inner.initial_coupon_id AS initial_coupon_idFROM (SELECT outer.id AS id, 'stripe.posthog_test' AS source_label, parseDateTime64BestEffortOrNull(toString(outer.created), 6, 'UTC') AS timestamp, outer.name AS name, outer.email AS email, outer.phone AS phone, outer.address AS address, outer.metadata AS metadata, JSONExtractString(address, 'country') AS country, cohort_inner.cohort AS cohort, cohort_inner.initial_coupon AS initial_coupon, cohort_inner.initial_coupon_id AS initial_coupon_id, ifNull(resolved.resolved_distinct_id, '') AS resolved_distinct_id, ifNull(resolved.resolved_source, '') AS resolved_sourceFROM (@@ -356,13 +356,13 @@GROUP BY child_meta.customer_id) AS resolved ON equals(resolved.customer_id, outer.id)) AS innerORDER BY timestamp DESCLIMIT 1 BY id) AS revenue_analytics_customer ON equals(revenue_analytics_revenue_item.customer_id, revenue_analytics_customer.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), equals(revenue_analytics_customer.country, 'US'))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_customer.country, 'US'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -401,7 +401,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -420,13 +420,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -463,13 +463,13 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -508,7 +508,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -527,11 +527,11 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -568,11 +568,11 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2025-02-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -611,7 +611,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -664,13 +664,13 @@FROM eventsWHERE equals(events.team_id, 99999))ORDER BY id ASC) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -709,7 +709,7 @@FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscriptionWHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_itemLEFT JOIN (- SELECT inner.id AS id, inner.source_label AS source_label, inner.timestamp AS timestamp, inner.name AS name, inner.email AS email, inner.phone AS phone, inner.address AS address, if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata, inner.country AS country, inner.cohort AS cohort, inner.initial_coupon AS initial_coupon, inner.initial_coupon_id AS initial_coupon_id+ SELECT inner.id AS id, inner.source_label AS source_label, inner.timestamp AS timestamp, inner.name AS name, inner.email AS email, inner.phone AS phone, inner.address AS address, if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata, inner.country AS country, inner.cohort AS cohort, inner.initial_coupon AS initial_coupon, inner.initial_coupon_id AS initial_coupon_idFROM (SELECT outer.id AS id, 'stripe.posthog_test' AS source_label, parseDateTime64BestEffortOrNull(toString(outer.created), 6, 'UTC') AS timestamp, outer.name AS name, outer.email AS email, outer.phone AS phone, outer.address AS address, outer.metadata AS metadata, JSONExtractString(address, 'country') AS country, cohort_inner.cohort AS cohort, cohort_inner.initial_coupon AS initial_coupon, cohort_inner.initial_coupon_id AS initial_coupon_id, ifNull(resolved.resolved_distinct_id, '') AS resolved_distinct_id, ifNull(resolved.resolved_source, '') AS resolved_sourceFROM (@@ -739,13 +739,13 @@LEFT JOIN (SELECT posthog_test_stripe_product.id AS id, 'stripe.posthog_test' AS source_label, posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -784,7 +784,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -810,13 +810,13 @@SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '') AS product_idFROM events WHERE equals(events.team_id, 99999))ORDER BY id ASC) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -856,13 +856,13 @@WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_itemLEFT JOIN (SELECT posthog_test_stripe_product.id AS id, 'stripe.posthog_test' AS source_label, posthog_test_stripe_product.name AS name- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -901,7 +901,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -920,13 +920,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -963,13 +963,13 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2026-05-01 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -1008,7 +1008,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -1027,13 +1027,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -1070,13 +1070,13 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-12-01 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2024-12-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -1115,7 +1115,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -1134,13 +1134,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -1177,13 +1177,13 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -1222,7 +1222,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -1241,13 +1241,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -1284,13 +1284,13 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -1329,7 +1329,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -1355,13 +1355,13 @@SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '') AS product_idFROM events WHERE equals(events.team_id, 99999))ORDER BY id ASC) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -1401,13 +1401,13 @@WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_itemLEFT JOIN (SELECT posthog_test_stripe_product.id AS id, 'stripe.posthog_test' AS source_label, posthog_test_stripe_product.name AS name- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -1446,7 +1446,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -1465,13 +1465,13 @@WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))GROUP BY subscription_id, person_id)ORDER BY started_at DESC) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -1508,13 +1508,13 @@FROM (SELECT posthog_test_stripe_subscription.id AS id, 'stripe.posthog_test' AS source_label, JSONExtractString(posthog_test_stripe_subscription.plan, 'id') AS plan_id, JSONExtractString(posthog_test_stripe_subscription.plan, 'product') AS product_id, posthog_test_stripe_subscription.customer AS customer_id, posthog_test_stripe_subscription.status AS status, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.created), 6, 'UTC') AS started_at, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_subscription.ended_at), 6, 'UTC') AS ended_at, posthog_test_stripe_subscription.metadata AS metadataFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_subscriptions/posthog_test_stripe_subscription/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `plan` String, `status` String, `created` DateTime, `customer` String, `ended_at` DateTime, `metadata` String') AS posthog_test_stripe_subscription) AS subscription- WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))) AS subquery+ WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_item WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -1553,7 +1553,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -1579,13 +1579,13 @@SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '') AS product_idFROM events WHERE equals(events.team_id, 99999))ORDER BY id ASC) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), equals(revenue_analytics_product.name, 'Product C'))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_product.name, 'Product C'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -1625,13 +1625,13 @@WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_itemLEFT JOIN (SELECT posthog_test_stripe_product.id AS id, 'stripe.posthog_test' AS source_label, posthog_test_stripe_product.name AS name- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), equals(revenue_analytics_product.name, 'Product C'))) AS subquery+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_product.name, 'Product C'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0@@ -1670,7 +1670,7 @@UNION ALLSELECT NULL AS id, NULL AS invoice_item_id, subscription.source_label AS source_label, toTimeZone(subscription.ended_at, 'UTC') AS timestamp, timestamp AS created_at, 1 AS is_recurring, subscription.product_id AS product_id, subscription.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, NULL AS invoice_id, subscription.id AS subscription_id, NULL AS session_id, NULL AS event_name, NULL AS coupon, NULL AS coupon_id, NULL AS original_currency, accurateCastOrNull(0, 'Decimal64(10)') AS original_amount, 0 AS enable_currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_divider, accurateCastOrNull(0, 'Decimal64(10)') AS currency_aware_amount, NULL AS currency, accurateCastOrNull(0, 'Decimal64(10)') AS amountFROM (- SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp) AS ended_at, NULL AS metadata+ SELECT subscription_id AS id, 'revenue_analytics.events.purchase' AS source_label, NULL AS plan_id, product_id AS product_id, toString(person_id) AS customer_id, NULL AS status, min_timestamp AS started_at, if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp) AS ended_at, NULL AS metadataFROM (SELECT events__person.id AS person_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription'), ''), 'null'), '^"|"$', '') AS subscription_id, min(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '')) AS product_id, min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp, max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp, addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_daysFROM events@@ -1696,13 +1696,13 @@SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'product'), ''), 'null'), '^"|"$', '') AS product_idFROM events WHERE equals(events.team_id, 99999))ORDER BY id ASC) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), equals(revenue_analytics_product.name, 'Product C'))) AS subquery+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_product.name, 'Product C'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000@@ -1742,13 +1742,13 @@WHERE and(greaterOrEquals(toTimeZone(subscription.ended_at, 'UTC'), addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(toTimeZone(subscription.ended_at, 'UTC'), assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))) AS revenue_analytics_revenue_itemLEFT JOIN (SELECT posthog_test_stripe_product.id AS id, 'stripe.posthog_test' AS source_label, posthog_test_stripe_product.name AS name- FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.is_recurring, 1), 0), equals(revenue_analytics_product.name, 'Product C'))) AS subquery+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id) WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, addDays(assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC')), -60)), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.is_recurring, 1), equals(revenue_analytics_product.name, 'Product C'))) AS subqueryGROUP BY breakdown_by, customer_id, subscription_id, day) AS grouped_by_dayGROUP BY breakdown_by, customer_id, subscription_id) AS map_query) AS mrr_per_day_subqueryWHERE or(ifNull(equals(mrr_per_day_subquery.date, toLastDayOfMonth(mrr_per_day_subquery.date)), isNull(mrr_per_day_subquery.date)- and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), ifNull(equals(mrr_per_day_subquery.row_number, 1), 0))+ and isNull(toLastDayOfMonth(mrr_per_day_subquery.date))), equals(mrr_per_day_subquery.row_number, 1))ORDER BY mrr_per_day_subquery.breakdown_by ASC, mrr_per_day_subquery.customer_id ASC, mrr_per_day_subquery.subscription_id ASC, mrr_per_day_subquery.date ASC)- WHERE and(ifNull(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(date, assumeNotNull(toDateTime('2024-11-30 00:00:00', 'UTC'))), lessOrEquals(date, assumeNotNull(toDateTime('2025-05-31 23:59:59', 'UTC'))))GROUP BY breakdown_by, dateORDER BY date ASC, total DESC, breakdown_by ASCLIMIT 10000 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0diff --git a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_overview_query_runner.ambr b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_overview_query_runner.ambrindex b0ac62226348..0fe04e44c8f2 100644--- a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_overview_query_runner.ambr+++ b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_overview_query_runner.ambr@@ -125,7 +125,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'America/Los_Angeles'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'America/Los_Angeles'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'America/Los_Angeles'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'America/Los_Angeles'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'America/Los_Angeles'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'America/Los_Angeles'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'America/Los_Angeles'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'America/Los_Angeles')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -267,7 +267,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -502,7 +502,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -644,7 +644,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-01-02 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-01-02 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -786,7 +786,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0)))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -928,7 +928,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0)))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase')))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -1070,7 +1070,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0)))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase')))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -1226,7 +1226,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_product.name, 'Product C')))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_product.name, 'Product C')))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -1382,7 +1382,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_product.name, 'Product D')))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_product.name, 'Product D')))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -1579,7 +1579,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1629,7 +1629,7 @@GROUP BY child_meta.customer_id) AS resolved ON equals(resolved.customer_id, outer.id)) AS innerORDER BY timestamp DESCLIMIT 1 BY id) AS revenue_analytics_customer ON equals(revenue_analytics_revenue_item.customer_id, revenue_analytics_customer.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_customer.country, 'US')))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), equals(revenue_analytics_customer.country, 'US')))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,@@ -1785,7 +1785,7 @@'stripe.posthog_test' AS source_label,posthog_test_stripe_product.name AS nameFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.overview_query_runner.stripe_products/posthog_test_stripe_product/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `type` String, `active` UInt8, `images` String, `object` String, `created` DateTime, `features` String, `livemode` UInt8, `metadata` String, `tax_code` String, `attributes` String, `updated_at` DateTime, `description` String, `default_price_id` String') AS posthog_test_stripe_product) AS revenue_analytics_product ON equals(revenue_analytics_revenue_item.product_id, revenue_analytics_product.id)- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), 0)), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), in(revenue_analytics_product.name, tuple('Product A', 'Product D'))))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-30 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC')))), ifNull(greater(revenue_analytics_revenue_item.amount, accurateCastOrNull(0, 'Decimal64(10)')), 0), in(revenue_analytics_product.name, tuple('Product A', 'Product D'))))LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,readonly=2,max_execution_time=60,diff --git a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_top_customers_query_runner.ambr b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_top_customers_query_runner.ambrindex 806f1243ca5c..42d4032ec93d 100644--- a/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_top_customers_query_runner.ambr+++ b/products/revenue_analytics/backend/hogql_queries/test/__snapshots__/test_revenue_analytics_top_customers_query_runner.ambr@@ -364,7 +364,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'non-existent-source'))GROUP BY customer_id,monthORDER BY amount DESC@@ -377,7 +377,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -632,7 +632,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))))GROUP BY customer_id,monthORDER BY amount DESC@@ -645,7 +645,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -900,7 +900,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-02-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-03-04 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-02-03 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-03-04 23:59:59', 'UTC'))))GROUP BY customer_id,monthORDER BY amount DESC@@ -913,7 +913,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1170,7 +1170,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))))GROUP BY customer_id,monthORDER BY amount DESC@@ -1183,7 +1183,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1440,7 +1440,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))))GROUP BY customer_id,monthORDER BY amount DESC@@ -1453,7 +1453,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1708,7 +1708,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))GROUP BY customer_id,monthORDER BY amount DESC@@ -1721,7 +1721,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -1977,7 +1977,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))GROUP BY customer_id,monthORDER BY amount DESC@@ -1990,7 +1990,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -2245,7 +2245,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC'))), 0)), ifNull(equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'), 0))+ WHERE and(and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2023-11-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59', 'UTC')))), equals(revenue_analytics_revenue_item.source_label, 'revenue_analytics.events.purchase'))GROUP BY customer_id,monthORDER BY amount DESC@@ -2258,7 +2258,7 @@inner.email AS email,inner.phone AS phone,inner.address AS address,- if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(ifNull(notEquals(inner.resolved_distinct_id, ''), 1), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,+ if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata,inner.country AS country,inner.cohort AS cohort,inner.initial_coupon AS initial_coupon,@@ -2513,7 +2513,7 @@if(equals(original_currency, currency), toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(0, 10), multiplyDecimal(divideDecimal(toDecimal64(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal64(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))) AS amountFROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.top_customers_query_runner.stripe_charges/posthog_test_stripe_charge/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `paid` Int8, `amount` Int64, `object` String, `source` String, `status` String, `created` DateTime, `invoice` String, `outcome` String, `captured` Int8, `currency` String, `customer` String, `disputed` Int8, `livemode` Int8, `metadata` String, `refunded` Int8, `description` String, `receipt_url` String, `failure_code` String, `fraud_details` String, `radar_options` String, `receipt_email` String, `payment_intent` String, `payment_method` String, `amount_captured` Int64, `amount_refunded` Int64, `billing_details` String, `failure_message` String, `balance_transaction` String, `statement_descriptor` String, `payment_method_details` String, `calculated_statement_descriptor` String') AS posthog_test_stripe_chargeWHERE and(or(isNull(invoice_id), empty(invoice_id)), equals(posthog_test_stripe_charge.status, 'succeeded'))) AS revenue_analytics_revenue_item- WHERE and(ifNull(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))), 0))+ WHERE and(greaterOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2015-01-01 00:00:00', 'UTC'))), lessOrEquals(revenue_analytics_revenue_item.timestamp, assumeNotNull(toDateTime('2025-04-21 23:59:59', 'UTC'))))GROUP BY customer_id,monthORDER BY amount DESCdiff --git a/products/revenue_analytics/backend/views/test/__snapshots__/test_mrr_views.ambr b/products/revenue_analytics/backend/views/test/__snapshots__/test_mrr_views.ambrindex 9b218b19d721..b7bc3796f9e8 100644--- a/products/revenue_analytics/backend/views/test/__snapshots__/test_mrr_views.ambr+++ b/products/revenue_analytics/backend/views/test/__snapshots__/test_mrr_views.ambr@@ -68,7 +68,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,@@ -414,7 +414,7 @@toString(person_id) AS customer_id,NULL AS status,min_timestamp AS started_at,- if(ifNull(greater(max_timestamp_plus_dropoff_days, today()), 0), NULL, max_timestamp_plus_dropoff_days) AS ended_at,+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,NULL AS metadataFROM(SELECT events__person.id AS person_id,diff --git a/products/web_analytics/backend/hogql_queries/events_prefilter.py b/products/web_analytics/backend/hogql_queries/events_prefilter.pyindex 4fbe69c089af..b683fb1581c8 100644--- a/products/web_analytics/backend/hogql_queries/events_prefilter.py+++ b/products/web_analytics/backend/hogql_queries/events_prefilter.py@@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Unionfrom posthog.hogql import astfrom posthog.hogql.constants import LimitContext-from posthog.hogql.database.models import DatabaseField+from posthog.hogql.database.models import DatabaseField, StringDatabaseFieldfrom posthog.hogql.visitor import TraversingVisitorfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator@@ -27,23 +27,57 @@ class _EventsFieldCollector(TraversingVisitor):def visit_field(self, node: ast.Field):field_type = node.typeif isinstance(field_type, ast.PropertyType):- ft = field_type.field_type- table_type = ft.table_type- col_name = ft.name- # Unwrap VirtualTableType (e.g. poe for person properties) to check if this- # property ultimately lives on the events table, and resolve the actual DB- # column name (e.g. "person_properties" instead of "properties")- while isinstance(table_type, ast.VirtualTableType):- db_field = table_type.virtual_table.fields.get(ft.name)- if isinstance(db_field, DatabaseField):- col_name = db_field.name- table_type = table_type.table_type- if table_type == self.events_table_type and len(field_type.chain) >= 1:- self.property_accesses.add((str(field_type.chain[0]), col_name))- field_type = ft- if isinstance(field_type, ast.FieldType) and field_type.table_type == self.events_table_type:+ self._record_property_access(field_type.field_type, str(field_type.chain[0]) if field_type.chain else None)+ field_type = field_type.field_type+ if isinstance(field_type, ast.FieldType) and self._matches_events_table(field_type.table_type):self.fields.add(field_type.name)+ def _matches_events_table(self, table_type: ast.Type | None) -> bool:+ """True when `table_type` is this collector's events-table occurrence.++ Property resolution reads materialized / dmat / property-group columns through a copy of the events table with+ the synthetic column added (the HogQL schema doesn't know those columns), so the reads it rewrote no longer+ compare equal to the occurrence's own type. Treat such an augmented copy of the same table as a match — without+ this, those columns are left out of the prefilter subquery and the outer query fails with UNKNOWN_IDENTIFIER.+ """+ if table_type == self.events_table_type:+ return True+ candidate: ast.Type | None = table_type+ target: ast.Type | None = self.events_table_type+ if isinstance(candidate, ast.TableAliasType) and isinstance(target, ast.TableAliasType):+ if candidate.alias != target.alias:+ return False+ candidate, target = candidate.table_type, target.table_type+ if not isinstance(candidate, ast.TableType) or not isinstance(target, ast.TableType):+ return False+ # An augmented copy is the same table class with the original's fields plus the synthetic ones.+ return type(candidate.table) is type(target.table) and set(target.table.fields).issubset(candidate.table.fields)++ def visit_property_access(self, node: ast.PropertyAccess):+ # After the lowering pass an unmaterialized `properties.$x` read is a `PropertyAccess` over the blob `Field`,+ # not a `PropertyType`. Record the property access so `_resolve_materialized_columns` keeps the `properties`+ # column in the subquery instead of discarding it. `super()` still visits `node.expr` (the blob field).+ super().visit_property_access(node)+ blob_type = node.expr.type+ if isinstance(blob_type, ast.FieldType) and node.keys:+ self._record_property_access(blob_type, str(node.keys[0]))++ def _record_property_access(self, blob_field_type: ast.FieldType, property_name: str | None) -> None:+ """Record a (property, table_column) access on the events table, if this property lives there."""+ if property_name is None:+ return+ table_type = blob_field_type.table_type+ col_name = blob_field_type.name+ # Unwrap VirtualTableType (e.g. poe for person properties) to check if this property ultimately lives on the+ # events table, and resolve the actual DB column name (e.g. "person_properties" instead of "properties").+ while isinstance(table_type, ast.VirtualTableType):+ db_field = table_type.virtual_table.fields.get(blob_field_type.name)+ if isinstance(db_field, DatabaseField):+ col_name = db_field.name+ table_type = table_type.table_type+ if self._matches_events_table(table_type):+ self.property_accesses.add((property_name, col_name))+class EventsPrefilterTransformer(TraversingVisitor):"""Wraps FROM events in a resolved AST with a prefiltered subquery.@@ -117,6 +151,16 @@ class EventsPrefilterTransformer(TraversingVisitor):collector.property_accesses, events_columns, events_table_type)+ # Any collected column the HogQL schema doesn't know (a synthetic materialized / dmat / property-group read+ # built by property resolution) must be registered on the table for the duration of the print, or the+ # subquery's bare SELECT of it won't resolve.+ table = self._get_events_table(events_table_type)+ if table is not None:+ for column in events_columns | mat_column_names:+ if column not in table.fields:+ table.fields[column] = StringDatabaseField(name=column)+ self._temp_schema_fields.append((table, column))+inner_join = ast.JoinExpr(table=join.table, type=events_table_type)subquery = ast.SelectQuery(# Bare fields (no ast.Alias) so ClickHouse column names pass throughdiff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambrindex f455324a193e..2b326a68691e 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr@@ -13,8 +13,8 @@# name: TestExternalClicksTableQueryRunner.test_all_time.1'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -59,8 +59,8 @@# name: TestExternalClicksTableQueryRunner.test_custom_order_by'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -105,8 +105,8 @@# name: TestExternalClicksTableQueryRunner.test_custom_order_by.1'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -151,8 +151,8 @@# name: TestExternalClicksTableQueryRunner.test_dont_filter_test_accounts'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -197,8 +197,8 @@# name: TestExternalClicksTableQueryRunner.test_filter_test_accounts'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -253,8 +253,8 @@# name: TestExternalClicksTableQueryRunner.test_increase_in_users'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-11 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-11 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-11 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-11 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -299,8 +299,8 @@# name: TestExternalClicksTableQueryRunner.test_no_crash_when_no_data'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -345,8 +345,8 @@# name: TestExternalClicksTableQueryRunner.test_path_cleaning'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -391,8 +391,8 @@# name: TestExternalClicksTableQueryRunner.test_path_cleaning.1'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -437,8 +437,8 @@# name: TestExternalClicksTableQueryRunner.test_should_exclude_subdomain_under_root'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -483,8 +483,8 @@# name: TestExternalClicksTableQueryRunner.test_should_exclude_subdomain_with_shared_root'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -529,8 +529,8 @@# name: TestExternalClicksTableQueryRunner.test_strip_query_params'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,@@ -575,8 +575,8 @@# name: TestExternalClicksTableQueryRunner.test_strip_query_params.1'''SELECT url AS `context.columns.url`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,- tuple(sumIf(filtered_click_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, 0)) AS `context.columns.visitors`,+ tuple(sumIf(filtered_click_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))), sumIf(filtered_click_count, 0)) AS `context.columns.clicks`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_click_count,diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_notable_changes.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_notable_changes.ambrindex 9242e8a3bb49..50cd9d192ea0 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_notable_changes.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_notable_changes.ambr@@ -4,17 +4,17 @@SELECT 'Page' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -77,17 +77,17 @@SELECT 'Entry page' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -149,17 +149,17 @@SELECT 'Referrer' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -221,17 +221,17 @@SELECT 'Device' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -294,17 +294,17 @@SELECT 'Browser' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -367,17 +367,17 @@SELECT 'Country' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -440,17 +440,17 @@SELECT 'Channel' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -541,17 +541,17 @@SELECT 'UTM source' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -627,17 +627,17 @@SELECT 'Page' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -700,17 +700,17 @@SELECT 'Entry page' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -772,17 +772,17 @@SELECT 'Referrer' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -844,17 +844,17 @@SELECT 'Device' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -917,17 +917,17 @@SELECT 'Browser' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -990,17 +990,17 @@SELECT 'Country' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1063,17 +1063,17 @@SELECT 'Channel' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1164,17 +1164,17 @@SELECT 'UTM source' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1250,17 +1250,17 @@SELECT 'Page' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1323,17 +1323,17 @@SELECT 'Entry page' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1395,17 +1395,17 @@SELECT 'Referrer' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1467,17 +1467,17 @@SELECT 'Device' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1540,17 +1540,17 @@SELECT 'Browser' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1613,17 +1613,17 @@SELECT 'Country' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1686,17 +1686,17 @@SELECT 'Channel' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,@@ -1787,17 +1787,17 @@SELECT 'UTM source' AS dimension_type,dimension_value AS dimension_value,uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-29 23:59:59',- 'UTC'))), 0))) AS current_visitors,- uniqIf(person_id,- and(ifNull(greaterOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-15 00:00:00',- 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp,- assumeNotNull(toDateTime('2025-01-22 23:59:59',- 'UTC'))), 0))) AS previous_visitors+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-29 23:59:59',+ 'UTC'))))) AS current_visitors,+ uniqIf(person_id,+ and(greaterOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-15 00:00:00',+ 'UTC'))), lessOrEquals(start_timestamp,+ assumeNotNull(toDateTime('2025-01-22 23:59:59',+ 'UTC'))))) AS previous_visitorsFROM (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id,events.person_id)) AS person_id,diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambrindex b6202307e4a6..8b23f94c87ee 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr@@ -4,7 +4,7 @@# ---# name: TestWebGoalsQueryRunner.test_aggregate_function_in_where_error.1'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,uniqIf(web_goals_person_id, 0) AS previous_total_people,'Test Action 1' AS action_name_0,tuple(sum(action_current_count_0), NULL) AS action_total_0,@@ -70,7 +70,7 @@GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.versionHAVING greater(sum(cohortpeople.sign), 0)))), and(equals(events.event, '$pageview'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-input([-_a-zA-Z0-9\\.:"= \\[\\]\\(\\),]*?)?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-btn\\..*?text\\-white([-_a-zA-Z0-9\\.:"= \\[\\]\\(\\),]*?)?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)), and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a([-_a-zA-Z0-9\\.:"= \\[\\]\\(\\),]*?)?($|;|:([^;^\\s]*(;|$|\\s))).*?\\.ant\\-btn([-_a-zA-Z0-9\\.:"= \\[\\]\\(\\),]*?)?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'mat_$host'), ''), 'null'), '^"|"$', ''), 'teest.com'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'mat_$current_url'), ''), 'null'), '^"|"$', '')), '%https://teest.com%'), 0)), 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), 0)+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -87,8 +87,8 @@# ---# name: TestWebGoalsQueryRunner.test_dont_show_deleted_actions'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,- uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0))) AS previous_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,+ uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), sum(action_previous_count_0)) AS action_total_0,tuple(uniq(action_current_person_id_0), uniq(action_previous_person_id_0)) AS action_uniques_0,@@ -125,7 +125,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0)))+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC')))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -142,8 +142,8 @@# ---# name: TestWebGoalsQueryRunner.test_many_users_and_actions'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,- uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0))) AS previous_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,+ uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), sum(action_previous_count_0)) AS action_total_0,tuple(uniq(action_current_person_id_0), uniq(action_previous_person_id_0)) AS action_uniques_0,@@ -187,7 +187,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Pay $10'), 0), events.elements_chain_texts)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0)))+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC')))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -204,7 +204,7 @@# ---# name: TestWebGoalsQueryRunner.test_no_comparison'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,uniqIf(web_goals_person_id, 0) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), NULL) AS action_total_0,@@ -248,7 +248,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Pay $10'), 0), events.elements_chain_texts)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), 0)+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0)LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -265,8 +265,8 @@# ---# name: TestWebGoalsQueryRunner.test_no_crash_when_no_data_and_some_actions'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,- uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0))) AS previous_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,+ uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), sum(action_previous_count_0)) AS action_total_0,tuple(uniq(action_current_person_id_0), uniq(action_previous_person_id_0)) AS action_uniques_0,@@ -310,7 +310,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Pay $10'), 0), events.elements_chain_texts)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0)))+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC')))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -327,8 +327,8 @@# ---# name: TestWebGoalsQueryRunner.test_one_user_one_action'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,- uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0))) AS previous_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,+ uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), sum(action_previous_count_0)) AS action_total_0,tuple(uniq(action_current_person_id_0), uniq(action_previous_person_id_0)) AS action_uniques_0,@@ -372,7 +372,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Pay $10'), 0), events.elements_chain_texts)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0)))+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC')))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -389,8 +389,8 @@# ---# name: TestWebGoalsQueryRunner.test_one_user_two_different_actions'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,- uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0))) AS previous_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,+ uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), sum(action_previous_count_0)) AS action_total_0,tuple(uniq(action_current_person_id_0), uniq(action_previous_person_id_0)) AS action_uniques_0,@@ -434,7 +434,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Pay $10'), 0), events.elements_chain_texts)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0)))+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC')))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -451,8 +451,8 @@# ---# name: TestWebGoalsQueryRunner.test_one_user_two_similar_actions_across_sessions'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,- uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0))) AS previous_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,+ uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), sum(action_previous_count_0)) AS action_total_0,tuple(uniq(action_current_person_id_0), uniq(action_previous_person_id_0)) AS action_uniques_0,@@ -496,7 +496,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Pay $10'), 0), events.elements_chain_texts)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0)))+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC')))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,@@ -513,8 +513,8 @@# ---# name: TestWebGoalsQueryRunner.test_one_users_one_action_each'''- SELECT uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0))) AS current_total_people,- uniqIf(web_goals_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0))) AS previous_total_people,+ SELECT uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))))) AS current_total_people,+ uniqIf(web_goals_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))) AS previous_total_people,'Contacted Sales' AS action_name_0,tuple(sum(action_current_count_0), sum(action_previous_count_0)) AS action_total_0,tuple(uniq(action_current_person_id_0), uniq(action_previous_person_id_0)) AS action_uniques_0,@@ -558,7 +558,7 @@WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Contacted Sales'), 0), events.elements_chain_texts)), and(equals(events.event, '$pageview'), ifNull(match(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'), isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''))and isNull('https://(app|eu|us)\\.posthog\\.com/project/\\d+/web.*'))), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)button(\\.|$|;|:)'), arrayExists(x -> ifNull(equals(x, 'Pay $10'), 0), events.elements_chain_texts)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))))), 1, 1))GROUP BY events.`$session_id`)- WHERE or(and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC'))), 0)), and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC'))), 0)))+ WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-11-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-08-03 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-10-31 23:59:59', 'UTC')))))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,allow_experimental_object_type=1,diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambrindex 852dae3dca86..871a49e7b765 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr@@ -65,16 +65,16 @@# ---# name: TestWebOverviewQueryRunner.test_comparison'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -118,12 +118,12 @@# ---# name: TestWebOverviewQueryRunner.test_conversion_goal_no_conversions'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_conversion_count,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_conversion_count,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_conversions,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_conversions,+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_conversion_count,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_conversion_count,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_conversions,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_conversions,divide(unique_conversions, unique_users) AS conversion_rate,divide(previous_unique_conversions, previous_unique_users) AS previous_conversion_rateFROM@@ -169,12 +169,12 @@# ---# name: TestWebOverviewQueryRunner.test_conversion_goal_one_autocapture_conversion'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_conversion_count,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_conversion_count,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_conversions,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_conversions,+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_conversion_count,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_conversion_count,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_conversions,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_conversions,divide(unique_conversions, unique_users) AS conversion_rate,divide(previous_unique_conversions, previous_unique_users) AS previous_conversion_rateFROM@@ -217,12 +217,12 @@# ---# name: TestWebOverviewQueryRunner.test_conversion_goal_one_custom_action_conversion'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_conversion_count,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_conversion_count,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_conversions,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_conversions,+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_conversion_count,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_conversion_count,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_conversions,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_conversions,divide(unique_conversions, unique_users) AS conversion_rate,divide(previous_unique_conversions, previous_unique_users) AS previous_conversion_rateFROM@@ -265,12 +265,12 @@# ---# name: TestWebOverviewQueryRunner.test_conversion_goal_one_custom_event_conversion'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_conversion_count,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_conversion_count,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_conversions,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_conversions,+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_conversion_count,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_conversion_count,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_conversions,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_conversions,divide(unique_conversions, unique_users) AS conversion_rate,divide(previous_unique_conversions, previous_unique_users) AS previous_conversion_rateFROM@@ -313,12 +313,12 @@# ---# name: TestWebOverviewQueryRunner.test_conversion_goal_one_pageview_conversion'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_conversion_count,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_conversion_count,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_conversions,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_conversions,+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_conversion_count,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_conversion_count,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_conversions,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_conversions,divide(unique_conversions, unique_users) AS conversion_rate,divide(previous_unique_conversions, previous_unique_users) AS previous_conversion_rateFROM@@ -364,12 +364,12 @@# ---# name: TestWebOverviewQueryRunner.test_conversion_rate'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_conversion_count,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_conversion_count,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_conversions,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_conversions,+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_conversion_count,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_conversion_count,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_conversions,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_conversions,divide(unique_conversions, unique_users) AS conversion_rate,divide(previous_unique_conversions, previous_unique_users) AS previous_conversion_rateFROM@@ -627,16 +627,16 @@# ---# name: TestWebOverviewQueryRunner.test_correctly_counts_pageviews_in_long_running_session'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -680,16 +680,16 @@# ---# name: TestWebOverviewQueryRunner.test_dont_filter_test_accounts'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -733,16 +733,16 @@# ---# name: TestWebOverviewQueryRunner.test_filter_cohort'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -791,16 +791,16 @@# ---# name: TestWebOverviewQueryRunner.test_filter_test_accounts'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -854,16 +854,16 @@# ---# name: TestWebOverviewQueryRunner.test_increase_in_users'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -907,16 +907,16 @@# ---# name: TestWebOverviewQueryRunner.test_increase_in_users_using_mobile'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -960,16 +960,16 @@# ---# name: TestWebOverviewQueryRunner.test_limit_is_context_aware'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -1013,16 +1013,16 @@# ---# name: TestWebOverviewQueryRunner.test_no_crash_when_no_data'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -1066,16 +1066,16 @@# ---# name: TestWebOverviewQueryRunner.test_no_crash_when_no_data.1'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS total_filtered_pageview_count,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_total_filtered_pageview_count,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_sessions,- uniqIf(session_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_sessions,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS avg_duration_s,- avgIf(session_duration, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_avg_duration_s,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS total_filtered_pageview_count,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_total_filtered_pageview_count,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_sessions,+ uniqIf(session_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_sessions,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS avg_duration_s,+ avgIf(session_duration, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_avg_duration_s,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS session_person_id,events__session.session_id AS session_id,@@ -1119,12 +1119,12 @@# ---# name: TestWebOverviewQueryRunner.test_no_crash_when_no_data.2'''- SELECT uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_users,- uniqIf(session_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_users,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS total_conversion_count,- sumIf(conversion_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_total_conversion_count,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS unique_conversions,- uniqIf(conversion_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))), 0))) AS previous_unique_conversions,+ SELECT uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_users,+ uniqIf(session_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_users,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS total_conversion_count,+ sumIf(conversion_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_total_conversion_count,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-08 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS unique_conversions,+ uniqIf(conversion_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-07 23:59:59', 'UTC'))))) AS previous_unique_conversions,divide(unique_conversions, unique_users) AS conversion_rate,divide(previous_unique_conversions, previous_unique_users) AS previous_conversion_rateFROMdiff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambrindex 90a5eeb1a026..b4fbaa7142af 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr@@ -72,10 +72,10 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS visitors,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS views,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_views+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_visitors,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,count() AS filtered_pageview_count,@@ -112,8 +112,8 @@GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)LEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))) AS bounce_rate,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0))) AS previous_bounce_rate+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))))) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,any(events__session.`$is_bounce`) AS is_bounce,@@ -173,9 +173,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -213,7 +213,7 @@GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)LEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -274,9 +274,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -314,7 +314,7 @@GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)LEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -375,9 +375,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -415,7 +415,7 @@GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)LEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -475,9 +475,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -506,7 +506,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -566,9 +566,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -597,7 +597,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -657,9 +657,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -688,7 +688,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT replaceRegexpAll(replaceRegexpAll(replaceRegexpAll(events__session.`$entry_pathname`, '\\/a\\/\\d+', '/a/:id'), '\\/b\\/\\d+', '/b/:id'), '\\/c\\/\\d+', '/c/:id') AS breakdown_value,@@ -748,9 +748,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -779,7 +779,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -839,9 +839,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -870,7 +870,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -1042,8 +1042,8 @@# name: TestWebStatsTableQueryRunner.test_comparison'''SELECT breakdown_value AS `context.columns.breakdown_value`,- tuple(uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))), uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0)))) AS `context.columns.visitors`,- tuple(sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))), 0))), sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC'))), 0)))) AS `context.columns.views`,+ tuple(uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))), uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC')))))) AS `context.columns.visitors`,+ tuple(sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-06 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-13 23:59:59', 'UTC'))))), sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-11-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-05 23:59:59', 'UTC')))))) AS `context.columns.views`,divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -3210,9 +3210,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -3250,7 +3250,7 @@GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)LEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -3880,9 +3880,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-31 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-31 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-31 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-31 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -3911,7 +3911,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-30 00:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-31 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-30 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-07-31 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -3971,9 +3971,9 @@`context.columns.bounce_rate`.1 AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -4002,7 +4002,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -4063,9 +4063,9 @@`context.columns.bounce_rate`.1 AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -4094,7 +4094,7 @@GROUP BY breakdown_value) AS countsLEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,@@ -4717,9 +4717,9 @@divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`FROM(SELECT breakdown_value AS breakdown_value,- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS visitors,uniqIf(filtered_person_id, 0) AS previous_visitors,- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS views,sumIf(filtered_pageview_count, 0) AS previous_viewsFROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,@@ -4757,7 +4757,7 @@GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)LEFT JOIN(SELECT breakdown_value AS breakdown_value,- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS bounce_rate,avgIf(is_bounce, 0) AS previous_bounce_rateFROM(SELECT events__session.`$entry_pathname` AS breakdown_value,diff --git a/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py b/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.pyindex 0b87d063ed25..81f7a9339534 100644--- a/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py+++ b/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py@@ -1,4 +1,4 @@-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, also_test_with_materialized_columns+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, also_test_with_materialized_columns, materializedfrom unittest.mock import patchfrom posthog.schema import (@@ -10,6 +10,11 @@ from posthog.schema import (WebStatsTableQuery,)+from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.printer.utils import prepare_ast_for_printing, print_prepared_ast++from products.web_analytics.backend.hogql_queries.events_prefilter import EventsPrefilterTransformerfrom products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner@@ -169,6 +174,47 @@ class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):assert "events.properties" in sqlassert "JSONExtractRaw(events.properties," in sql+ def test_bounce_with_materialized_event_property_filter(self):+ # Property resolution rewrites a materialized property read to a synthetic mat_* column the HogQL schema+ # doesn't know about; the prefilter subquery must still SELECT that column or the outer query fails with+ # UNKNOWN_IDENTIFIER. Executes against ClickHouse, so a missing column fails the query itself.+ with materialized("events", "customProperty"):+ sql = self._run_prefiltered_query(+ includeBounceRate=True,+ properties=[+ EventPropertyFilter(+ key="customProperty",+ operator=PropertyOperator.EXACT,+ value=["1"],+ )+ ],+ )++ assert "mat_customProperty" in sql+ assert sql.count("mat_customProperty") >= 2, (+ "subquery must SELECT the materialized column the outer query reads"+ )++ def test_deep_key_read_off_materialized_column_kept_in_subquery(self):+ # A deep read (properties.customProperty.bar) through a materialized column becomes a JSON extract over the+ # synthetic mat_* column; the transformer must keep that column in the prefilter subquery.+ with materialized("events", "customProperty"):+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ node = parse_select("SELECT count() FROM events WHERE properties.customProperty.bar = 'x'")+ prepared = prepare_ast_for_printing(node, context=context, dialect="clickhouse", stack=[])+ assert prepared is not None+ transformer = EventsPrefilterTransformer(team_id=self.team.pk, date_from="2024-01-01", date_to="2024-01-02")+ try:+ transformer.visit(prepared)+ assert transformer.wraps_applied == 1+ sql = print_prepared_ast(prepared, context=context, dialect="clickhouse")+ finally:+ transformer.cleanup_temp_schema_fields()++ assert sql.count("mat_customProperty") >= 2, (+ "subquery must SELECT the materialized column the outer query reads"+ )+@also_test_with_materialized_columns(person_properties=["email"],verify_no_jsonextract=False,