OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
docs: drop the V1-equivalence proofs and the port archaeology
Carl-Gerhard Lindesvärd3125369371eb
diff --git a/packages/core/src/buffers/buffers.sql.proof.md b/packages/core/src/buffers/buffers.sql.proof.mddeleted file mode 100644index 9ad2cdc89..000000000--- a/packages/core/src/buffers/buffers.sql.proof.md+++ /dev/null@@ -1,141 +0,0 @@-# buffers off `sqlstring` — V1 → V2 result-set proof (M12-009)--M12-009 deletes `sqlstring` from every workspace manifest, so the three buffer-files that still imported it had to move onto the `sql` tag first. V1 is the-`sqlstring.escape(...)` text each file built at `30d236fa`; V2 is the tagged-statement in this commit. Both forms were rendered in one Bun process and-executed through the same `@clickhouse/client` (`format: 'JSONCompact'`) — V1-as `query`, V2 as `query` + `query_params`. `meta` and `data` were compared-field for field.--- **Date**: 2026-09-07, run by ralph on this box.-- **Reads**: local prod-copy `openpanel` (319M events), read-only.-- **Mutation**: the `profile-backfill-buffer` lightweight `UPDATE` is a write,- so it ran against a throwaway `m12009_scratch` database seeded with three- rows, never against `openpanel` or `openpanel_test`. The database was dropped- after the run.-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box. Timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`).-- **Verdict**: **4 statements, all IDENTICAL.**--| # | Site | Statement | Rows | old → new |-|---|---|---|---:|---|-| 1 | `group-buffer.ts:84` | `SELECT … FROM groups FINAL WHERE project_id/id` | 1 | 33ms → 8ms |-| 2 | `profile-buffer.ts:222` | batch fetch, `withDateFilter=false` | 2 | 20ms → 20ms |-| 3 | `profile-buffer.ts:222` | batch fetch, `withDateFilter=true` | 0 | 9ms → 8ms |-| 4 | `profile-backfill-buffer.ts:96` | lightweight `UPDATE … CASE session_id` | 3 read back | 7ms → 6ms |--## IN / GLOBAL IN--Every `IN` touched here takes a **literal set** — `(p.id, p.project_id) IN-((…), (…))` and `(project_id, session_id) IN ((…), (…))` — not a subquery. A-literal set is evaluated identically on every shard, so `docs/ENVIRONMENT.md`'s-`IN` vs `GLOBAL IN` trap does not apply and **no `IN` was converted in either-direction**. Binding the tuple members as `{pN:String}` does not change that:-the set is still spelled out in the query text, one placeholder per member.--## Run output--```-==============================================================================-CASE: group-buffer: SELECT ... FROM groups FINAL [db=openpanel]---- OLD (clix/sqlstring text) ----SELECT project_id, id, type, name, properties, created_at- FROM groups FINAL- WHERE project_id = 'acade'- AND id = 'acade'- AND deleted = 0---- NEW (sql tag) ----SELECT project_id, id, type, name, properties, created_at- FROM groups FINAL- WHERE project_id = {p1:String}- AND id = {p2:String}- AND deleted = 0---- params ----{"p1":"acade","p2":"acade"}-old: ok=true rows=1 33ms-new: ok=true rows=1 8ms-RESULT SETS: IDENTICAL-==============================================================================-CASE: profile-buffer: batch fetch (withDateFilter=false) [db=openpanel]---- OLD (clix/sqlstring text) ----SELECT id, project_id, argMax(first_name, p.last_seen_at) AS first_name, argMax(last_name, p.last_seen_at) AS last_name, argMax(email, p.last_seen_at) AS email, argMax(avatar, p.last_seen_at) AS avatar, argMax(properties, p.last_seen_at) AS properties, argMax(is_external, p.last_seen_at) AS is_external, argMax(groups, p.last_seen_at) AS groups, min(created_at) AS created_at, max(p.last_seen_at) AS last_seen_at- FROM profiles AS p- WHERE (p.id, p.project_id) IN (('03b7d7d74db08200f7fb3dc912abb51e', '0byte'), ('07deba9fc77b280a8dbc7f823d5c2319', '0byte'))-- GROUP BY p.id, p.project_id---- NEW (sql tag) ----SELECT id, project_id, argMax(first_name, p.last_seen_at) AS first_name, argMax(last_name, p.last_seen_at) AS last_name, argMax(email, p.last_seen_at) AS email, argMax(avatar, p.last_seen_at) AS avatar, argMax(properties, p.last_seen_at) AS properties, argMax(is_external, p.last_seen_at) AS is_external, argMax(groups, p.last_seen_at) AS groups, min(created_at) AS created_at, max(p.last_seen_at) AS last_seen_at- FROM profiles AS p- WHERE (p.id, p.project_id) IN (({p1:String}, {p2:String}), ({p3:String}, {p4:String}))-- GROUP BY p.id, p.project_id---- params ----{"p1":"03b7d7d74db08200f7fb3dc912abb51e","p2":"0byte","p3":"07deba9fc77b280a8dbc7f823d5c2319","p4":"0byte"}-old: ok=true rows=2 20ms-new: ok=true rows=2 20ms-RESULT SETS: IDENTICAL-==============================================================================-CASE: profile-buffer: batch fetch (withDateFilter=true) [db=openpanel]---- OLD (clix/sqlstring text) ----SELECT id, project_id, argMax(first_name, p.last_seen_at) AS first_name, argMax(last_name, p.last_seen_at) AS last_name, argMax(email, p.last_seen_at) AS email, argMax(avatar, p.last_seen_at) AS avatar, argMax(properties, p.last_seen_at) AS properties, argMax(is_external, p.last_seen_at) AS is_external, argMax(groups, p.last_seen_at) AS groups, min(created_at) AS created_at, max(p.last_seen_at) AS last_seen_at- FROM profiles AS p- WHERE (p.id, p.project_id) IN (('03b7d7d74db08200f7fb3dc912abb51e', '0byte'), ('07deba9fc77b280a8dbc7f823d5c2319', '0byte'))- AND p.last_seen_at > now() - INTERVAL 2 DAY- GROUP BY p.id, p.project_id---- NEW (sql tag) ----SELECT id, project_id, argMax(first_name, p.last_seen_at) AS first_name, argMax(last_name, p.last_seen_at) AS last_name, argMax(email, p.last_seen_at) AS email, argMax(avatar, p.last_seen_at) AS avatar, argMax(properties, p.last_seen_at) AS properties, argMax(is_external, p.last_seen_at) AS is_external, argMax(groups, p.last_seen_at) AS groups, min(created_at) AS created_at, max(p.last_seen_at) AS last_seen_at- FROM profiles AS p- WHERE (p.id, p.project_id) IN (({p1:String}, {p2:String}), ({p3:String}, {p4:String}))- AND p.last_seen_at > now() - INTERVAL 2 DAY- GROUP BY p.id, p.project_id---- params ----{"p1":"03b7d7d74db08200f7fb3dc912abb51e","p2":"0byte","p3":"07deba9fc77b280a8dbc7f823d5c2319","p4":"0byte"}-old: ok=true rows=0 9ms-new: ok=true rows=0 8ms-RESULT SETS: IDENTICAL-```--The `profile-backfill-buffer` case, run against `m12009_scratch`:--```-==============================================================================-CASE: profile-backfill-buffer: lightweight UPDATE ... CASE session_id [db=m12009_scratch]---- OLD ----UPDATE events_replicated- SET profile_id = CASE session_id- WHEN 's1' THEN 'prof-1'-WHEN 's2' THEN 'prof-2'- END- WHERE (project_id, session_id) IN (('p1', 's1'),('p1', 's2'))- AND created_at > now() - INTERVAL 6 HOURS---- NEW ----UPDATE events_replicated- SET profile_id = CASE session_id- WHEN {p1:String} THEN {p2:String}-WHEN {p3:String} THEN {p4:String}- END- WHERE (project_id, session_id) IN (({p5:String}, {p6:String}), ({p7:String}, {p8:String}))- AND created_at > now() - INTERVAL 6 HOURS---- params ----{"p1":"s1","p2":"prof-1","p3":"s2","p4":"prof-2","p5":"p1","p6":"s1","p7":"p1","p8":"s2"}-old: ok=true 7ms-new: ok=true 6ms-old rows after: {"meta":[{"name":"project_id","type":"String"},{"name":"session_id","type":"String"},{"name":"profile_id","type":"String"}],"data":[["p1","s1","prof-1"],["p1","s2","prof-2"],["p2","s3","keep"]]}-new rows after: {"meta":[{"name":"project_id","type":"String"},{"name":"session_id","type":"String"},{"name":"profile_id","type":"String"}],"data":[["p1","s1","prof-1"],["p1","s2","prof-2"],["p2","s3","keep"]]}-RESULT SETS: IDENTICAL-```--`m12009_scratch.events_replicated` needed `enable_block_number_column = 1` for-`allow_experimental_lightweight_update` to apply — a property of the throwaway-fixture table, not of the statement; both forms failed identically before it was-set and both succeeded identically after.--## Whitespace-only differences, stated--`profile-backfill-buffer.ts`'s tuple list joins on `', '` where V1 joined on-`','`, and `profile-buffer.ts`'s aggregate column list is now a-`sql.join([...], ', ')` of one fragment per column instead of a-`String[].join(', ')`. Both render the same tokens; the run above is over the-rendered text, so the comparison covers it.diff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.tsindex 1cdd2412d..a551f652e 100644--- a/packages/core/src/modules/chart/chart.service.ts+++ b/packages/core/src/modules/chart/chart.service.ts@@ -1,19 +1,6 @@-// Ported from packages/db/src/services/chart.service.ts, packages/db/src/-// engine/* and the handler bodies of packages/trpc/src/routers/chart.ts-// (M7-003). Every ClickHouse statement this module runs is a `sql` fragment-// from src/sql.ts, proven byte-equivalent to V1 in src/sql.proof.md; V1's-// chart.service and engine are re-export shims onto this module and its-// router delegates here (DELEGATE PATTERN).-//-// The funnel, conversion, sankey and retention statements this module-// dispatches to live in the sibling `*.service.ts` files of this module-// (M7-004).-//-// M10-003: every function takes `ServiceDeps` and reaches ClickHouse and-// Postgres as `deps.ch` / `deps.db`. The `load*` lazy loaders are gone, and-// so is the `@openpanel/core` self-barrel hop this file used to make for the-// report module's `mergeGlobalFilters` / `onlyReportEvents` — those are-// imported straight from `../report/src/series` (docs/TECH_DEBT.md §2, §4).+// Every ClickHouse statement this module runs is a `sql` fragment from+// src/sql.ts. Funnel, conversion, sankey and retention are dispatched to the+// sibling `*.service.ts` files.// The one thing still value-imported from `@openpanel/db` under `./src/` is// ADR-013's `sql` tag, which ADR-007 keeps in `packages/db` by name: a// compile-time template tag, no client and no request scope.diff --git a/packages/core/src/modules/chart/conversion.service.ts b/packages/core/src/modules/chart/conversion.service.tsindex 867b00cf6..e26e2d9ca 100644--- a/packages/core/src/modules/chart/conversion.service.ts+++ b/packages/core/src/modules/chart/conversion.service.ts@@ -1,8 +1,3 @@-// Ported from packages/db/src/services/conversion.service.ts (M7-004). The-// statement is a `sql` fragment from src/conversion.sql.ts, proven-// byte-equivalent to V1 in src/conversion.sql.proof.md; V1's-// conversion.service is a re-export shim onto this module (DELEGATE PATTERN).-import { sql } from '@openpanel/db/src/clickhouse/sql';import { omit } from 'ramda';import type { ServiceDeps, Services } from '../../services';diff --git a/packages/core/src/modules/chart/funnel.service.ts b/packages/core/src/modules/chart/funnel.service.tsindex 7206a5ff8..28ed1d8c0 100644--- a/packages/core/src/modules/chart/funnel.service.ts+++ b/packages/core/src/modules/chart/funnel.service.ts@@ -1,8 +1,3 @@-// Ported from packages/db/src/services/funnel.service.ts (M7-004). Every-// ClickHouse statement is a `sql` fragment from src/funnel.sql.ts, proven-// byte-equivalent to V1 in src/funnel.sql.proof.md; V1's funnel.service is a-// re-export shim onto this module (DELEGATE PATTERN).-import { ifNaN } from '@openpanel/shared';import { last, reverse } from 'ramda';import type { ServiceDeps, Services } from '../../services';diff --git a/packages/core/src/modules/chart/retention.service.ts b/packages/core/src/modules/chart/retention.service.tsindex 7065766ec..a75b9ba2f 100644--- a/packages/core/src/modules/chart/retention.service.ts+++ b/packages/core/src/modules/chart/retention.service.ts@@ -1,8 +1,3 @@-// Ported from packages/db/src/services/retention.service.ts (M7-004). Every-// ClickHouse statement is a `sql` fragment from src/retention.sql.ts, proven-// byte-equivalent to V1 in src/retention.sql.proof.md; V1's retention.service-// is a re-export shim onto this module (DELEGATE PATTERN).-//// The cohort matrix here is the single source of truth for retention cohorts:// it powers the dashboard retention chart (via the tRPC `cohort` procedure) as// well as the MCP / agent / REST retention endpoints.diff --git a/packages/core/src/modules/chart/sankey.service.ts b/packages/core/src/modules/chart/sankey.service.tsindex e330b0ca2..28a8aafe1 100644--- a/packages/core/src/modules/chart/sankey.service.ts+++ b/packages/core/src/modules/chart/sankey.service.ts@@ -1,8 +1,3 @@-// Ported from packages/db/src/services/sankey.service.ts (M7-004). Every-// ClickHouse statement is a `sql` fragment from src/sankey.sql.ts, proven-// byte-equivalent to V1 in src/sankey.sql.proof.md; V1's sankey.service is a-// re-export shim onto this module (DELEGATE PATTERN).-import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import { TRPCBadRequestError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';@@ -140,8 +135,8 @@ function toSankeyEvent(* `getSankey` itself: §12 fix 9 bounds that procedure specifically, because it* is the range picker that offers `12m`/`lastYear`. The REST* `/insights/:projectId/user_flow` route, the MCP `get_user_flow` tool and the- * assistant tool take caller-supplied dates and are outside fix 9's endpoint- * list; see sankey.sql.proof.md for that residual.+ * assistant tool take caller-supplied dates, so they are not covered by the+ * range picker's cap.*/export function assertSankeyWindowIsAnswerable(startDate: string,diff --git a/packages/core/src/modules/chart/src/conversion.sql.proof.md b/packages/core/src/modules/chart/src/conversion.sql.proof.mddeleted file mode 100644index 40497b085..000000000--- a/packages/core/src/modules/chart/src/conversion.sql.proof.md+++ /dev/null@@ -1,152 +0,0 @@-# conversion.sql.ts — V1 -> V2 result-set proof (M7-004)--The conversion statement was executed twice against the same data — once as V1 (the `git HEAD` `packages/db/src/services/conversion.service.ts`, `c4760ac2`, captured by wrapping the shared ClickHouse client) and once as V2 (the fragment the core service sends) — through one `@clickhouse/client` with `format: 'JSON'` and the same `session_timezone`. The two responses were compared on `data` (every row, every column, as JSON) and `meta` (column names and types). Both sides were driven by their own service, so the inputs, the breakdown resolution and the cohort lookups are the real ones.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static). Projects: `secure-privacy`, `verdict`, `bayse` (America/New_York).-- **Machine**: single-node ClickHouse on a 4-vCPU box — timings are directional only; production is 2 shards x 2 replicas (`docs/ENVIRONMENT.md`). The statement contains no `IN (subquery)`; the profile, group and cohort joins keep V1's exact `LEFT ANY JOIN` / `ARRAY JOIN` shape, so no `IN` / `GLOBAL IN` decision is made or unmade here.--- **Verdict**: 12 cases, 0 not identical.--### conversionQuery — no breakdown, day (secure-privacy)--**IDENTICAL** — rows V1/V2 = 7/7; rows_read V1/V2 = 106489/106489; wall V1/V2 = 38 ms / 42 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, windowFunnel(86400)( toDateTime(created_at), events.name = 'session_start', events.name = 'session_end' ) as steps FROM events WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"secure-privacy","p8":["session_start","session_end"],"p9":"2026-07-06 00:00:00","p10":"2026-07-12 23:59:59"}-```--### conversionQuery — breakdown country, day--**IDENTICAL** — rows V1/V2 = 463/463; rows_read V1/V2 = 106489/106489; wall V1/V2 = 55 ms / 38 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, country as b_0, windowFunnel(86400)( toDateTime(created_at), events.name = 'session_start', events.name = 'session_end' ) as steps FROM events WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id, country) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, country as b_0, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id, country) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"secure-privacy","p8":["session_start","session_end"],"p9":"2026-07-06 00:00:00","p10":"2026-07-12 23:59:59"}-```--### conversionQuery — profile_id group, week interval, limit 3--**IDENTICAL** — rows V1/V2 = 19/19; rows_read V1/V2 = 155590/155590; wall V1/V2 = 50 ms / 65 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, b_0, uniqExact(profile_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(profile_id), 2) AS conversion_rate_percentage FROM ( (SELECT profile_id, any(toStartOfWeek(toDateTime(created_at))) as event_day, os as b_0, windowFunnel(259200)( toDateTime(created_at), events.name = 'session_start', events.name = 'screen_view' ) as steps FROM events WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'screen_view') AND created_at BETWEEN toDateTime('2026-06-01 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY profile_id, os) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2-SELECT event_day, b_0, uniqExact(profile_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(profile_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT profile_id, any(toStartOfWeek(toDateTime(created_at))) as event_day, os as b_0, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY profile_id, os) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":259200,"p5":"session_start","p6":"screen_view","p7":"secure-privacy","p8":["session_start","screen_view"],"p9":"2026-06-01 00:00:00","p10":"2026-07-12 23:59:59"}-```--### conversionQuery — step filters (country is US) + breakdown, hour--**IDENTICAL** — rows V1/V2 = 49/49; rows_read V1/V2 = 24572/24572; wall V1/V2 = 16 ms / 17 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfHour(created_at)) as event_day, device as b_0, windowFunnel(86400)( toDateTime(created_at), (events.name = 'screen_view' AND country = 'US'), events.name = 'session_end' ) as steps FROM events WHERE project_id = 'secure-privacy' AND events.name IN ('screen_view', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-07 00:00:00') GROUP BY session_id, device) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfHour(created_at)) as event_day, device as b_0, windowFunnel({p4:UInt64})( toDateTime(created_at), (events.name = {p5:String} AND country = 'US'), events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id, device) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"screen_view","p6":"session_end","p7":"secure-privacy","p8":["screen_view","session_end"],"p9":"2026-07-06 00:00:00","p10":"2026-07-07 00:00:00"}-```--### conversionQuery — property breakdown + properties filter, day--**IDENTICAL** — rows V1/V2 = 4/4; rows_read V1/V2 = 65534/65534; wall V1/V2 = 29 ms / 48 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, properties['__path'] as b_0, windowFunnel(86400)( toDateTime(created_at), (events.name = 'screen_view' AND events.properties['__query.utm_source'] != ''), events.name = 'session_end' ) as steps FROM events WHERE project_id = 'secure-privacy' AND events.name IN ('screen_view', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') GROUP BY session_id, properties['__path']) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, properties['__path'] as b_0, windowFunnel({p4:UInt64})( toDateTime(created_at), (events.name = {p5:String} AND events.properties['__query.utm_source'] != ''), events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id, properties['__path']) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"screen_view","p6":"session_end","p7":"secure-privacy","p8":["screen_view","session_end"],"p9":"2026-07-06 00:00:00","p10":"2026-07-09 23:59:59"}-```--### conversionQuery — profile breakdown -> profiles LEFT ANY JOIN, day--**IDENTICAL** — rows V1/V2 = 15/15; rows_read V1/V2 = 376510/376510; wall V1/V2 = 72 ms / 66 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, profile.email as b_0, windowFunnel(86400)( toDateTime(created_at), events.name = 'session_start', events.name = 'session_end' ) as steps FROM events LEFT ANY JOIN ( SELECT id, email FROM profiles FINAL WHERE project_id = 'secure-privacy' ) as profile ON profile.id = profile_id WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') GROUP BY session_id, profile.email) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, profile.email as b_0, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events LEFT ANY JOIN ( SELECT id, email FROM profiles FINAL WHERE project_id = {p7:String} ) as profile ON profile.id = profile_id WHERE project_id = {p8:String} AND events.name IN {p9:Array(String)} AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String}) GROUP BY session_id, profile.email) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"secure-privacy","p8":"secure-privacy","p9":["session_start","session_end"],"p10":"2026-07-06 00:00:00","p11":"2026-07-09 23:59:59"}-```--### conversionQuery — profile.properties breakdown -> properties Map join, day--**IDENTICAL** — rows V1/V2 = 4/4; rows_read V1/V2 = 376510/376510; wall V1/V2 = 96 ms / 101 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, profile.properties['plan'] as b_0, windowFunnel(86400)( toDateTime(created_at), events.name = 'session_start', events.name = 'session_end' ) as steps FROM events LEFT ANY JOIN ( SELECT id, properties FROM profiles FINAL WHERE project_id = 'secure-privacy' ) as profile ON profile.id = profile_id WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') GROUP BY session_id, profile.properties['plan']) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, profile.properties['plan'] as b_0, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events LEFT ANY JOIN ( SELECT id, properties FROM profiles FINAL WHERE project_id = {p7:String} ) as profile ON profile.id = profile_id WHERE project_id = {p8:String} AND events.name IN {p9:Array(String)} AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String}) GROUP BY session_id, profile.properties['plan']) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"secure-privacy","p8":"secure-privacy","p9":["session_start","session_end"],"p10":"2026-07-06 00:00:00","p11":"2026-07-09 23:59:59"}-```--### conversionQuery — group breakdown -> ARRAY JOIN groups, day--**IDENTICAL** — rows V1/V2 = 14/14; rows_read V1/V2 = 68893/68893; wall V1/V2 = 35 ms / 43 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, _group_id as b_0, windowFunnel(86400)( toDateTime(created_at), events.name = 'session_start', events.name = 'session_end' ) as steps FROM events ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') AS _g ON _g.id = _group_id WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') GROUP BY session_id, _group_id) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2-SELECT event_day, b_0, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, _group_id as b_0, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p7:String}) AS _g ON _g.id = _group_id WHERE project_id = {p8:String} AND events.name IN {p9:Array(String)} AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String}) GROUP BY session_id, _group_id) ) WHERE steps > 0 GROUP BY event_day, b_0 ORDER BY event_day ASC, b_0 ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"secure-privacy","p8":"secure-privacy","p9":["session_start","session_end"],"p10":"2026-07-06 00:00:00","p11":"2026-07-09 23:59:59"}-```--### conversionQuery — unknown breakdown dropped, minute interval--**IDENTICAL** — rows V1/V2 = 116/116; rows_read V1/V2 = 16381/16381; wall V1/V2 = 15 ms / 15 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfMinute(created_at)) as event_day, windowFunnel(86400)( toDateTime(created_at), events.name = 'session_start', events.name = 'session_end' ) as steps FROM events WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-06 02:00:00') GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfMinute(created_at)) as event_day, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"secure-privacy","p8":["session_start","session_end"],"p9":"2026-07-06 00:00:00","p10":"2026-07-06 02:00:00"}-```--### conversionQuery — month interval, verdict--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 24600197/24600197; wall V1/V2 = 626 ms / 576 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfMonth(toDateTime(created_at))) as event_day, windowFunnel(86400)( toDateTime(created_at), events.name = 'view_lobby_item', events.name = 'view_picks' ) as steps FROM events WHERE project_id = 'verdict' AND events.name IN ('view_lobby_item', 'view_picks') AND created_at BETWEEN toDateTime('2026-05-01 00:00:00') AND toDateTime('2026-07-31 23:59:59') GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfMonth(toDateTime(created_at))) as event_day, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"view_lobby_item","p6":"view_picks","p7":"verdict","p8":["view_lobby_item","view_picks"],"p9":"2026-05-01 00:00:00","p10":"2026-07-31 23:59:59"}-```--### conversionQuery — non-UTC session timezone (America/New_York), day--**IDENTICAL** — rows V1/V2 = 7/7; rows_read V1/V2 = 7945887/7945887; wall V1/V2 = 145 ms / 143 ms; clickhouse_settings: {"session_timezone":"America/New_York"} (both).--```sql--- V1-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, windowFunnel(86400)( toDateTime(created_at), events.name = 'session_start', events.name = 'session_end' ) as steps FROM events WHERE project_id = 'bayse' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, windowFunnel({p4:UInt64})( toDateTime(created_at), events.name = {p5:String}, events.name = {p6:String} ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"bayse","p8":["session_start","session_end"],"p9":"2026-07-06 00:00:00","p10":"2026-07-12 23:59:59"}-```--### conversionQuery — globalFilters merged into both steps, day--**IDENTICAL** — rows V1/V2 = 4/4; rows_read V1/V2 = 65534/65534; wall V1/V2 = 25 ms / 35 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= 2) AS conversions, round(100.0 * countIf(steps >= 2) / uniqExact(session_id), 2) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, windowFunnel(86400)( toDateTime(created_at), (events.name = 'session_start' AND os = 'iOS'), (events.name = 'session_end' AND os = 'iOS') ) as steps FROM events WHERE project_id = 'secure-privacy' AND events.name IN ('session_start', 'session_end') AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2-SELECT event_day, uniqExact(session_id) AS total_first, countIf(steps >= {p1:UInt64}) AS conversions, round(100.0 * countIf(steps >= {p2:UInt64}) / uniqExact(session_id), {p3:UInt64}) AS conversion_rate_percentage FROM ( (SELECT session_id, any(toStartOfDay(created_at)) as event_day, windowFunnel({p4:UInt64})( toDateTime(created_at), (events.name = {p5:String} AND os = 'iOS'), (events.name = {p6:String} AND os = 'iOS') ) as steps FROM events WHERE project_id = {p7:String} AND events.name IN {p8:Array(String)} AND created_at BETWEEN toDateTime({p9:String}) AND toDateTime({p10:String}) GROUP BY session_id) ) WHERE steps > 0 GROUP BY event_day ORDER BY event_day ASC--- V2 params: {"p1":2,"p2":2,"p3":2,"p4":86400,"p5":"session_start","p6":"session_end","p7":"secure-privacy","p8":["session_start","session_end"],"p9":"2026-07-06 00:00:00","p10":"2026-07-09 23:59:59"}-```diff --git a/packages/core/src/modules/chart/src/conversion.sql.ts b/packages/core/src/modules/chart/src/conversion.sql.tsindex be75fedf2..34a49b64b 100644--- a/packages/core/src/modules/chart/src/conversion.sql.ts+++ b/packages/core/src/modules/chart/src/conversion.sql.ts@@ -1,19 +1,12 @@-// The conversion statement as a pure `sql` fragment (ADR-013). Converted 1:1-// from packages/db/src/services/conversion.service.ts (M7-004): the SQL text-// is V1's clix output, with the project id, event names, dates, the funnel-// window and the interval bucket bound as `{pN:Type}` parameters instead of-// inlined literals. Result-set proof: conversion.sql.proof.md.+// The conversion statement as a pure `sql` fragment (ADR-013).//-// The field resolver and both filter compilers return fragments (M12-002,-// M12-003); their output — breakdown expressions, per-step filter clauses and+// The field resolver and both filter compilers return fragments; their output — breakdown expressions, per-step filter clauses and// the cohort joins — is interpolated directly. `compiledText` is left with the// `b_<index>` aliases this file generates itself.//-// Cluster note (docs/ENVIRONMENT.md): `events`, `profiles` and `groups` are-// Distributed on Cloud. The profile / group / cohort joins keep V1's exact-// LEFT ANY JOIN shape and run under the client's-// `distributed_product_mode: 'allow'` as before; no `IN (subquery)` is-// introduced or removed.+// Cluster note: `events`, `profiles` and `groups` are Distributed on Cloud.+// The profile / group / cohort joins are LEFT ANY JOIN and run under the+// client's `distributed_product_mode: 'allow'`; no `IN (subquery)` is involved.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IInterval } from '../../report/report.constants';diff --git a/packages/core/src/modules/chart/src/field-resolution.sql.proof.md b/packages/core/src/modules/chart/src/field-resolution.sql.proof.mddeleted file mode 100644index 0a825b8dd..000000000--- a/packages/core/src/modules/chart/src/field-resolution.sql.proof.md+++ /dev/null@@ -1,2150 +0,0 @@-# field-resolution.ts + table-filter-where.ts — V1 → V2 result-set proof (M12-003)--V1 is `packages/core/src/modules/chart/src/field-resolution.ts` and-`.../table-filter-where.ts` at `4cd0d76b`-(`git show HEAD:<path>`, materialised as `__v1_*` sibling modules so their-relative imports resolve, together with V1's `filter-cast.ts` twins-`castSql`/`buildTypedClause`; all three deleted after the run). V2 is the-converted pair in this commit. Both were imported into ONE Bun process, called-with the SAME inputs, and each produced expression / clause was spliced into-the SAME surrounding statement and executed through ONE `@clickhouse/client`-with `format: 'JSON'` and `session_timezone=UTC` on both sides — V1 as `query`,-V2 as `query` + `query_params`. `data` and `meta` were compared field for-field, and the two failing cases' error messages in full, untruncated. Every-statement carries a total `ORDER BY` (`ORDER BY c DESC,-toString(v) ASC`) or returns a single aggregate row, so **no case needed set-comparison**.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,850,511 events. Project- `secure-privacy` — window `2026-07-01 00:00:00` … `2026-07-08 00:00:00`- (76,885 events, 23,565 sessions), 118,502 profiles, 347 group rows.- **`cohort_members` is empty in the prod copy** (`SELECT count() FROM- cohort_members` = 0), so the five cohort cases are 0-row statement- equivalences; positive-row cohort coverage lives in `openpanel_test` (same- precedent as `sql.proof.md` and `filter-where.sql.proof.md`). The other- zero-count cases are listed under *Cases that return no rows, and why*.-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). Several statements contain `IN (subquery)` on a- `Distributed` table (cohort membership, the cross-table profile subselect,- the group `arrayExists` subselect and `session.performed_event`); **no `IN`- was converted to `GLOBAL IN` or back** — see *IN / GLOBAL IN* below.-- **Verdict**: **131 cases, all IDENTICAL.** 2 of the 131 are **IDENTICAL- ERROR** — the same V1 defect (a numeric or boolean filter value compared- against a String map property) reproduced with the same ClickHouse error- code, the same type pair, the same operands and the same empty result set;- listed in full under *The two IDENTICAL ERROR cases*, not fixed here. 10 more- are compile-time equivalences where both compilers emit no clause at all and- there is nothing to execute.--## compiled.ts kept because--`packages/core/src/modules/chart/src/compiled.ts` is **NOT deleted**. Neither-compiler's output crosses it any more — `getSelectPropertyKey` and every other-resolver return `SqlFragment`s, and no `compiledText(` /-`compiledTextWithProfileRefs(` call wraps them anywhere in `packages/core`-(`compiledTextWithProfileRefs` is deleted outright). What remains are callers-that splice a name the chart builders generated themselves, none of which is a-value and none of which `sql.id` can express (3+ dot-separated parts, backticks,-double quotes, or SQL keywords):--- `packages/core/src/modules/chart/src/field-resolution.ts:203,505` — the- `` `cohort-<id>` `` CTE name and the backtick-quoted CTE alias- `` `profile.properties.<key>` ``.-- `packages/core/src/modules/chart/src/sql.ts:175` — the CTE name in- `WITH <name> AS (...)`.-- `packages/core/src/modules/chart/src/sql.ts:274` — the double-quoted- `"profile.<field>"` CTE alias.-- `packages/core/src/modules/chart/src/sql.ts:340` — the- `` `cohort-<id>` `` CTE name in a JOIN.-- `packages/core/src/modules/chart/src/sql.ts:434,435,469,580` — the- `label_<n>` aliases / group-by keys and the `MATH_FUNCTION_BY_SEGMENT`- aggregate keyword.-- `packages/core/src/modules/chart/src/conversion.sql.ts:117` and- `packages/core/src/modules/chart/conversion.service.ts:137` — the `b_<index>`- aliases.-- `packages/core/src/modules/chart/src/funnel.sql.ts:78,188,307,366,391` — the- `b_<index>` aliases, the `windowFunnel` `'strict_increase'` mode keyword and- the `trim(ifNull(toString(b_<n>), ''))` normalisation.-- `packages/core/src/modules/chart/src/retention.sql.ts:170,171,172,200,206` —- the `toStartOf*` / `INTERVAL` unit / `>=`-vs-`=` keywords and the- `interval_<n>_users` aliases.-- `packages/core/src/modules/chart/src/sankey.sql.ts:28,38,48,187,201` — the- static `arrayFilter`/`arrayMap` expressions and the base CTE name.-- `packages/core/src/modules/overview/src/overview.sql.ts:115` — the- `toInterval<Unit>(n)` step of a `WITH FILL` clause.--`compiled.ts` also keeps `rewriteProfilePropertyRefs` (moved here from-`field-resolution.ts`, which now imports `compiledText` — the move is what-breaks the cycle) and `fragmentWithProfileRefs`, which is where the-profile-property rewrite lives.--## The profile-ref rewrite, after binding--`rewriteProfilePropertyRefs` is a TEXT pass over `profile.properties['<key>']`-(recipe trap 4). Binding the map key moves that key out of the text, so a pass-over the rendered statement can no longer see it. The rewrite therefore moved-into the fragment, in `fragmentWithProfileRefs`:--1. the fragment tree is **flattened** into one (literals, params) interleaving,- so "the literal immediately before this param" has an answer even though- `sql.id` contributes a nested fragment of its own;-2. every literal still goes through the original text rewrite;-3. a `String` param whose value is a narrowed key, sitting between a literal- ending `profile.properties[` and one starting `]`, is collapsed into- `` `profile.properties.<key>` ``.--A value can no longer be rewritten even in principle: only a param the resolver-placed in that exact syntactic position is eligible, and it is replaced by an-identifier rather than edited. The negative control is the case *a VALUE equal-to a narrowed key is never rewritten*, where `profile.properties['country'] =-'country'` keeps its bound `'country'` value on both sides.--## `isWildcardPropertyKey`--`filter-where.ts` decided "is this an array expression?" by testing the-RENDERED text of `getSelectPropertyKey` for a `%`. With the key bound, that-test moved into `field-resolution.isWildcardPropertyKey`. Equivalence was-checked in the same process over every shape that reaches it:--```-[- "properties.__query[*]",- "properties.__query.*.type",- "properties.__query.*",- "properties.__title",- "profile.properties.country",- "profile.properties.a%b",- "properties.a%b",- "country",- "has_profile",- "utm_source",- "group.name"-]-```--For each name, `V1.getSelectPropertyKey(name, undefined, undefined, undefined,-'e').includes('%')` was compared with `V2.isWildcardPropertyKey(name)`.-**Mismatches: []** — including the two V1-defects the predicate reproduces on purpose: `properties.__query.*` is NOT a-wildcard (its transformed pattern has no `%`, so V1 emitted `arrayMap(...) =-'x'` and failed), and `properties.a%b` IS treated as one (the literal `%` in-the key), which fails at ClickHouse. Neither is fixed here.--## IN / GLOBAL IN--Not rewritten in either direction. `grep -n "GLOBAL IN\|GLOBAL JOIN"` over-`packages/core/src`, `packages/db/src` and `apps/*/src` returns **no-application-code occurrence** — only the two comments that say the rule-(`filter-where.ts:115`, `table-filter-where.ts:13`), two more in-`retention.sql.ts`/`sankey.sql.ts`, and the `sql` tag's own R4 tests. Both-converted files contain zero `GLOBAL`.--`grep -n "\bIN \|NOT IN "` on the two files, V1 (`git show HEAD:<path>`) vs-V2:--| file | V1 | V2 |-|---|---|---|-| `field-resolution.ts` | none | none |-| `table-filter-where.ts` | 6 lines: `IN (…)` / `NOT IN (…)` value lists (97, 108), the cohort subselect (264), the group `arrayExists` subselect (283), the profile subselect (306), `performed_event`'s `IN (…)` (326) | 10 lines: the same six sites, with the cohort (298→300/301) and `performed_event` (363→370/371) ternaries split into an explicit `IN` / `NOT IN` pair each — same emitted keyword, no `GLOBAL` |--The value lists changed shape — V1's `IN ('a', 'b')` became-`IN {p:Array(String)}` (recipe idiom 9) — which is a binding change, not a-distribution one.--## Tests whose assertion moved from TEXT to statement + params--Binding the `properties[<key>]` map key (and the cohort labels) takes those-strings out of the SQL text, so every assertion that named one had to move off-the raw `query`. **No expectation changed what it says** — the expected-substrings are byte-identical to V1's; only the subject they run against-changed. Three test files did this with a local helper that renders-`toStatement()` and substitutes every `{pN:Type}` back to the literal V1-emitted (single-quoted, backslash-escaped, arrays as `(a, b)` — i.e.-`sqlstring.escape`'s output). `sql.test.ts` and `funnel.sql.test.ts`-expose it as a third field `.text` on their existing `render()` result,-alongside the untouched `.sql` / `.params`; `table-filter-where.test.ts` folds-it into the existing `build()` helper, so its call sites are unchanged, and-adds `paramsOf()` for the one new params assertion. A fourth,-`overview-raw-where.sql.test.ts`, has rendered `toStatement()` since M12-002-and has no such helper: its two affected assertions moved onto the placeholder-and the params directly.--| test | before | after |-|---|---|---|-| `sql.test.ts` › `getChartSql` › ``qualifies properties[...] with `e.` when group join is present (fixes AMBIGUOUS_IDENTIFIER)`` | `expect(rendered.sql).not.toMatch(/(?<![._\w])properties\[/)` and `.toContain("e.properties['__query.utm_source']")` | same two assertions on `rendered.text` |-| `sql.test.ts` › `getChartSql` › `property metric (property_sum) with group join is unambiguous` | `expect(rendered.sql).toContain("e.properties['revenue_amount']")` | same on `rendered.text` |-| `sql.test.ts` › `getChartSql` › `routes bare utm_source filter through properties map` | `expect(rendered.sql).toContain("properties['__query.utm_source']")`, `.not.toMatch(/(?<![._\w])utm_source\s*=/)` | same two on `rendered.text` |-| `sql.test.ts` › `getAggregateChartSql` › `properties + group breakdown is unambiguous` | `expect(rendered.sql).toContain("e.properties['__query.utm_source']")` | same on `rendered.text` |-| `sql.test.ts` › `profile-property narrowing` › all five non-EXPLAIN tests (`projects only the referenced keys as scalar columns in the profile CTE`, `falls back to the full Map for wildcard refs`, `never narrows identifier-unsafe keys (backtick falls back to the Map)`, `collects the math-metric property too`, `creates the profile join for a metric-only profile property`) | `const { sql } = await getChartSql(...)`, assertions on `sql` | `const { text } = ...`, the SAME assertions on `text`. Every one of these tests names a `properties['<key>']` access, so the whole destructure moved rather than half of it; the two assertions in the set that carry no bound value (`properties as "profile.properties"`, `LEFT ANY JOIN profile ON profile.id = profile_id`) would still hold on `.sql` |-| `funnel.sql.test.ts` › `profile breakdowns` › `adds the profiles join for a profile.properties breakdown` | ``expect(sql).toContain("properties['plan'] as `profile.properties.plan`")``; the two join assertions on `sql` | the first assertion on `text`; the two join assertions stay on `sql` |-| `funnel.sql.test.ts` › `cohort breakdowns` › `adds the cohort join for a cohort breakdown` | `expect(sql).toContain('Power users')`; the two alias assertions on `sql` | `expect(text).toContain('Power users')` — the cohort label is a bound value now; the two alias assertions stay on `sql` |-| `funnel.sql.test.ts` › `breakdown attribution` › `attributes event-property breakdowns at the entry step` | `expect(sql).toContain("argMinIf(properties['experiment'], created_at,")`; the GROUP BY assertions on `sql` | that one assertion on `chartText(...)`; the GROUP BY assertions stay on `sql` |-| `funnel.sql.test.ts` › `profile-property narrowing` › `joins scalar columns instead of the whole properties Map` | `const { sql } = render(statement)`, five assertions on `sql` | `const { text } = ...`, the same five on `text` |-| `table-filter-where.test.ts` › every `describe.each(TABLES)` case | `build()` returned `buildFilterWhere`'s `Record<string, string>` directly | `build()` renders each returned `SqlFragment` through `toStatement()` and substitutes its params back in. **Every `expect(where.fN).toBe(...)` string is unchanged** — that is the point of the helper, and it is what proves the emitted SQL is V1's |-| `table-filter-where.test.ts` › `escapes a quote in a properties key` | `expect(where.f0).toBe(profileWrap(table, "properties['pl\\'an'] = 'pro'"))` | unchanged, **plus** a new `expect(Object.values(paramsOf(table, filters)[0]!)).toContain("pl'an")` — the assertion that the quote now never reaches the SQL text at all |-| `overview-raw-where.sql.test.ts` › `rewrites utm_* to properties[__query.utm_*] for the events table` | `expect(query).toContain("properties['__query.utm_source']")`, `expect(query_params).toEqual({ p1: 'awn' })` | `expect(query).toContain('properties[{p1:String}]')`, `expect(query_params).toEqual({ p1: '__query.utm_source', p2: 'awn' })` — the map key binds, so it moved from the text into the params. The `not.toMatch(/(?<![._\w])utm_source\s*=/)` assertion is unchanged |-| `overview-raw-where.sql.test.ts` › `keeps utm_* as a top-level column for the sessions table` | `expect(query).not.toContain("properties['__query.utm_source']")` | `expect(query).not.toContain('properties[')` — strictly stronger: the old negative would now pass vacuously (the key is never in the text), this one still fails if a map access appears at all. The `toMatch` and `query_params` assertions are unchanged |--No other test changed what it asserts. `event.sql.test.ts`,-`profile.sql.test.ts` and `session.sql.test.ts` keep their expected SQL text-byte-for-byte; only their `filterClauses` INPUT fixtures changed, from-``compiledFilterClauses({ f0: "(path = '/')" })`` to ``{ f0: sql`(path = '/')` }``-— `compiledFilterClauses` was M12-002's text→fragment adapter for-`buildFilterWhere`'s output, and it dies here with the last text compiler, so-the fixtures build the fragment directly. `field-resolution.test.ts` is-untouched. No test was deleted, skipped or loosened; the only assertion added-anywhere is `table-filter-where.test.ts`'s params check (once per table, under-`describe.each`).--## Cases that return no rows, and why--Eleven of the 131 cases return zero matching rows on BOTH sides. Each is-listed here rather than hidden, per the recipe:--| case | why |-|---|---|-| `cohort resolvers / buildCohortMembershipQuery` | `cohort_members` is empty in the prod copy |-| `cohort resolvers / buildAllCohortsMembershipQuery` | same |-| `cohort / inCohort (cohortIds)` | same |-| `cohort / inCohort on the profiles table (profileIdExpr = id)` | same |-| `cohort / cohort:<id> filter name` | same |-| `profile-ref rewrite / a VALUE equal to a narrowed key is never rewritten` | negative control by construction: no profile has `properties['country'] = 'country'`. What it proves is the RENDERED pair, both of which keep the value bound/quoted rather than rewriting it to an identifier |-| `profile.properties.<key> / value with a quote` | no profile has `country = O'Brien`; the case exists for the escaping, which both sides agree on (V1 backslash-escapes, V2 never puts the value in the text) |-| `profile.properties.<key> / value with LIKE metacharacters (defect preserved)` | `a%b_` matches nothing; the case pins recipe trap 12 — the `%`/`_` stay wildcards on both sides |-| `value types / null value` | `properties['country'] = NULL` is never true. The binding itself (`NULL` keyword vs `Nullable(String)` param) is what the case pins |-| `group.* / group.name isNull` | every group reachable from this window has a non-empty name |-| `typed cast / boolean is (value true …)` | no `longitude` value is `true`/`1`/`yes`; the paired `value false` case matches 116,554 events |--## Numeric filter values bind as the type V1's literal had--V1 inlined a numeric filter value (`sqlstring.escape(5)` -> `5`) and let-ClickHouse infer the literal's type. A bound param has to **declare** one, so-`table-filter-where.ts`'s `valueParam` declares the type ClickHouse would have-inferred for the text V1 emitted, narrowest first — `5` is `UInt8`, `300`-`UInt16`, `-5` `Int8`, a fraction or an out-of-range magnitude `Float64`.-Declaring `Float64` for every number would bind a *different constant* from the-one V1 compared against, observable wherever the comparand's type takes part in-type resolution.--The mapping was cross-checked in one process against ClickHouse's own-inference: for each value, `toTypeName(<the text V1 emitted>)` from the server-vs the type the shipped compiler binds, read back out of the rendered clause-(`buildFilterWhere([{name: 'profile.properties.country', operator: 'is',-value: [v]}], …)`).--```-ok v1-literal=0 ch-infers=UInt8 v2-binds=UInt8-ok v1-literal=1 ch-infers=UInt8 v2-binds=UInt8-ok v1-literal=5 ch-infers=UInt8 v2-binds=UInt8-ok v1-literal=255 ch-infers=UInt8 v2-binds=UInt8-ok v1-literal=256 ch-infers=UInt16 v2-binds=UInt16-ok v1-literal=300 ch-infers=UInt16 v2-binds=UInt16-ok v1-literal=65535 ch-infers=UInt16 v2-binds=UInt16-ok v1-literal=65536 ch-infers=UInt32 v2-binds=UInt32-ok v1-literal=4294967295 ch-infers=UInt32 v2-binds=UInt32-ok v1-literal=4294967296 ch-infers=UInt64 v2-binds=UInt64-ok v1-literal=10000000000000000000 ch-infers=UInt64 v2-binds=UInt64-ok v1-literal=18446744073709552000 ch-infers=Float64 v2-binds=Float64-ok v1-literal=100000000000000000000 ch-infers=Float64 v2-binds=Float64-ok v1-literal=1e+21 ch-infers=Float64 v2-binds=Float64-ok v1-literal=-1 ch-infers=Int8 v2-binds=Int8-ok v1-literal=-5 ch-infers=Int8 v2-binds=Int8-ok v1-literal=-128 ch-infers=Int8 v2-binds=Int8-ok v1-literal=-129 ch-infers=Int16 v2-binds=Int16-ok v1-literal=-32768 ch-infers=Int16 v2-binds=Int16-ok v1-literal=-32769 ch-infers=Int32 v2-binds=Int32-ok v1-literal=-2147483648 ch-infers=Int32 v2-binds=Int32-ok v1-literal=-2147483649 ch-infers=Int64 v2-binds=Int64-ok v1-literal=-9223372036854776000 ch-infers=Float64 v2-binds=Float64-ok v1-literal=-100000000000000000000 ch-infers=Float64 v2-binds=Float64-ok v1-literal=5.5 ch-infers=Float64 v2-binds=Float64-ok v1-literal=10.5 ch-infers=Float64 v2-binds=Float64-ok v1-literal=-0.5 ch-infers=Float64 v2-binds=Float64-ok v1-literal=0.1 ch-infers=Float64 v2-binds=Float64-ALL 28 MATCH-```--The two boundary rows are why the type is derived from the *digits* V1 printed-rather than from the JS number: `String(2 ** 64)` and `String(-(2 ** 63))` both-render decimals outside the UInt64 / Int64 range, and ClickHouse types them-`Float64` — which is exactly what V1 fed it.--`filter-cast.ts`'s twin (`typedValueParam`, M12-002) needs none of this: on the-typed path every value is wrapped in `toFloat64OrNull(toString(…))` or a-sibling cast, which erases the declared type before anything else observes it.-The ten `typed cast` cases below are identical either way.--## The two IDENTICAL ERROR cases--Two cases are a V1 defect: the compiler happily emits `properties['<key>'] =-<number>` / `= <boolean>` against a `Map(String, String)`, which ClickHouse-rejects. Both sides fail, both with code **386 `NO_COMMON_TYPE`**, on the same-operand pair, with the same type pair, and neither returns a row. The defect is-reproduced, not fixed.--Their messages are recorded **in full, untruncated**, and they are not-byte-equal. The whole of the difference is that ClickHouse prints a bound-constant as `_CAST(<literal>, '<Type>'…)` in the `while executing …` expression-trace where it prints an inlined literal bare:--```--- numeric-V1: … arrayElement(__table1.properties, 'country'_String) String String(size = 0), 5_UInt8 UInt8 Const(size = 0, UInt8(size = 1)).-V2: … arrayElement(__table1.properties, 'country'_String) String String(size = 0), _CAST(5_UInt8, 'UInt8'_String) UInt8 Const(size = 0, UInt8(size = 1)).--- boolean-V1: … arrayElement(__table1.properties, 'country'_String) String String(size = 0), 1_Bool Bool Const(size = 0, UInt8(size = 1)).-V2: … arrayElement(__table1.properties, 'country'_String) String String(size = 0), _CAST(1_Bool, 'Bool'_String) Bool Const(size = 0, UInt8(size = 1)).-```--That token is a property of parameter binding itself — ADR-013's whole point —-and not of either file converted here. Control, with nothing from this module-in it:--```bash-# inlined literal-curl -sG 'http://127.0.0.1:8123/' --data-urlencode "query=SELECT 'a' = 5"-Code: 53. DB::Exception: Cannot convert string 'a' to type UInt8: In scope SELECT 'a' = 5. (TYPE_MISMATCH)--# the same query with the constant bound-curl -sG 'http://127.0.0.1:8123/' --data-urlencode "query=SELECT 'a' = {p1:UInt8}" --data-urlencode 'param_p1=5'-Code: 53. DB::Exception: Cannot convert string 'a' to type UInt8: In scope SELECT 'a' = _CAST(5, 'UInt8'). (TYPE_MISMATCH)--# a bound STRING param renders exactly like the inlined literal — which is why-# every other IDENTICAL ERROR case in this proof and in filter-where.sql.proof.md-# comes out byte-equal-curl -sG 'http://127.0.0.1:8123/' --data-urlencode "query=SELECT [1,2] = {p1:String}" --data-urlencode 'param_p1=a'-Code: 130. DB::Exception: Array does not start with '[' character: while converting 'a' to Array(UInt8): In scope SELECT [1, 2] = 'a'. (CANNOT_READ_ARRAY_FROM_TEXT)-curl -sG 'http://127.0.0.1:8123/' --data-urlencode "query=SELECT [1,2] = 'a'"-Code: 130. DB::Exception: Array does not start with '[' character: while converting 'a' to Array(UInt8): In scope SELECT [1, 2] = 'a'. (CANNOT_READ_ARRAY_FROM_TEXT)-```--So the residue is ClickHouse's rendering of a bound constant in a debug trace,-identical for every bound non-String param anywhere in the repository, and it-carries no result-set, error-code or type information that differs. What *was*-a real difference — the declared type, `Float64` where V1's literal was `UInt8`-— is fixed above, and both cases are `IDENTICAL ERROR` per the recipe (§5:-"both sides failing with the same ClickHouse error").--## Per-case results--`rows_read` and wall time differ run to run and between an inline literal and a-bound param — recorded, not chased (recipe, *Proof-file template*). `rows` is-the number of result rows, not the number of matched events; the matched counts-are in each case's `result` line below.--| branch | case | verdict | rows V1/V2 | rows_read V1/V2 | wall ms V1/V2 |-|---|---|---|---|---|---|-| getSelectPropertyKey | top-level column (no map match) | IDENTICAL | 20/20 | 90057/90057 | 32/23 |-| getSelectPropertyKey | camelCase alias normalised (referrerName) | IDENTICAL | 20/20 | 90057/90057 | 21/17 |-| getSelectPropertyKey | has_profile | IDENTICAL | 2/2 | 90057/90057 | 17/17 |-| getSelectPropertyKey | properties.<key> | IDENTICAL | 20/20 | 90057/90057 | 24/19 |-| getSelectPropertyKey | bare utm_source -> properties.__query.* | IDENTICAL | 12/12 | 90057/90057 | 16/21 |-| getSelectPropertyKey | wildcard -> mapExtractKeyLike | IDENTICAL | 20/20 | 90057/90057 | 27/23 |-| getSelectPropertyKey | nested .*. wildcard | IDENTICAL | 3/3 | 90057/90057 | 33/17 |-| getSelectPropertyKey | group.* via getGroupPropertySql (name) | IDENTICAL | 20/20 | 93416/93416 | 14/12 |-| getSelectPropertyKey | group.* with eventsAlias present (e.properties untouched) | IDENTICAL | 20/20 | 93416/93416 | 27/25 |-| getGroupPropertySql | name | IDENTICAL | 20/20 | 93416/93416 | 15/17 |-| getGroupPropertySql | type | IDENTICAL | 2/2 | 93416/93416 | 17/12 |-| getGroupPropertySql | properties.<key> | IDENTICAL | 3/3 | 93416/93416 | 17/23 |-| getGroupPropertySql | fallback _group_id | IDENTICAL | 20/20 | 93416/93416 | 24/22 |-| getGroupPropertySelect | name | IDENTICAL | 20/20 | 3359/3359 | 6/8 |-| getGroupPropertySelect | type | IDENTICAL | 1/1 | 3359/3359 | 7/7 |-| getGroupPropertySelect | id | IDENTICAL | 20/20 | 3359/3359 | 6/7 |-| getGroupPropertySelect | properties.<key> | IDENTICAL | 4/4 | 3359/3359 | 8/8 |-| getGroupPropertySelect | fallback id | IDENTICAL | 20/20 | 3359/3359 | 3/5 |-| getProfilePropertySelect | id | IDENTICAL | 20/20 | 310976/310976 | 45/46 |-| getProfilePropertySelect | first_name | IDENTICAL | 20/20 | 310976/310976 | 30/31 |-| getProfilePropertySelect | last_name | IDENTICAL | 20/20 | 310976/310976 | 30/31 |-| getProfilePropertySelect | email | IDENTICAL | 20/20 | 310976/310976 | 29/28 |-| getProfilePropertySelect | avatar | IDENTICAL | 1/1 | 310976/310976 | 29/34 |-| getProfilePropertySelect | created_at | IDENTICAL | 20/20 | 310976/310976 | 34/35 |-| getProfilePropertySelect | last_seen_at | IDENTICAL | 20/20 | 310976/310976 | 34/34 |-| getProfilePropertySelect | properties.<key> | IDENTICAL | 20/20 | 310976/310976 | 83/68 |-| getProfilePropertySelect | fallback id | IDENTICAL | 20/20 | 310976/310976 | 41/39 |-| cohort resolvers | buildCohortMembershipQuery | IDENTICAL | 1/1 | 0/0 | 4/3 |-| cohort resolvers | buildAllCohortsMembershipQuery | IDENTICAL | 1/1 | 0/0 | 3/3 |-| cohort resolvers | buildInlineCohortJoin | IDENTICAL | 1/1 | 90057/90057 | 13/14 |-| cohort resolvers | buildAllCohortsLabelExpr (with cohorts, quote in a name) | IDENTICAL | 1/1 | 1/1 | 3/4 |-| cohort resolvers | buildAllCohortsLabelExpr (matching id) | IDENTICAL | 2/2 | 2/2 | 5/3 |-| cohort resolvers | buildAllCohortsLabelExpr (no cohorts) | IDENTICAL | 1/1 | 1/1 | 3/2 |-| cohort resolvers | getCohortCteName | IDENTICAL | 1/1 | 1/1 | 2/3 |-| getSelectPropertyKey | cohort breakdown label (named cohort) | IDENTICAL | 2/2 | 90057/90057 | 18/14 |-| getSelectPropertyKey | cohort breakdown label (unnamed cohort) | IDENTICAL | 2/2 | 90057/90057 | 22/13 |-| profile-ref rewrite | narrowed key: CTE scalar column + rewritten ref | IDENTICAL | 20/20 | 401033/401033 | 101/84 |-| profile-ref rewrite | needsFullMap: Map still selected, ref still narrowed | IDENTICAL | 20/20 | 401033/401033 | 85/80 |-| profile-ref rewrite | no narrowed keys: full Map, ref untouched | IDENTICAL | 20/20 | 401033/401033 | 82/81 |-| profile-ref rewrite | a VALUE equal to a narrowed key is never rewritten | IDENTICAL | 1/1 | 401033/401033 | 74/76 |-| profile.properties.<key> | is (single value) | IDENTICAL | 1/1 | 310976/310976 | 65/66 |-| profile.properties.<key> | is (multi value -> IN) | IDENTICAL | 1/1 | 310976/310976 | 63/63 |-| profile.properties.<key> | isNot (single value) | IDENTICAL | 1/1 | 310976/310976 | 62/64 |-| profile.properties.<key> | isNot (multi value -> NOT IN) | IDENTICAL | 1/1 | 310976/310976 | 65/64 |-| profile.properties.<key> | contains (ILIKE) | IDENTICAL | 1/1 | 310976/310976 | 64/64 |-| profile.properties.<key> | doesNotContain (NOT ILIKE, AND joiner) | IDENTICAL | 1/1 | 310976/310976 | 63/65 |-| profile.properties.<key> | startsWith | IDENTICAL | 1/1 | 310976/310976 | 66/64 |-| profile.properties.<key> | endsWith | IDENTICAL | 1/1 | 310976/310976 | 62/65 |-| profile.properties.<key> | regex (match) | IDENTICAL | 1/1 | 310976/310976 | 67/64 |-| profile.properties.<key> | isNull (empty value array) | IDENTICAL | 1/1 | 310976/310976 | 63/63 |-| profile.properties.<key> | isNotNull (empty value array) | IDENTICAL | 1/1 | 310976/310976 | 65/64 |-| profile.properties.<key> | gt (non-numeric column) | IDENTICAL | 1/1 | 310976/310976 | 66/67 |-| profile.properties.<key> | lt (non-numeric column) | IDENTICAL | 1/1 | 310976/310976 | 67/62 |-| profile.properties.<key> | gte (non-numeric column) | IDENTICAL | 1/1 | 310976/310976 | 66/67 |-| profile.properties.<key> | lte (non-numeric column) | IDENTICAL | 1/1 | 310976/310976 | 65/64 |-| profile.properties.<key> | value with a quote | IDENTICAL | 1/1 | 310976/310976 | 60/63 |-| profile.properties.<key> | value with LIKE metacharacters (defect preserved) | IDENTICAL | 1/1 | 310976/310976 | 67/65 |-| profile.properties.<key> | empty value array with a value operator (dropped) | IDENTICAL (no clause emitted) | – | – | – |-| profile.<column> | is (single value) | IDENTICAL | 1/1 | 433856/433856 | 42/41 |-| profile.<column> | is (multi value -> IN) | IDENTICAL | 1/1 | 442048/442048 | 42/44 |-| profile.<column> | isNot (single value) | IDENTICAL | 1/1 | 18749152/18749152 | 1293/1289 |-| profile.<column> | isNot (multi value -> NOT IN) | IDENTICAL | 1/1 | 18749152/18749152 | 1292/1291 |-| profile.<column> | contains (ILIKE) | IDENTICAL | 1/1 | 310976/310976 | 30/29 |-| profile.<column> | doesNotContain (NOT ILIKE, AND joiner) | IDENTICAL | 1/1 | 310976/310976 | 33/33 |-| profile.<column> | startsWith | IDENTICAL | 1/1 | 310976/310976 | 36/30 |-| profile.<column> | endsWith | IDENTICAL | 1/1 | 310976/310976 | 30/29 |-| profile.<column> | regex (match) | IDENTICAL | 1/1 | 310976/310976 | 32/31 |-| profile.<column> | isNull (empty value array) | IDENTICAL | 1/1 | 310976/310976 | 33/32 |-| profile.<column> | isNotNull (empty value array) | IDENTICAL | 1/1 | 310976/310976 | 30/29 |-| profile.<numeric column> | isNot on created_at (toFloat64 both sides) | IDENTICAL | 1/1 | 310976/310976 | 31/32 |-| profile.<numeric column> | gt on created_at (toFloat64 both sides) | IDENTICAL | 1/1 | 139104/139104 | 21/22 |-| profile.<numeric column> | lt on created_at (toFloat64 both sides) | IDENTICAL | 1/1 | 122880/122880 | 19/16 |-| profile.<numeric column> | gte on created_at (toFloat64 both sides) | IDENTICAL | 1/1 | 139104/139104 | 22/20 |-| profile.<numeric column> | lte on created_at (toFloat64 both sides) | IDENTICAL | 1/1 | 122880/122880 | 18/16 |-| profile.<numeric column> | is on created_at (exact unix second) | IDENTICAL | 1/1 | 73728/73728 | 10/11 |-| profile.<numeric column> | gte on last_seen_at | IDENTICAL | 1/1 | 310976/310976 | 37/29 |-| profile.* cross-table | events: wraps in profile_id IN (SELECT id FROM profiles …) | IDENTICAL | 1/1 | 540281/540281 | 40/38 |-| profile.* cross-table | sessions: wraps in profile_id IN (SELECT id FROM profiles …) | IDENTICAL | 1/1 | 376412/376412 | 37/38 |-| profile.* cross-table | unknown profile field is dropped | IDENTICAL (no clause emitted) | – | – | – |-| value types | numeric value on a String property (both sides fail, code 386) | **IDENTICAL ERROR** | –/– | –/– | 16/4 |-| value types | numeric value on a numeric column (session.duration) | IDENTICAL | 1/1 | 32720/32720 | 10/10 |-| value types | numeric value, gt on a numeric column (toFloat64 both sides) | IDENTICAL | 1/1 | 32720/32720 | 10/11 |-| value types | fractional numeric value on a numeric column | IDENTICAL | 1/1 | 32720/32720 | 16/9 |-| value types | boolean value (escape(true) -> Bool param) | **IDENTICAL ERROR** | –/– | –/– | 7/5 |-| value types | null value (escape(null) -> Nullable(String) param) | IDENTICAL | 1/1 | 0/0 | 5/4 |-| group.* | group.name is | IDENTICAL | 1/1 | 232664/232664 | 14/13 |-| group.* | group.name is (multi -> IN) | IDENTICAL | 1/1 | 232664/232664 | 11/13 |-| group.* | group.name isNot | IDENTICAL | 1/1 | 232664/232664 | 19/14 |-| group.* | group.name contains | IDENTICAL | 1/1 | 232664/232664 | 14/16 |-| group.* | group.name doesNotContain | IDENTICAL | 1/1 | 232664/232664 | 14/16 |-| group.* | group.name startsWith | IDENTICAL | 1/1 | 232664/232664 | 10/10 |-| group.* | group.name endsWith | IDENTICAL | 1/1 | 232664/232664 | 12/13 |-| group.* | group.name regex | IDENTICAL | 1/1 | 232664/232664 | 13/12 |-| group.* | group.name isNull | IDENTICAL | 1/1 | 232664/232664 | 9/12 |-| group.* | group.name isNotNull | IDENTICAL | 1/1 | 232664/232664 | 21/21 |-| group.* | group.type is | IDENTICAL | 1/1 | 232664/232664 | 18/25 |-| group.* | group.properties.<key> isNotNull | IDENTICAL | 1/1 | 232664/232664 | 17/17 |-| group.* | group.<unknown> falls back to id | IDENTICAL | 1/1 | 232664/232664 | 14/17 |-| group.* | no groupsExpr -> dropped | IDENTICAL (no clause emitted) | – | – | – |-| session.* | session.duration gt (numeric column) | IDENTICAL | 1/1 | 32720/32720 | 9/10 |-| session.* | session.event_count gte | IDENTICAL | 1/1 | 24553/24553 | 13/16 |-| session.* | session.screen_view_count lt | IDENTICAL | 1/1 | 32720/32720 | 20/18 |-| session.* | session.revenue lte | IDENTICAL | 1/1 | 32720/32720 | 14/9 |-| session.* | session.is_bounce true | IDENTICAL | 1/1 | 32720/32720 | 10/12 |-| session.* | session.is_bounce false | IDENTICAL | 1/1 | 32720/32720 | 9/8 |-| session.* | session.is_bounce isNot true (negates) | IDENTICAL | 1/1 | 32720/32720 | 8/9 |-| session.* | session.is_bounce empty value -> dropped | IDENTICAL (no clause emitted) | – | – | – |-| session.* | session.performed_event (single value) | IDENTICAL | 1/1 | 671556/671556 | 48/46 |-| session.* | session.performed_event (multi -> IN) | IDENTICAL | 1/1 | 671556/671556 | 49/41 |-| session.* | session.performed_event isNot -> NOT IN | IDENTICAL | 1/1 | 671556/671556 | 35/43 |-| session.* | session.performed_event with a date scope | IDENTICAL | 1/1 | 171877/171877 | 23/51 |-| session.* | session.performed_event empty value -> dropped | IDENTICAL (no clause emitted) | – | – | – |-| session.* | session.<unknown> -> dropped | IDENTICAL (no clause emitted) | – | – | – |-| session.* | session.* on a non-sessions table -> dropped | IDENTICAL (no clause emitted) | – | – | – |-| cohort | inCohort (cohortIds) | IDENTICAL | 1/1 | 0/0 | 10/10 |-| cohort | notInCohort | IDENTICAL | 1/1 | 229305/229305 | 16/15 |-| cohort | inCohort on the profiles table (profileIdExpr = id) | IDENTICAL | 1/1 | 0/0 | 7/7 |-| cohort | cohort:<id> filter name | IDENTICAL | 1/1 | 0/0 | 6/7 |-| cohort | inCohort with no ids -> dropped | IDENTICAL (no clause emitted) | – | – | – |-| typed cast | number is on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 73/66 |-| typed cast | number gt on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 68/66 |-| typed cast | number isNot (AND joiner) on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 67/82 |-| typed cast | boolean is (value true — no truthy longitude here, 0 rows both sides) on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 63/63 |-| typed cast | boolean is (value false — matches every non-truthy row) on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 67/66 |-| typed cast | date gte on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 64/65 |-| typed cast | datetime lt on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 63/65 |-| typed cast | string type falls through to the raw path on profile.properties.longitude | IDENTICAL | 1/1 | 310976/310976 | 64/61 |-| typed cast | number gte on a group property | IDENTICAL | 1/1 | 232664/232664 | 13/14 |-| typed cast | number gt on a session numeric column | IDENTICAL | 1/1 | 32720/32720 | 9/9 |-| ignored | properties.* on the profiles table -> dropped | IDENTICAL (no clause emitted) | – | – | – |-| ignored | bare column -> dropped | IDENTICAL (no clause emitted) | – | – | – |--## Rendered statements, one per case--Every V1 statement below was produced by CALLING the V1 compiler, not retyped.-Each pair is reproducible with `curl 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC'`,-binding V2's params as `param_pN=`.----### getSelectPropertyKey--**top-level column (no map match)** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 90057/90057; wall V1/V2 = 32 ms / 23 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT country AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT country AS v, count() AS c FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"US","c":43329},{"v":"SG","c":3873},{"v":"GB","c":3484},{"v":"IN","c":3110},{"v":"CA","c":2782},{"v":"ES","c":2368},{"v":"PL","c":2250},{"v":"JP","c":1448},{"v":"MX","c":1335},{"v":"BR","c":1214},{"v":"SE","c":1154},{"v":"CN","c":1041},{"v":"ZA","c":982},{"v":"NL","c":698},{"v":"TR","c":656},{"v":"IT","c":634},{"v":"BG","c":541},{"v":"DE","c":427},{"v":"PK","c":408},{"v":"FR","c":381}]`--**camelCase alias normalised (referrerName)** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 90057/90057; wall V1/V2 = 21 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT referrer_name AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT referrer_name AS v, count() AS c FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00"}-```--result (both sides): 20 rows, first: `{"v":"Google","c":58439}`--**has_profile** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 90057/90057; wall V1/V2 = 17 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT if(profile_id != device_id, 'true', 'false') AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT if(profile_id != device_id, 'true', 'false') AS v, count() AS c FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"false","c":74044},{"v":"true","c":2841}]`--**properties.<key>** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 90057/90057; wall V1/V2 = 24 ms / 19 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT properties['__title'] AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT properties[{p1:String}] AS v, count() AS c FROM events WHERE project_id = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"__title","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): 20 rows, first: `{"v":"","c":23963}`--**bare utm_source -> properties.__query.*** — IDENTICAL; rows V1/V2 = 12/12; rows_read V1/V2 = 90057/90057; wall V1/V2 = 16 ms / 21 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT properties['__query.utm_source'] AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT properties[{p1:String}] AS v, count() AS c FROM events WHERE project_id = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"__query.utm_source","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"","c":76810},{"v":"chatgpt.com","c":41},{"v":"netranks","c":11},{"v":"www.theaienterprise.io","c":9},{"v":"dbt","c":3},{"v":"10words","c":2},{"v":"gralio.ai","c":2},{"v":"under%25252525252525252525252525252525252520site","c":2},{"v":"you.com","c":2},{"v":"aem-abm","c":1},{"v":"employsome","c":1},{"v":"infomotion","c":1}]`--**wildcard -> mapExtractKeyLike** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 90057/90057; wall V1/V2 = 27 ms / 23 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%'))) AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, {p1:String}))) AS v, count() AS c FROM events WHERE project_id = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"__query.%","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): 20 rows, first: `{"v":[],"c":74809}`--**nested .*. wildcard** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 90057/90057; wall V1/V2 = 33 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%.type'))) AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, {p1:String}))) AS v, count() AS c FROM events WHERE project_id = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"__query.%.type","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":[],"c":76823},{"v":["login"],"c":57},{"v":["signup"],"c":5}]`--**group.* via getGroupPropertySql (name)** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 93416/93416; wall V1/V2 = 14 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT _g.name AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT _g.name AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = {p2:String} AND e.created_at >= toDateTime({p3:String}) AND e.created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): 20 rows, first: `{"v":"","c":1856}`--**group.* with eventsAlias present (e.properties untouched)** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 93416/93416; wall V1/V2 = 27 ms / 25 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT e.properties['__title'] AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT e.properties[{p2:String}] AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = {p3:String} AND e.created_at >= toDateTime({p4:String}) AND e.created_at < toDateTime({p5:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"__title","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): 20 rows, first: `{"v":"","c":349}`---### getGroupPropertySql--**name** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 93416/93416; wall V1/V2 = 15 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT _g.name AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT _g.name AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = {p2:String} AND e.created_at >= toDateTime({p3:String}) AND e.created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): 20 rows, first: `{"v":"","c":1856}`--**type** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 93416/93416; wall V1/V2 = 17 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT _g.type AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT _g.type AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = {p2:String} AND e.created_at >= toDateTime({p3:String}) AND e.created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"","c":1856},{"v":"company","c":997}]`--**properties.<key>** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 93416/93416; wall V1/V2 = 17 ms / 23 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT _g.properties['employees'] AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT _g.properties[{p2:String}] AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = {p3:String} AND e.created_at >= toDateTime({p4:String}) AND e.created_at < toDateTime({p5:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"employees","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"","c":1924},{"v":"1","c":859},{"v":"201","c":70}]`--**fallback _group_id** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 93416/93416; wall V1/V2 = 24 ms / 22 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT _group_id AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT _group_id AS v, count() AS c FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE e.project_id = {p2:String} AND e.created_at >= toDateTime({p3:String}) AND e.created_at < toDateTime({p4:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"2026-07-08 00:00:00"}-```--result (both sides): 20 rows, first: `{"v":"1316","c":830}`---### getGroupPropertySelect--**name** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 3359/3359; wall V1/V2 = 6 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT name AS v, count() AS c FROM groups FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT name AS v, count() AS c FROM groups FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"Secureprivacy","c":2}`--**type** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3359/3359; wall V1/V2 = 7 ms / 7 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT type AS v, count() AS c FROM groups FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT type AS v, count() AS c FROM groups FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): `[{"v":"company","c":347}]`--**id** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 3359/3359; wall V1/V2 = 6 ms / 7 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT id AS v, count() AS c FROM groups FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT id AS v, count() AS c FROM groups FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"10070","c":1}`--**properties.<key>** — IDENTICAL; rows V1/V2 = 4/4; rows_read V1/V2 = 3359/3359; wall V1/V2 = 8 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT properties['employees'] AS v, count() AS c FROM groups FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT properties[{p1:String}] AS v, count() AS c FROM groups FINAL WHERE project_id = {p2:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"employees","p2":"secure-privacy"}-```--result (both sides): `[{"v":"1","c":287},{"v":"","c":50},{"v":"201","c":9},{"v":"5001","c":1}]`--**fallback id** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 3359/3359; wall V1/V2 = 3 ms / 5 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT id AS v, count() AS c FROM groups FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT id AS v, count() AS c FROM groups FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"10070","c":1}`---### getProfilePropertySelect--**id** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 45 ms / 46 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT id AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT id AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"0000b966f4b0ac3190d964dc7990f4b6","c":1}`--**first_name** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 30 ms / 31 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT first_name AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT first_name AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"","c":118176}`--**last_name** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 30 ms / 31 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT last_name AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT last_name AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"","c":118345}`--**email** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 29 ms / 28 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT email AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT email AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"","c":117249}`--**avatar** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 29 ms / 34 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT avatar AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT avatar AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): `[{"v":"","c":118502}]`--**created_at** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 34 ms / 35 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT created_at AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT created_at AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"2026-07-30 10:18:52.000","c":40}`--**last_seen_at** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 34 ms / 34 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT last_seen_at AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT last_seen_at AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"2026-07-30 10:18:52.000","c":40}`--**properties.<key>** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 83 ms / 68 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT properties['country'] AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT properties[{p1:String}] AS v, count() AS c FROM profiles FINAL WHERE project_id = {p2:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"country","p2":"secure-privacy"}-```--result (both sides): `[{"v":"US","c":59816},{"v":"SG","c":12759},{"v":"GB","c":5163},{"v":"IN","c":4789},{"v":"CA","c":3673},{"v":"PL","c":2944},{"v":"CN","c":2558},{"v":"ES","c":2328},{"v":"MX","c":2024},{"v":"BR","c":1878},{"v":"DE","c":1847},{"v":"JP","c":1819},{"v":"SE","c":1579},{"v":"ZA","c":1326},{"v":"IT","c":1298},{"v":"TR","c":938},{"v":"NL","c":859},{"v":"BD","c":768},{"v":"FR","c":691},{"v":"PK","c":583}]`--**fallback id** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 310976/310976; wall V1/V2 = 41 ms / 39 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT id AS v, count() AS c FROM profiles FINAL WHERE project_id = 'secure-privacy' GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT id AS v, count() AS c FROM profiles FINAL WHERE project_id = {p1:String} GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): 20 rows, first: `{"v":"0000b966f4b0ac3190d964dc7990f4b6","c":1}`---### cohort resolvers--**buildCohortMembershipQuery** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 4 ms / 3 ms; clickhouse_settings: session_timezone=UTC (both).--cohort_members is empty here — 0-row statement equivalence.--```sql--- V1-SELECT count() AS c FROM (- SELECT profile_id- FROM cohort_members FINAL- WHERE cohort_id = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'- AND project_id = 'secure-privacy'- )--- V2-SELECT count() AS c FROM (- SELECT profile_id- FROM cohort_members FINAL- WHERE cohort_id = {p1:String}- AND project_id = {p2:String}- )--- V2 params: {"p1":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","p2":"secure-privacy"}-```--result (both sides): `[{"c":0}]`--**buildAllCohortsMembershipQuery** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 3 ms / 3 ms; clickhouse_settings: session_timezone=UTC (both).--cohort_members is empty here — 0-row statement equivalence.--```sql--- V1-SELECT count() AS c FROM (- SELECT profile_id, cohort_id- FROM cohort_members FINAL- WHERE project_id = 'secure-privacy'- )--- V2-SELECT count() AS c FROM (- SELECT profile_id, cohort_id- FROM cohort_members FINAL- WHERE project_id = {p1:String}- )--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): `[{"c":0}]`--**buildInlineCohortJoin** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 90057/90057; wall V1/V2 = 13 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c FROM events LEFT ANY JOIN (- SELECT profile_id- FROM cohort_members FINAL- WHERE cohort_id = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'- AND project_id = 'secure-privacy'- ) AS cohort_aaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee ON cohort_aaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee.profile_id = events.profile_id WHERE events.project_id = 'secure-privacy' AND events.created_at >= toDateTime('2026-07-01 00:00:00') AND events.created_at < toDateTime('2026-07-08 00:00:00')--- V2-SELECT count() AS c FROM events LEFT ANY JOIN (- SELECT profile_id- FROM cohort_members FINAL- WHERE cohort_id = {p1:String}- AND project_id = {p2:String}- ) AS cohort_aaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee ON cohort_aaaaaaaa_bbbb_cccc_dddd_eeeeeeeeeeee.profile_id = events.profile_id WHERE events.project_id = {p3:String} AND events.created_at >= toDateTime({p4:String}) AND events.created_at < toDateTime({p5:String})--- V2 params: {"p1":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","p2":"secure-privacy","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): `[{"c":76885}]`--**buildAllCohortsLabelExpr (with cohorts, quote in a name)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1/1; wall V1/V2 = 3 ms / 4 ms; clickhouse_settings: session_timezone=UTC (both).--cohort_members is empty, so the label is exercised over a synthetic one-row cohort_id.--```sql--- V1-SELECT transform(_all_cohorts.cohort_id, ['aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', '11111111-2222-3333-4444-555555555555'], ['Power users', 'O\'Brien\'s list'], 'Unknown') AS v, count() AS c FROM (SELECT 'zzz' AS cohort_id) AS _all_cohorts GROUP BY v--- V2-SELECT transform(_all_cohorts.cohort_id, {p1:Array(String)}, {p2:Array(String)}, {p3:String}) AS v, count() AS c FROM (SELECT 'zzz' AS cohort_id) AS _all_cohorts GROUP BY v--- V2 params: {"p1":["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","11111111-2222-3333-4444-555555555555"],"p2":["Power users","O'Brien's list"],"p3":"Unknown"}-```--result (both sides): `[{"v":"Unknown","c":1}]`--**buildAllCohortsLabelExpr (matching id)** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 2/2; wall V1/V2 = 5 ms / 3 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT transform(_all_cohorts.cohort_id, ['aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', '11111111-2222-3333-4444-555555555555'], ['Power users', 'O\'Brien\'s list'], 'Unknown') AS v, count() AS c FROM (SELECT 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' AS cohort_id UNION ALL SELECT '11111111-2222-3333-4444-555555555555') AS _all_cohorts GROUP BY v ORDER BY v--- V2-SELECT transform(_all_cohorts.cohort_id, {p1:Array(String)}, {p2:Array(String)}, {p3:String}) AS v, count() AS c FROM (SELECT {p4:String} AS cohort_id UNION ALL SELECT {p5:String}) AS _all_cohorts GROUP BY v ORDER BY v--- V2 params: {"p1":["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","11111111-2222-3333-4444-555555555555"],"p2":["Power users","O'Brien's list"],"p3":"Unknown","p4":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","p5":"11111111-2222-3333-4444-555555555555"}-```--result (both sides): `[{"v":"O'Brien's list","c":1},{"v":"Power users","c":1}]`--**buildAllCohortsLabelExpr (no cohorts)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1/1; wall V1/V2 = 3 ms / 2 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'Unknown' AS v, count() AS c FROM (SELECT 'zzz' AS cohort_id) AS _all_cohorts GROUP BY v--- V2-SELECT {p1:String} AS v, count() AS c FROM (SELECT 'zzz' AS cohort_id) AS _all_cohorts GROUP BY v--- V2 params: {"p1":"Unknown"}-```--result (both sides): `[{"v":"Unknown","c":1}]`--**getCohortCteName** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1/1; wall V1/V2 = 2 ms / 3 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH `cohort-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee` AS (SELECT 1 AS x) SELECT count() AS c FROM `cohort-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee`--- V2-WITH `cohort-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee` AS (SELECT 1 AS x) SELECT count() AS c FROM `cohort-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee`--- V2 params: {}-```--result (both sides): `[{"c":1}]`---### getSelectPropertyKey--**cohort breakdown label (named cohort)** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 90057/90057; wall V1/V2 = 18 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).--The cohort JOIN alias is replaced by `profile_id` on BOTH sides so the label expression itself is exercised against real rows (cohort_members is empty).--```sql--- V1-SELECT if(notEmpty(profile_id), 'Power users', 'Not Power users') AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT if(notEmpty(profile_id), {p1:String}, {p2:String}) AS v, count() AS c FROM events WHERE project_id = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at < toDateTime({p5:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"Power users","p2":"Not Power users","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"Power users","c":76568},{"v":"Not Power users","c":317}]`--**cohort breakdown label (unnamed cohort)** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 90057/90057; wall V1/V2 = 22 ms / 13 ms; clickhouse_settings: session_timezone=UTC (both).--Same alias substitution as the case above.--```sql--- V1-SELECT if(notEmpty(profile_id), 'In Cohort', 'Not In Cohort') AS v, count() AS c FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-SELECT if(notEmpty(profile_id), {p1:String}, {p2:String}) AS v, count() AS c FROM events WHERE project_id = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at < toDateTime({p5:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"In Cohort","p2":"Not In Cohort","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"In Cohort","c":76568},{"v":"Not In Cohort","c":317}]`---### profile-ref rewrite--**narrowed key: CTE scalar column + rewritten ref** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 401033/401033; wall V1/V2 = 101 ms / 84 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties['country'] as `profile.properties.country` FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT `profile.properties.country` AS v, count() AS c FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH profile AS (SELECT id as "profile.id", properties[{p1:String}] as `profile.properties.country` FROM profiles FINAL WHERE project_id = {p2:String}) SELECT `profile.properties.country` AS v, count() AS c FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = {p3:String} AND e.created_at >= toDateTime({p4:String}) AND e.created_at < toDateTime({p5:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"country","p2":"secure-privacy","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"US","c":42927},{"v":"SG","c":3854},{"v":"GB","c":3486},{"v":"IN","c":2941},{"v":"CA","c":2782},{"v":"PL","c":2196},{"v":"ES","c":2077},{"v":"","c":1832},{"v":"JP","c":1434},{"v":"MX","c":1335},{"v":"BR","c":1214},{"v":"SE","c":1138},{"v":"CN","c":1030},{"v":"ZA","c":977},{"v":"NL","c":677},{"v":"TR","c":643},{"v":"IT","c":626},{"v":"BG","c":537},{"v":"PK","c":377},{"v":"FR","c":372}]`--**needsFullMap: Map still selected, ref still narrowed** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 401033/401033; wall V1/V2 = 85 ms / 80 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties['country'] as `profile.properties.country`, properties as "profile.properties" FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT `profile.properties.country` AS v, count() AS c FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH profile AS (SELECT id as "profile.id", properties[{p1:String}] as `profile.properties.country`, properties as "profile.properties" FROM profiles FINAL WHERE project_id = {p2:String}) SELECT `profile.properties.country` AS v, count() AS c FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = {p3:String} AND e.created_at >= toDateTime({p4:String}) AND e.created_at < toDateTime({p5:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"country","p2":"secure-privacy","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"US","c":42927},{"v":"SG","c":3854},{"v":"GB","c":3486},{"v":"IN","c":2941},{"v":"CA","c":2782},{"v":"PL","c":2196},{"v":"ES","c":2077},{"v":"","c":1832},{"v":"JP","c":1434},{"v":"MX","c":1335},{"v":"BR","c":1214},{"v":"SE","c":1138},{"v":"CN","c":1030},{"v":"ZA","c":977},{"v":"NL","c":677},{"v":"TR","c":643},{"v":"IT","c":626},{"v":"BG","c":537},{"v":"PK","c":377},{"v":"FR","c":372}]`--**no narrowed keys: full Map, ref untouched** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 401033/401033; wall V1/V2 = 82 ms / 81 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties as "profile.properties" FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT profile.properties['country'] AS v, count() AS c FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2-WITH profile AS (SELECT id as "profile.id", properties as "profile.properties" FROM profiles FINAL WHERE project_id = {p1:String}) SELECT profile.properties[{p2:String}] AS v, count() AS c FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = {p3:String} AND e.created_at >= toDateTime({p4:String}) AND e.created_at < toDateTime({p5:String}) GROUP BY v ORDER BY c DESC, toString(v) ASC LIMIT 20--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00"}-```--result (both sides): `[{"v":"US","c":42927},{"v":"SG","c":3854},{"v":"GB","c":3486},{"v":"IN","c":2941},{"v":"CA","c":2782},{"v":"PL","c":2196},{"v":"ES","c":2077},{"v":"","c":1832},{"v":"JP","c":1434},{"v":"MX","c":1335},{"v":"BR","c":1214},{"v":"SE","c":1138},{"v":"CN","c":1030},{"v":"ZA","c":977},{"v":"NL","c":677},{"v":"TR","c":643},{"v":"IT","c":626},{"v":"BG","c":537},{"v":"PK","c":377},{"v":"FR","c":372}]`--**a VALUE equal to a narrowed key is never rewritten** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 401033/401033; wall V1/V2 = 74 ms / 76 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties['country'] as `profile.properties.country` FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT count() AS c, uniq(e.profile_id) AS u FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') AND `profile.properties.country` = 'country'--- V2-WITH profile AS (SELECT id as "profile.id", properties[{p1:String}] as `profile.properties.country` FROM profiles FINAL WHERE project_id = {p2:String}) SELECT count() AS c, uniq(e.profile_id) AS u FROM events e LEFT ANY JOIN profile ON profile.id = e.profile_id WHERE e.project_id = {p3:String} AND e.created_at >= toDateTime({p4:String}) AND e.created_at < toDateTime({p5:String}) AND `profile.properties.country` = {p6:String}--- V2 params: {"p1":"country","p2":"secure-privacy","p3":"secure-privacy","p4":"2026-07-01 00:00:00","p5":"2026-07-08 00:00:00","p6":"country"}-```--result (both sides): `[{"c":0,"u":0}]`---### profile.properties.<key>--**is (single value)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 65 ms / 66 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (properties['country'] = 'US')--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (properties[{p2:String}] = {p3:String})--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"US"}-```--result (both sides): `[{"c":59816,"u":59815}]`--**is (multi value -> IN)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 63 ms / 63 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (properties['country'] IN ('US', 'SE'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (properties[{p2:String}] IN {p3:Array(String)})--- V2 params: {"p1":"secure-privacy","p2":"country","p3":["US","SE"]}-```--result (both sides): `[{"c":61395,"u":61394}]`--**isNot (single value)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 62 ms / 64 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (properties['country'] != 'US')--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (properties[{p2:String}] != {p3:String})--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"US"}-```--result (both sides): `[{"c":58686,"u":58684}]`--**isNot (multi value -> NOT IN)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 65 ms / 64 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (properties['country'] NOT IN ('US', 'SE'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (properties[{p2:String}] NOT IN {p3:Array(String)})--- V2 params: {"p1":"secure-privacy","p2":"country","p3":["US","SE"]}-```--result (both sides): `[{"c":57107,"u":57105}]`--**contains (ILIKE)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 64 ms / 64 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] ILIKE '%u%'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] ILIKE {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"%u%"}-```--result (both sides): `[{"c":60860,"u":60859}]`--**doesNotContain (NOT ILIKE, AND joiner)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 63 ms / 65 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] NOT ILIKE '%u%' AND properties['country'] NOT ILIKE '%s%'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] NOT ILIKE {p3:String} AND properties[{p4:String}] NOT ILIKE {p5:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"%u%","p4":"country","p5":"%s%"}-```--result (both sides): `[{"c":40583,"u":40583}]`--**startsWith** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 66 ms / 64 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] ILIKE 'U%'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] ILIKE {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"U%"}-```--result (both sides): `[{"c":60148,"u":60147}]`--**endsWith** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 62 ms / 65 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] ILIKE '%E'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] ILIKE {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"%E"}-```--result (both sides): `[{"c":4602,"u":4602}]`--**regex (match)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 67 ms / 64 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((match(properties['country'], '^U')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((match(properties[{p2:String}], {p3:String})))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"^U"}-```--result (both sides): `[{"c":60148,"u":60147}]`--**isNull (empty value array)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 63 ms / 63 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] = '' OR properties['country'] IS NULL))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] = '' OR properties[{p3:String}] IS NULL))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"country"}-```--result (both sides): `[{"c":2,"u":2}]`--**isNotNull (empty value array)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 65 ms / 64 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] != '' AND properties['country'] IS NOT NULL))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] != '' AND properties[{p3:String}] IS NOT NULL))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"country"}-```--result (both sides): `[{"c":118500,"u":118461}]`--**gt (non-numeric column)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 66 ms / 67 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] > 'S'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] > {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"S"}-```--result (both sides): `[{"c":77915,"u":77720}]`--**lt (non-numeric column)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 67 ms / 62 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] < 'S'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] < {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"S"}-```--result (both sides): `[{"c":40587,"u":40587}]`--**gte (non-numeric column)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 66 ms / 67 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] >= 'S'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] >= {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"S"}-```--result (both sides): `[{"c":77915,"u":77720}]`--**lte (non-numeric column)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 65 ms / 64 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] <= 'S'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] <= {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"S"}-```--result (both sides): `[{"c":40587,"u":40587}]`--**value with a quote** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 60 ms / 63 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (properties['country'] = 'O\'Brien')--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (properties[{p2:String}] = {p3:String})--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"O'Brien"}-```--result (both sides): `[{"c":0,"u":0}]`--**value with LIKE metacharacters (defect preserved)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 67 ms / 65 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] ILIKE '%a%b_%'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((properties[{p2:String}] ILIKE {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"country","p3":"%a%b_%"}-```--result (both sides): `[{"c":0,"u":0}]`--**empty value array with a value operator (dropped)** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```---### profile.<column>--**is (single value)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 433856/433856; wall V1/V2 = 42 ms / 41 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (email = '[email protected]')--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (email = {p2:String})--- V2 params: {"p1":"secure-privacy","p2":"[email protected]"}-```--result (both sides): `[{"c":2,"u":2}]`--**is (multi value -> IN)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 442048/442048; wall V1/V2 = 42 ms / 44 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (email IN ('[email protected]', '[email protected]'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (email IN {p2:Array(String)})--- V2 params: {"p1":"secure-privacy","p2":["[email protected]","[email protected]"]}-```--result (both sides): `[{"c":4,"u":4}]`--**isNot (single value)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 18749152/18749152; wall V1/V2 = 1293 ms / 1289 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (email != '[email protected]')--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (email != {p2:String})--- V2 params: {"p1":"secure-privacy","p2":"[email protected]"}-```--result (both sides): `[{"c":118500,"u":118461}]`--**isNot (multi value -> NOT IN)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 18749152/18749152; wall V1/V2 = 1292 ms / 1291 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (email NOT IN ('[email protected]', '[email protected]'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (email NOT IN {p2:Array(String)})--- V2 params: {"p1":"secure-privacy","p2":["[email protected]","[email protected]"]}-```--result (both sides): `[{"c":118498,"u":118456}]`--**contains (ILIKE)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 30 ms / 29 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((email ILIKE '%gmail%'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((email ILIKE {p2:String}))--- V2 params: {"p1":"secure-privacy","p2":"%gmail%"}-```--result (both sides): `[{"c":861,"u":861}]`--**doesNotContain (NOT ILIKE, AND joiner)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 33 ms / 33 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((email NOT ILIKE '%gmail%' AND email NOT ILIKE '%yahoo%'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((email NOT ILIKE {p2:String} AND email NOT ILIKE {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":"%gmail%","p3":"%yahoo%"}-```--result (both sides): `[{"c":117640,"u":117534}]`--**startsWith** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 36 ms / 30 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((email ILIKE 'j%'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((email ILIKE {p2:String}))--- V2 params: {"p1":"secure-privacy","p2":"j%"}-```--result (both sides): `[{"c":62,"u":62}]`--**endsWith** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 30 ms / 29 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((email ILIKE '%.com'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((email ILIKE {p2:String}))--- V2 params: {"p1":"secure-privacy","p2":"%.com"}-```--result (both sides): `[{"c":1128,"u":1128}]`--**regex (match)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 32 ms / 31 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((match(email, 'gmail')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((match(email, {p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"gmail"}-```--result (both sides): `[{"c":861,"u":861}]`--**isNull (empty value array)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 33 ms / 32 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((email = '' OR email IS NULL))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((email = '' OR email IS NULL))--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): `[{"c":117249,"u":117120}]`--**isNotNull (empty value array)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 30 ms / 29 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((email != '' AND email IS NOT NULL))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((email != '' AND email IS NOT NULL))--- V2 params: {"p1":"secure-privacy"}-```--result (both sides): `[{"c":1253,"u":1253}]`---### profile.<numeric column>--**isNot on created_at (toFloat64 both sides)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 31 ms / 32 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64(created_at) != toFloat64('1785000000')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64(created_at) != toFloat64({p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"1785000000"}-```--result (both sides): `[{"c":118502,"u":118465}]`--**gt on created_at (toFloat64 both sides)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 139104/139104; wall V1/V2 = 21 ms / 22 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64(created_at) > toFloat64('1785000000')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64(created_at) > toFloat64({p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"1785000000"}-```--result (both sides): `[{"c":51926,"u":51926}]`--**lt on created_at (toFloat64 both sides)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 122880/122880; wall V1/V2 = 19 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64(created_at) < toFloat64('1785000000')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64(created_at) < toFloat64({p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"1785000000"}-```--result (both sides): `[{"c":66576,"u":66464}]`--**gte on created_at (toFloat64 both sides)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 139104/139104; wall V1/V2 = 22 ms / 20 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64(created_at) >= toFloat64('1785000000')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64(created_at) >= toFloat64({p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"1785000000"}-```--result (both sides): `[{"c":51926,"u":51926}]`--**lte on created_at (toFloat64 both sides)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 122880/122880; wall V1/V2 = 18 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64(created_at) <= toFloat64('1785000000')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64(created_at) <= toFloat64({p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"1785000000"}-```--result (both sides): `[{"c":66576,"u":66464}]`--**is on created_at (exact unix second)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 73728/73728; wall V1/V2 = 10 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64(created_at) = toFloat64('1782864003')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64(created_at) = toFloat64({p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"1782864003"}-```--result (both sides): `[{"c":1,"u":1}]`--**gte on last_seen_at** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 37 ms / 29 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64(last_seen_at) >= toFloat64('1785000000')))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64(last_seen_at) >= toFloat64({p2:String})))--- V2 params: {"p1":"secure-privacy","p2":"1785000000"}-```--result (both sides): `[{"c":52068,"u":52068}]`---### profile.* cross-table--**events: wraps in profile_id IN (SELECT id FROM profiles …)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 540281/540281; wall V1/V2 = 40 ms / 38 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id IN (SELECT id FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (email != '' AND email IS NOT NULL)))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (profile_id IN (SELECT id FROM profiles FINAL WHERE project_id = {p4:String} AND (email != '' AND email IS NOT NULL)))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy"}-```--result (both sides): `[{"c":1385,"u":54}]`--**sessions: wraps in profile_id IN (SELECT id FROM profiles …)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 376412/376412; wall V1/V2 = 37 ms / 38 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id IN (SELECT id FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (email != '' AND email IS NOT NULL)))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (profile_id IN (SELECT id FROM profiles FINAL WHERE project_id = {p4:String} AND (email != '' AND email IS NOT NULL)))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy"}-```--result (both sides): `[{"c":86,"u":48}]`--**unknown profile field is dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```---### value types--Re-run after `valueParam` started declaring the type ClickHouse infers for V1's-literal (see *Numeric filter values bind as the type V1's literal had*); the-wrapper parenthesises each compiled clause, hence the doubled parens.--**numeric value on a String property (both sides fail, code 386)** — IDENTICAL ERROR; rows V1/V2 = –/–; rows_read V1/V2 = –/–; wall V1/V2 = 16 ms / 4 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] = 5))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {w1:String} AND ((properties[{p1:String}] = {p2:UInt8}))--- V2 params: {"w1": "secure-privacy","p1": "country","p2": 5}-```--```-V1 error: There is no supertype for types String, UInt8 because some of them are String/FixedString/Enum and some of them are not: while executing function equals on arguments arrayElement(__table1.properties, 'country'_String) String String(size = 0), 5_UInt8 UInt8 Const(size = 0, UInt8(size = 1)).-V2 error: There is no supertype for types String, UInt8 because some of them are String/FixedString/Enum and some of them are not: while executing function equals on arguments arrayElement(__table1.properties, 'country'_String) String String(size = 0), _CAST(5_UInt8, 'UInt8'_String) UInt8 Const(size = 0, UInt8(size = 1)).-```--**numeric value on a numeric column (session.duration)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 11 ms / 15 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (((toFloat64(duration) = toFloat64(0))))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (((toFloat64(duration) = toFloat64({p1:UInt8}))))--- V2 params: {"w1": "secure-privacy","w2": "2026-07-01 00:00:00","w3": "2026-07-08 00:00:00","p1": 0}-```--result (both sides): `[{"c":22694,"u":22224}]`--**numeric value, gt on a numeric column (toFloat64 both sides)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 12 ms / 13 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (((toFloat64(duration) > toFloat64(10))))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (((toFloat64(duration) > toFloat64({p1:UInt8}))))--- V2 params: {"w1": "secure-privacy","w2": "2026-07-01 00:00:00","w3": "2026-07-08 00:00:00","p1": 10}-```--result (both sides): `[{"c":868,"u":702}]`--**fractional numeric value on a numeric column** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 16 ms / 18 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (((toFloat64(duration) > toFloat64(10.5))))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (((toFloat64(duration) > toFloat64({p1:Float64}))))--- V2 params: {"w1": "secure-privacy","w2": "2026-07-01 00:00:00","w3": "2026-07-08 00:00:00","p1": 10.5}-```--result (both sides): `[{"c":868,"u":702}]`--**boolean value (escape(true) -> Bool param)** — IDENTICAL ERROR; rows V1/V2 = –/–; rows_read V1/V2 = –/–; wall V1/V2 = 7 ms / 5 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((properties['country'] = true))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {w1:String} AND ((properties[{p1:String}] = {p2:Bool}))--- V2 params: {"w1": "secure-privacy","p1": "country","p2": true}-```--```-V1 error: There is no supertype for types String, Bool because some of them are String/FixedString/Enum and some of them are not: while executing function equals on arguments arrayElement(__table1.properties, 'country'_String) String String(size = 0), 1_Bool Bool Const(size = 0, UInt8(size = 1)).-V2 error: There is no supertype for types String, Bool because some of them are String/FixedString/Enum and some of them are not: while executing function equals on arguments arrayElement(__table1.properties, 'country'_String) String String(size = 0), _CAST(1_Bool, 'Bool'_String) Bool Const(size = 0, UInt8(size = 1)).-```--**null value (escape(null) -> Nullable(String) param)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 5 ms / 4 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (properties['country'] = NULL)--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (properties[{p2:String}] = {p3:Nullable(String)})--- V2 params: {"p1":"secure-privacy","p2":"country","p3":null}-```--result (both sides): `[{"c":0,"u":0}]`---### group.*--**group.name is** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 14 ms / 13 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND name = 'Narrative'), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND name = {p5:String}), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"Narrative"}-```--result (both sides): `[{"c":138,"u":2}]`--**group.name is (multi -> IN)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 11 ms / 13 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND name IN ('Narrative', 'TLC DigiTech')), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND name IN {p5:Array(String)}), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":["Narrative","TLC DigiTech"]}-```--result (both sides): `[{"c":224,"u":3}]`--**group.name isNot** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 19 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND name != 'Narrative'), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND name != {p5:String}), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"Narrative"}-```--result (both sides): `[{"c":859,"u":29}]`--**group.name contains** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 14 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (name ILIKE '%e%')), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (name ILIKE {p5:String})), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"%e%"}-```--result (both sides): `[{"c":640,"u":22}]`--**group.name doesNotContain** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 14 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (name NOT ILIKE '%e%')), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (name NOT ILIKE {p5:String})), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"%e%"}-```--result (both sides): `[{"c":357,"u":9}]`--**group.name startsWith** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 10 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (name ILIKE 'N%')), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (name ILIKE {p5:String})), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"N%"}-```--result (both sides): `[{"c":159,"u":3}]`--**group.name endsWith** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 12 ms / 13 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (name ILIKE '%h')), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (name ILIKE {p5:String})), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"%h"}-```--result (both sides): `[{"c":86,"u":1}]`--**group.name regex** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 13 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (match(name, '^N'))), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (match(name, {p5:String}))), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"^N"}-```--result (both sides): `[{"c":159,"u":3}]`--**group.name isNull** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 9 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (name = '' OR name IS NULL)), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (name = '' OR name IS NULL)), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy"}-```--result (both sides): `[{"c":0,"u":0}]`--**group.name isNotNull** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 21 ms / 21 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (name != '' AND name IS NOT NULL)), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (name != '' AND name IS NOT NULL)), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy"}-```--result (both sides): `[{"c":997,"u":31}]`--**group.type is** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 18 ms / 25 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND type = 'company'), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND type = {p5:String}), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"company"}-```--result (both sides): `[{"c":997,"u":31}]`--**group.properties.<key> isNotNull** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 17 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (properties['employees'] != '' AND properties['employees'] IS NOT NULL)), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (properties[{p5:String}] != '' AND properties[{p6:String}] IS NOT NULL)), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"employees","p6":"employees"}-```--result (both sides): `[{"c":929,"u":29}]`--**group.<unknown> falls back to id** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 14 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (id != '' AND id IS NOT NULL)), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (id != '' AND id IS NOT NULL)), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy"}-```--result (both sides): `[{"c":997,"u":31}]`--**no groupsExpr -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```---### session.*--**session.duration gt (numeric column)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 9 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((toFloat64(duration) > toFloat64('10')))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND ((toFloat64(duration) > toFloat64({p4:String})))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"10"}-```--result (both sides): `[{"c":868,"u":702}]`--**session.event_count gte** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 24553/24553; wall V1/V2 = 13 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((toFloat64(event_count) >= toFloat64('2')))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND ((toFloat64(event_count) >= toFloat64({p4:String})))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"2"}-```--result (both sides): `[{"c":37,"u":36}]`--**session.screen_view_count lt** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 20 ms / 18 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((toFloat64(screen_view_count) < toFloat64('3')))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND ((toFloat64(screen_view_count) < toFloat64({p4:String})))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"3"}-```--result (both sides): `[{"c":23129,"u":22592}]`--**session.revenue lte** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 14 ms / 9 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((toFloat64(revenue) <= toFloat64('0')))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND ((toFloat64(revenue) <= toFloat64({p4:String})))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"0"}-```--result (both sides): `[{"c":23565,"u":22863}]`--**session.is_bounce true** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 10 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (is_bounce = 1)--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (is_bounce = 1)--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00"}-```--result (both sides): `[{"c":22726,"u":22251}]`--**session.is_bounce false** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 9 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (is_bounce = 0)--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (is_bounce = 0)--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00"}-```--result (both sides): `[{"c":839,"u":676}]`--**session.is_bounce isNot true (negates)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 8 ms / 9 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (is_bounce = 0)--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (is_bounce = 0)--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00"}-```--result (both sides): `[{"c":839,"u":676}]`--**session.is_bounce empty value -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```--**session.performed_event (single value)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 671556/671556; wall V1/V2 = 48 ms / 46 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (id IN (SELECT DISTINCT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view'))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (id IN (SELECT DISTINCT session_id FROM events WHERE project_id = {p4:String} AND name = {p5:String}))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"screen_view"}-```--result (both sides): `[{"c":23564,"u":22863}]`--**session.performed_event (multi -> IN)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 671556/671556; wall V1/V2 = 49 ms / 41 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (id IN (SELECT DISTINCT session_id FROM events WHERE project_id = 'secure-privacy' AND name IN ('screen_view', 'session_start')))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (id IN (SELECT DISTINCT session_id FROM events WHERE project_id = {p4:String} AND name IN {p5:Array(String)}))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":["screen_view","session_start"]}-```--result (both sides): `[{"c":23565,"u":22863}]`--**session.performed_event isNot -> NOT IN** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 671556/671556; wall V1/V2 = 35 ms / 43 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (id NOT IN (SELECT DISTINCT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view'))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (id NOT IN (SELECT DISTINCT session_id FROM events WHERE project_id = {p4:String} AND name = {p5:String}))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"screen_view"}-```--result (both sides): `[{"c":1,"u":1}]`--**session.performed_event with a date scope** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 171877/171877; wall V1/V2 = 23 ms / 51 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (id IN (SELECT DISTINCT session_id FROM events WHERE project_id = 'secure-privacy' AND toDate(created_at) BETWEEN toDate('2026-07-01 00:00:00') AND toDate('2026-07-08 00:00:00') AND name = 'screen_view'))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (id IN (SELECT DISTINCT session_id FROM events WHERE project_id = {p4:String} AND toDate(created_at) BETWEEN toDate({p5:String}) AND toDate({p6:String}) AND name = {p7:String}))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"2026-07-01 00:00:00","p6":"2026-07-08 00:00:00","p7":"screen_view"}-```--result (both sides): `[{"c":23564,"u":22863}]`--**session.performed_event empty value -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```--**session.<unknown> -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```--**session.* on a non-sessions table -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```---### cohort--**inCohort (cohortIds)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 10 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both).--cohort_members is empty in the prod copy — 0 matching rows on both sides.--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND project_id = 'secure-privacy'))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p4:Array(String)} AND project_id = {p5:String}))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],"p5":"secure-privacy"}-```--result (both sides): `[{"c":0,"u":0}]`--**notInCohort** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 229305/229305; wall V1/V2 = 16 ms / 15 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND project_id = 'secure-privacy'))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p4:Array(String)} AND project_id = {p5:String}))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],"p5":"secure-privacy"}-```--result (both sides): `[{"c":76885,"u":22983}]`--**inCohort on the profiles table (profileIdExpr = id)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 7 ms / 7 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND project_id = 'secure-privacy'))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p2:Array(String)} AND project_id = {p3:String}))--- V2 params: {"p1":"secure-privacy","p2":["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],"p3":"secure-privacy"}-```--result (both sides): `[{"c":0,"u":0}]`--**cohort:<id> filter name** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 6 ms / 7 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee') AND project_id = 'secure-privacy'))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p4:Array(String)} AND project_id = {p5:String}))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],"p5":"secure-privacy"}-```--result (both sides): `[{"c":0,"u":0}]`--**inCohort with no ids -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```---### typed cast--**number is on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 73 ms / 66 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64OrNull(toString(properties['longitude'])) = toFloat64OrNull(toString('-77.4903'))))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64OrNull(toString(properties[{p2:String}])) = toFloat64OrNull(toString({p3:String}))))--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"-77.4903"}-```--result (both sides): `[{"c":10852,"u":10852}]`--**number gt on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 68 ms / 66 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64OrNull(toString(properties['longitude'])) > toFloat64OrNull(toString('0'))))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64OrNull(toString(properties[{p2:String}])) > toFloat64OrNull(toString({p3:String}))))--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"0"}-```--result (both sides): `[{"c":41665,"u":41663}]`--**number isNot (AND joiner) on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 67 ms / 82 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toFloat64OrNull(toString(properties['longitude'])) != toFloat64OrNull(toString('0')) AND toFloat64OrNull(toString(properties['longitude'])) != toFloat64OrNull(toString('1'))))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toFloat64OrNull(toString(properties[{p2:String}])) != toFloat64OrNull(toString({p3:String})) AND toFloat64OrNull(toString(properties[{p4:String}])) != toFloat64OrNull(toString({p5:String}))))--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"0","p4":"longitude","p5":"1"}-```--result (both sides): `[{"c":118501,"u":118462}]`--**boolean is (value true — no truthy longitude here, 0 rows both sides) on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 63 ms / 63 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((if(lower(trim(toString(properties['longitude']))) IN ('true', '1', 'yes'), 1, 0) = if(lower(trim(toString('true'))) IN ('true', '1', 'yes'), 1, 0)))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((if(lower(trim(toString(properties[{p2:String}]))) IN ('true', '1', 'yes'), 1, 0) = if(lower(trim(toString({p3:String}))) IN ('true', '1', 'yes'), 1, 0)))--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"true"}-```--result (both sides): `[{"c":0,"u":0}]`--**boolean is (value false — matches every non-truthy row) on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 67 ms / 66 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((if(lower(trim(toString(properties['longitude']))) IN ('true', '1', 'yes'), 1, 0) = if(lower(trim(toString('false'))) IN ('true', '1', 'yes'), 1, 0)))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((if(lower(trim(toString(properties[{p2:String}]))) IN ('true', '1', 'yes'), 1, 0) = if(lower(trim(toString({p3:String}))) IN ('true', '1', 'yes'), 1, 0)))--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"false"}-```--result (both sides): `[{"c":118502,"u":118465}]`--**date gte on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 64 ms / 65 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((toDate(parseDateTimeBestEffortOrNull(toString(properties['longitude']))) >= toDate(parseDateTimeBestEffortOrNull(toString('2019-01-01')))))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((toDate(parseDateTimeBestEffortOrNull(toString(properties[{p2:String}]))) >= toDate(parseDateTimeBestEffortOrNull(toString({p3:String})))))--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"2019-01-01"}-```--result (both sides): `[{"c":84,"u":84}]`--**datetime lt on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 63 ms / 65 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND ((parseDateTimeBestEffortOrNull(toString(properties['longitude'])) < parseDateTimeBestEffortOrNull(toString('2030-01-01 00:00:00'))))--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND ((parseDateTimeBestEffortOrNull(toString(properties[{p2:String}])) < parseDateTimeBestEffortOrNull(toString({p3:String}))))--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"2030-01-01 00:00:00"}-```--result (both sides): `[{"c":84,"u":84}]`--**string type falls through to the raw path on profile.properties.longitude** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 310976/310976; wall V1/V2 = 64 ms / 61 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = 'secure-privacy' AND (properties['longitude'] = '-77.4903')--- V2-SELECT count() AS c, uniq(id) AS u FROM profiles FINAL WHERE project_id = {p1:String} AND (properties[{p2:String}] = {p3:String})--- V2 params: {"p1":"secure-privacy","p2":"longitude","p3":"-77.4903"}-```--result (both sides): `[{"c":10852,"u":10852}]`--**number gte on a group property** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 232664/232664; wall V1/V2 = 13 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = 'secure-privacy' AND (toFloat64OrNull(toString(properties['employees'])) >= toFloat64OrNull(toString('0')))), groups))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND (arrayExists(g -> g IN (SELECT id FROM groups FINAL WHERE project_id = {p4:String} AND (toFloat64OrNull(toString(properties[{p5:String}])) >= toFloat64OrNull(toString({p6:String})))), groups))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"secure-privacy","p5":"employees","p6":"0"}-```--result (both sides): `[{"c":929,"u":29}]`--**number gt on a session numeric column** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32720/32720; wall V1/V2 = 9 ms / 9 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((toFloat64OrNull(toString(duration)) > toFloat64OrNull(toString('0'))))--- V2-SELECT count() AS c, uniq(profile_id) AS u FROM sessions WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at < toDateTime({p3:String}) AND ((toFloat64OrNull(toString(duration)) > toFloat64OrNull(toString({p4:String}))))--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"0"}-```--result (both sides): `[{"c":871,"u":702}]`---### ignored--**properties.* on the profiles table -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```--**bare column -> dropped** — IDENTICAL: both compilers emit no clause.--Both compilers emit no clause — compile-time equivalence, nothing executed.--```sql--- V1-<no clause>--- V2-<no clause>--- V2 params: {}-```-diff --git a/packages/core/src/modules/chart/src/filter-where.sql.proof.md b/packages/core/src/modules/chart/src/filter-where.sql.proof.mddeleted file mode 100644index 2eeeddf92..000000000--- a/packages/core/src/modules/chart/src/filter-where.sql.proof.md+++ /dev/null@@ -1,707 +0,0 @@-# filter-where.ts — V1 → V2 result-set proof (M12-002)--V1 is `packages/core/src/modules/chart/src/filter-where.ts` at `be029da1`-(`git show HEAD:packages/core/src/modules/chart/src/filter-where.ts`,-materialised as a sibling module so its relative imports resolve, deleted after-the run). V2 is the converted file in this commit. Both compilers were imported-into ONE Bun process, called with the SAME `IChartEventFilter[]`, `projectId`,-`eventsAlias` and `tableScope`, and each compiled clause was spliced into the-SAME surrounding count query and executed through ONE `@clickhouse/client` with-`format: 'JSON'` and `session_timezone=UTC` on both sides — V1 as `query`, V2 as-`query` + `query_params`. `data` and `meta` were compared field for field. Every-statement here returns a single aggregate row, so no case needed set comparison.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,850,470 events. Project- `secure-privacy` (347 group rows, 345 distinct names, 31 of those reachable- from events in the window), window `2026-07-01 00:00:00` … `2026-07-08 00:00:00` (76,885 events, 22,983- distinct profiles), `session_timezone=UTC`. One case (`wildcard array /- isNull`) uses project `dd5f6d1c-fff9-43c9-8c89-e40ba06752c8` over the same- window, because it is the only project in the copy with an empty-valued- `__query.*` key there — on `secure-privacy` that case returns 0 rows and would- prove nothing. **`cohort_members` is empty in the prod copy** (`SELECT count()- FROM cohort_members` = 0), so the two `inCohort` cases are 0-row statement- equivalences; positive-row cohort coverage lives in `openpanel_test` (same- precedent as `sql.proof.md`).-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). Two statements contain `IN (subquery)` on a- `Distributed` table (the two cohort branches); **no `IN` was converted to- `GLOBAL IN` or back** — see *IN / GLOBAL IN* below.-- **Verdict**: **94 cases, all IDENTICAL** — 91 executed against ClickHouse- (3 of them IDENTICAL ERROR: V1 defects reproduced byte-for-byte, listed- below, not fixed here) and 3 compile-time equivalences where both compilers- emit no clause at all.--## Per-case results--Row counts are `count()` / `uniq(profile_id)` over the window, V1/V2. Three-cases return 0 rows and say why in their row: the two `inCohort` cases-(`cohort_members` is empty here) and `typed cast / number is with a null value`-(a comparison against NULL is never true — the binding itself is proven by the-probe under *The `null` binding*).--| branch | case | verdict | rows V1/V2 | count V1/V2 | uniq V1/V2 | rows_read V1/V2 | wall ms V1/V2 |-|---|---|---|---|---|---|---|---|-| top-level column | is (single value) | IDENTICAL | 1/1 | 3066/3066 | 986/986 | 90057/90057 | 29/21 |-| top-level column | is (multi value -> IN) | IDENTICAL | 1/1 | 3921/3921 | 1090/1090 | 90057/90057 | 21/20 |-| top-level column | isNot (single value) | IDENTICAL | 1/1 | 73819/73819 | 22268/22268 | 90057/90057 | 37/18 |-| top-level column | isNot (multi value -> NOT IN) | IDENTICAL | 1/1 | 72964/72964 | 22179/22179 | 90057/90057 | 24/23 |-| top-level column | contains | IDENTICAL | 1/1 | 60795/60795 | 19723/19723 | 90057/90057 | 20/19 |-| top-level column | doesNotContain | IDENTICAL | 1/1 | 16090/16090 | 3393/3393 | 90057/90057 | 20/23 |-| top-level column | startsWith | IDENTICAL | 1/1 | 60089/60089 | 19504/19504 | 90057/90057 | 17/22 |-| top-level column | endsWith | IDENTICAL | 1/1 | 6333/6333 | 1953/1953 | 90057/90057 | 16/19 |-| top-level column | regex (slashes stripped) | IDENTICAL | 1/1 | 60089/60089 | 19504/19504 | 90057/90057 | 21/21 |-| top-level column | isNull (empty value array) | IDENTICAL | 1/1 | 15591/15591 | 3420/3420 | 90057/90057 | 13/23 |-| top-level column | isNotNull (empty value array) | IDENTICAL | 1/1 | 61294/61294 | 19631/19631 | 90057/90057 | 20/15 |-| top-level column | gt on a numeric column (toFloat64 cast) | IDENTICAL | 1/1 | 868/868 | 702/702 | 90057/90057 | 20/14 |-| top-level column | gte on a numeric column | IDENTICAL | 1/1 | 869/869 | 702/702 | 90057/90057 | 13/13 |-| top-level column | lt on a numeric column | IDENTICAL | 1/1 | 76688/76688 | 22983/22983 | 90057/90057 | 15/15 |-| top-level column | lte on a numeric column | IDENTICAL | 1/1 | 76688/76688 | 22983/22983 | 90057/90057 | 15/20 |-| top-level column | gt on a non-numeric column (raw comparison) | IDENTICAL | 1/1 | 73522/73522 | 22243/22243 | 90057/90057 | 18/17 |-| top-level column | lte on a non-numeric column | IDENTICAL | 1/1 | 7068/7068 | 2091/2091 | 90057/90057 | 22/20 |-| top-level column | camelCase alias (referrerName -> referrer_name) | IDENTICAL | 1/1 | 58439/58439 | 18908/18908 | 90057/90057 | 28/31 |-| top-level column | null in the value array (String(null) -> 'null') | IDENTICAL | 1/1 | 3066/3066 | 986/986 | 90057/90057 | 20/16 |-| top-level column | unknown column is dropped | IDENTICAL (no clause emitted) | – | – | – | – | – |-| top-level column | empty value array with a value operator is dropped | IDENTICAL (no clause emitted) | – | – | – | – | – |-| properties.* | is (single value) | IDENTICAL | 1/1 | 1084/1084 | 360/360 | 81866/81866 | 18/18 |-| properties.* | is (multi value -> IN) | IDENTICAL | 1/1 | 1084/1084 | 360/360 | 81866/81866 | 34/18 |-| properties.* | isNot (single value) | IDENTICAL | 1/1 | 75801/75801 | 22949/22949 | 90057/90057 | 35/23 |-| properties.* | isNot (multi value -> NOT IN) | IDENTICAL | 1/1 | 75801/75801 | 22949/22949 | 90057/90057 | 30/38 |-| properties.* | contains | IDENTICAL | 1/1 | 52792/52792 | 22934/22934 | 90057/90057 | 29/22 |-| properties.* | doesNotContain | IDENTICAL | 1/1 | 24093/24093 | 22891/22891 | 90057/90057 | 20/23 |-| properties.* | startsWith | IDENTICAL | 1/1 | 3948/3948 | 1434/1434 | 90057/90057 | 23/26 |-| properties.* | endsWith | IDENTICAL | 1/1 | 3039/3039 | 1120/1120 | 90057/90057 | 26/20 |-| properties.* | regex (NOT slash-stripped, unlike the column branch) | IDENTICAL | 1/1 | 3948/3948 | 1434/1434 | 90057/90057 | 32/19 |-| properties.* | isNull | IDENTICAL | 1/1 | 23963/23963 | 22890/22890 | 90057/90057 | 22/20 |-| properties.* | isNotNull | IDENTICAL | 1/1 | 52922/52922 | 22973/22973 | 90057/90057 | 28/29 |-| properties.* | gt (toFloat64OrZero) | IDENTICAL | 1/1 | 1157/1157 | 529/529 | 81866/81866 | 17/17 |-| properties.* | gte (toFloat64OrZero) | IDENTICAL | 1/1 | 76885/76885 | 22983/22983 | 90057/90057 | 35/19 |-| properties.* | lt (toFloat64OrZero) | IDENTICAL | 1/1 | 75728/75728 | 22983/22983 | 90057/90057 | 29/23 |-| properties.* | lte (toFloat64OrZero) | IDENTICAL | 1/1 | 75728/75728 | 22983/22983 | 90057/90057 | 22/21 |-| properties.* | eventsAlias qualifies the map (e.properties[...]) | IDENTICAL | 1/1 | 1084/1084 | 360/360 | 81866/81866 | 18/20 |-| properties.__query.* | bare utm_source routed into the __query map | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 12/18 |-| properties.__query.* | explicit properties.__query.utm_source contains | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 12/12 |-| properties.__query.* | properties.__query.gclid isNotNull | IDENTICAL | 1/1 | 1292/1292 | 547/547 | 81866/81866 | 29/22 |-| profile.properties.* | is (single value) | IDENTICAL | 1/1 | 42927/42927 | 13651/13651 | 401033/401033 | 109/82 |-| profile.properties.* | is + rewriteProfilePropertyRefs narrows the ref | IDENTICAL | 1/1 | 42927/42927 | 13651/13651 | 401033/401033 | 75/76 |-| profile.properties.* | contains + rewriteProfilePropertyRefs (the value keeps its own text) | IDENTICAL | 1/1 | 70431/70431 | 21700/21700 | 401033/401033 | 79/76 |-| profile.properties.* | isNotNull | IDENTICAL | 1/1 | 75053/75053 | 22938/22938 | 401033/401033 | 79/82 |-| profile.properties.* | multi value -> IN | IDENTICAL | 1/1 | 46413/46413 | 14783/14783 | 401033/401033 | 79/83 |-| wildcard array | is | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 13/14 |-| wildcard array | isNot | IDENTICAL | 1/1 | 2035/2035 | 802/802 | 81866/81866 | 21/30 |-| wildcard array | contains | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 14/13 |-| wildcard array | doesNotContain | IDENTICAL | 1/1 | 2035/2035 | 802/802 | 81866/81866 | 16/18 |-| wildcard array | startsWith | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 17/14 |-| wildcard array | endsWith | IDENTICAL | 1/1 | 109/109 | 49/49 | 81866/81866 | 17/18 |-| wildcard array | regex | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 14/13 |-| wildcard array | isNull | IDENTICAL | 1/1 | 5/5 | 3/3 | 81897/16379 | 16/13 |-| wildcard array | isNotNull | IDENTICAL | 1/1 | 2076/2076 | 822/822 | 81866/81866 | 17/19 |-| wildcard array | gt | IDENTICAL | 1/1 | 1290/1290 | 587/587 | 81866/81866 | 23/25 |-| wildcard array | gte | IDENTICAL | 1/1 | 2076/2076 | 822/822 | 81866/81866 | 19/23 |-| wildcard array | lt | IDENTICAL | 1/1 | 2029/2029 | 807/807 | 81866/81866 | 32/25 |-| wildcard array | lte | IDENTICAL | 1/1 | 2043/2043 | 814/814 | 81866/81866 | 36/19 |-| wildcard array | nested .*. pattern (properties.__query.*.type) | IDENTICAL | 1/1 | 62/62 | 26/26 | 73674/73674 | 18/18 |-| trailing .* wildcard | properties.__query.* is (V1 defect: not a wildcard) | **IDENTICAL ERROR** | – | – | – | – | 4/4 |-| trailing .* wildcard | properties.__query.* isNotNull | **IDENTICAL ERROR** | – | – | – | – | 4/3 |-| group.* | group.type is | IDENTICAL | 1/1 | 997/997 | 31/31 | 93416/93416 | 32/34 |-| group.* | group.name contains | IDENTICAL | 1/1 | 733/733 | 24/24 | 93416/93416 | 31/27 |-| group.* | group.name is (multi -> IN) | IDENTICAL | 1/1 | 198/198 | 3/3 | 93416/93416 | 26/28 |-| group.* | group.name isNot (single) | IDENTICAL | 1/1 | 2715/2715 | 89/89 | 93416/93416 | 31/32 |-| group.* | group.name isNot (multi -> NOT IN) | IDENTICAL | 1/1 | 2655/2655 | 88/88 | 93416/93416 | 29/28 |-| group.* | group.properties.employees isNotNull | IDENTICAL | 1/1 | 929/929 | 29/29 | 93416/93416 | 32/33 |-| group.* | group.properties.country isNull | IDENTICAL | 1/1 | 2295/2295 | 77/77 | 93416/93416 | 30/30 |-| group.* | group.name startsWith | IDENTICAL | 1/1 | 138/138 | 2/2 | 93416/93416 | 27/33 |-| group.* | group.name endsWith | IDENTICAL | 1/1 | 357/357 | 13/13 | 93416/93416 | 30/29 |-| group.* | group.name doesNotContain | IDENTICAL | 1/1 | 2120/2120 | 68/68 | 93416/93416 | 32/28 |-| group.* | group.name regex | IDENTICAL | 1/1 | 733/733 | 24/24 | 93416/93416 | 28/27 |-| has_profile | has_profile true | IDENTICAL | 1/1 | 2841/2841 | 91/91 | 81866/81866 | 25/16 |-| has_profile | has_profile false | IDENTICAL | 1/1 | 74044/74044 | 22892/22892 | 90057/90057 | 26/18 |-| cohort | inCohort (cohort_members is empty in the prod copy) | IDENTICAL | 1/1 | 0/0 | 0/0 | 0/0 | 8/8 |-| cohort | notInCohort | IDENTICAL | 1/1 | 76885/76885 | 22983/22983 | 229305/229305 | 15/23 |-| cohort | inCohort with eventsAlias | IDENTICAL | 1/1 | 0/0 | 0/0 | 0/0 | 7/11 |-| cohort | inCohort with no cohort ids is dropped | IDENTICAL (no clause emitted) | – | – | – | – | – |-| typed cast | number is on a property | IDENTICAL | 1/1 | 8/8 | 4/4 | 16381/16381 | 17/15 |-| typed cast | number gt on a property | IDENTICAL | 1/1 | 1157/1157 | 529/529 | 81866/81866 | 22/19 |-| typed cast | number gte on a top-level column | IDENTICAL | 1/1 | 869/869 | 702/702 | 90057/90057 | 27/22 |-| typed cast | number isNot on a property (AND joiner) | IDENTICAL | 1/1 | 1157/1157 | 529/529 | 81866/81866 | 22/23 |-| typed cast | boolean is on a property | IDENTICAL | 1/1 | 54159/54159 | 22983/22983 | 90057/90057 | 29/27 |-| typed cast | date gte on created_at | IDENTICAL | 1/1 | 64656/64656 | 20059/20059 | 73676/73676 | 31/18 |-| typed cast | datetime lt on created_at | IDENTICAL | 1/1 | 12229/12229 | 2946/2946 | 24568/24568 | 10/9 |-| typed cast | number is on a wildcard array | IDENTICAL | 1/1 | 62/62 | 26/26 | 73674/73674 | 22/19 |-| typed cast | number is with a numeric (not string) value | IDENTICAL | 1/1 | 8/8 | 4/4 | 16381/16381 | 13/10 |-| typed cast | boolean is with a real boolean value | IDENTICAL | 1/1 | 54159/54159 | 22983/22983 | 90057/90057 | 26/33 |-| typed cast | number is with a null value (NULL keyword) | IDENTICAL | 1/1 | 0/0 | 0/0 | 0/0 | 7/5 |-| typed cast | number gte on a group property | IDENTICAL | 1/1 | 929/929 | 29/29 | 93416/93416 | 29/35 |-| sessions scope | bare entry_path is (no top-level allowlist) | **IDENTICAL ERROR** | – | – | – | – | 6/5 |-| sessions scope | utm_source stays a top-level column | IDENTICAL | 1/1 | 19/19 | 19/19 | 65436/65436 | 24/18 |-| sessions scope | camelCase alias on sessions | IDENTICAL | 1/1 | 19107/19107 | 18877/18877 | 65436/65436 | 16/13 |-| multiple filters | three filters joined with AND | IDENTICAL | 1/1 | 24996/24996 | 12289/12289 | 90057/90057 | 23/24 |-`rows_read` and wall time differ run to run and between an inline literal and-a bound param — recorded, not chased (recipe, *Proof-file template*).--## Rendered statements, one per branch--Every compiled clause below was produced by CALLING the two compilers, not-retyped. Each pair is reproducible with `curl` (see *Reproducing a case*).--### top-level column--**top-level column — is (single value)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **3066/3066**; uniq V1/V2 = **986/986**; rows_read V1/V2 = 90057/90057; wall V1/V2 = 29 ms / 21 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "path", "operator": "is", "value": ["/"]}]--- V1 clause-path = '/'--- V2 clause-path = {p1:String}--- V2 clause params: {"p1": "/"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (path = '/')--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (path = {p1:String})--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "/"}-```--### properties.*--**properties.* — is (single value)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **1084/1084**; uniq V1/V2 = **360/360**; rows_read V1/V2 = 81866/81866; wall V1/V2 = 18 ms / 18 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "properties.__title", "operator": "is", "value": ["Secure Privacy Consent Management Platform"]}]--- V1 clause-properties['__title'] = 'Secure Privacy Consent Management Platform'--- V2 clause-properties['__title'] = {p1:String}--- V2 clause params: {"p1": "Secure Privacy Consent Management Platform"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (properties['__title'] = 'Secure Privacy Consent Management Platform')--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (properties['__title'] = {p1:String})--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "Secure Privacy Consent Management Platform"}-```--### properties.__query.*--**properties.__query.* — bare utm_source routed into the __query map** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **41/41**; uniq V1/V2 = **20/20**; rows_read V1/V2 = 49113/49113; wall V1/V2 = 12 ms / 18 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "utm_source", "operator": "is", "value": ["chatgpt.com"]}]--- V1 clause-properties['__query.utm_source'] = 'chatgpt.com'--- V2 clause-properties['__query.utm_source'] = {p1:String}--- V2 clause params: {"p1": "chatgpt.com"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (properties['__query.utm_source'] = 'chatgpt.com')--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (properties['__query.utm_source'] = {p1:String})--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "chatgpt.com"}-```--### profile.properties.*--**profile.properties.* — is (single value)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **42927/42927**; uniq V1/V2 = **13651/13651**; rows_read V1/V2 = 401033/401033; wall V1/V2 = 109 ms / 82 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "profile.properties.country", "operator": "is", "value": ["US"]}]--- V1 clause-profile.properties['country'] = 'US'--- V2 clause-profile.properties['country'] = {p1:String}--- V2 clause params: {"p1": "US"}--- V1 statement-SELECT count() AS c, uniq(e.profile_id) AS u FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'secure-privacy') AS profile ON profile.id = e.profile_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') AND (profile.properties['country'] = 'US')--- V2 statement-SELECT count() AS c, uniq(e.profile_id) AS u FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = {w1:String}) AS profile ON profile.id = e.profile_id WHERE e.project_id = {w1:String} AND e.created_at >= toDateTime({w2:String}) AND e.created_at < toDateTime({w3:String}) AND (profile.properties['country'] = {p1:String})--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "US"}-```--### wildcard array--**wildcard array — is** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **41/41**; uniq V1/V2 = **20/20**; rows_read V1/V2 = 49113/49113; wall V1/V2 = 13 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "properties.__query[*]", "operator": "is", "value": ["chatgpt.com"]}]--- V1 clause-arrayExists(x -> x = 'chatgpt.com', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%'))))--- V2 clause-arrayExists(x -> x = {p1:String}, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%'))))--- V2 clause params: {"p1": "chatgpt.com"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(x -> x = 'chatgpt.com', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%')))))--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (arrayExists(x -> x = {p1:String}, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%')))))--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "chatgpt.com"}-```--### trailing .* wildcard--**trailing .* wildcard — properties.__query.* is (V1 defect: not a wildcard)** — IDENTICAL ERROR; wall V1/V2 = 4 ms / 4 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "properties.__query.*", "operator": "is", "value": ["chatgpt.com"]}]--- V1 clause-arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = 'chatgpt.com'--- V2 clause-arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = {p1:String}--- V2 clause params: {"p1": "chatgpt.com"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = 'chatgpt.com')--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = {p1:String})--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "chatgpt.com"}-```--Both sides fail with the same ClickHouse error:--```-V1: Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim-V2: Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim-```--### group.*--**group.* — group.type is** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **997/997**; uniq V1/V2 = **31/31**; rows_read V1/V2 = 93416/93416; wall V1/V2 = 32 ms / 34 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "group.type", "operator": "is", "value": ["company"]}]--- V1 clause-_g.type = 'company'--- V2 clause-_g.type = {p1:String}--- V2 clause params: {"p1": "company"}--- V1 statement-SELECT count() AS c, uniq(e.profile_id) AS u FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') AS _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') AND (_g.type = 'company')--- V2 statement-SELECT count() AS c, uniq(e.profile_id) AS u FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {w1:String}) AS _g ON _g.id = _group_id WHERE e.project_id = {w1:String} AND e.created_at >= toDateTime({w2:String}) AND e.created_at < toDateTime({w3:String}) AND (_g.type = {p1:String})--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "company"}-```--### has_profile--**has_profile — has_profile true** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **2841/2841**; uniq V1/V2 = **91/91**; rows_read V1/V2 = 81866/81866; wall V1/V2 = 25 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "has_profile", "operator": "is", "value": ["true"]}]--- V1 clause-profile_id != device_id--- V2 clause-profile_id != device_id--- V2 clause params: {}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id != device_id)--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (profile_id != device_id)--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00"}-```--### cohort--**cohort — inCohort (cohort_members is empty in the prod copy)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **0/0**; uniq V1/V2 = **0/0**; rows_read V1/V2 = 0/0; wall V1/V2 = 8 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "profile", "operator": "inCohort", "value": [], "cohortIds": ["11111111-1111-1111-1111-111111111111"]}]--- V1 clause-profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('11111111-1111-1111-1111-111111111111') AND project_id = 'secure-privacy')--- V2 clause-profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p1:Array(String)} AND project_id = {p2:String})--- V2 clause params: {"p1": ["11111111-1111-1111-1111-111111111111"], "p2": "secure-privacy"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('11111111-1111-1111-1111-111111111111') AND project_id = 'secure-privacy'))--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p1:Array(String)} AND project_id = {p2:String}))--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": ["11111111-1111-1111-1111-111111111111"], "p2": "secure-privacy"}-```--### typed cast--**typed cast — number is on a property** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **8/8**; uniq V1/V2 = **4/4**; rows_read V1/V2 = 16381/16381; wall V1/V2 = 17 ms / 15 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "properties.__query.adid", "operator": "is", "value": ["0"], "type": "number"}]--- V1 clause-(toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString('0')))--- V2 clause-(toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString({p1:String})))--- V2 clause params: {"p1": "0"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString('0'))))--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND ((toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString({p1:String}))))--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "0"}-```--### sessions scope--**sessions scope — bare entry_path is (no top-level allowlist)** — IDENTICAL ERROR; wall V1/V2 = 6 ms / 5 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "path", "operator": "is", "value": ["/"]}]--- V1 clause-path = '/'--- V2 clause-path = {p1:String}--- V2 clause params: {"p1": "/"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (path = '/')--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (path = {p1:String})--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "/"}-```--Both sides fail with the same ClickHouse error:--```-V1: Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A-V2: Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A-```--### multiple filters--**multiple filters — three filters joined with AND** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **24996/24996**; uniq V1/V2 = **12289/12289**; rows_read V1/V2 = 90057/90057; wall V1/V2 = 23 ms / 24 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- filter input: [{"name": "path", "operator": "startsWith", "value": ["/blog"]}, {"name": "country", "operator": "is", "value": ["US"]}, {"name": "properties.__title", "operator": "contains", "value": ["Privacy"]}]--- V1 clause-(path LIKE '/blog%') AND country = 'US' AND (properties['__title'] LIKE '%Privacy%')--- V2 clause-(path LIKE {p1:String}) AND country = {p2:String} AND (properties['__title'] LIKE {p3:String})--- V2 clause params: {"p1": "/blog%", "p2": "US", "p3": "%Privacy%"}--- V1 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((path LIKE '/blog%') AND country = 'US' AND (properties['__title'] LIKE '%Privacy%'))--- V2 statement-SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND ((path LIKE {p1:String}) AND country = {p2:String} AND (properties['__title'] LIKE {p3:String}))--- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "/blog%", "p2": "US", "p3": "%Privacy%"}-```-## The three compile-time equivalences--These emit no clause on either side, so there is nothing to execute — the-evidence is that both compilers return an empty record for the same input.--| case | V1 keys | V2 keys |-|---|---|---|-| top-level column — unknown column is dropped | `[]` | `[]` |-| top-level column — empty value array with a value operator is dropped | `[]` | `[]` |-| cohort — inCohort with no cohort ids is dropped | `[]` | `[]` |--## IDENTICAL ERROR cases — V1 defects reproduced, not fixed--- **trailing .* wildcard — properties.__query.* is (V1 defect: not a wildcard)**- - V1: `Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim`- - V2: `Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim`-- **trailing .* wildcard — properties.__query.* isNotNull**- - V1: `Array does not start with '[' character: while converting '' to Array(String): while executing function notEquals on arguments arrayMap(x String -> trimBoth(x),`- - V2: `Array does not start with '[' character: while converting '' to Array(String): while executing function notEquals on arguments arrayMap(x String -> trimBoth(x),`-- **sessions scope — bare entry_path is (no top-level allowlist)**- - V1: `Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A`- - V2: `Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A`-The first two are the trailing-`.*` branch: `getSelectPropertyKey` treats-`properties.__query.*` as a literal map-key pattern rather than a wildcard, so-the compiler emits an `Array(String)` expression compared against a scalar. The-third is the sessions scope, where V1 skips the top-level-column allowlist —-`path` is not a `sessions` column, so both sides reach ClickHouse and both are-rejected. All three are pre-existing V1 behaviour and are reproduced, not fixed.--## `rewriteProfilePropertyRefs` — where the rewrite happens now--V1 ran the rewrite over finished TEXT: `sql.ts` and `funnel.sql.ts` called-`compiledTextWithProfileRefs(clause, keys)` on the compiler's string. With the-compiler returning fragments there is no string to rewrite, so the rewrite moved-to `compiled.ts`'s `fragmentWithProfileRefs(fragment, keys)`, which maps-`rewriteProfilePropertyRefs` over `fragment.strings` — **the literal parts-only** — and recurses into nested fragments, leaving every `SqlParam`-untouched. **It never runs on params.**--That is the same rewrite, and now it is the same rewrite *by construction*.-`compiled.ts` recorded why the text version was safe: an escaped literal cannot-contain `['`, so the rewrite never matched a value. A bound param is not in the-text at all, so it cannot match even in principle — the accident became an-invariant. Callers: `sql.ts:358` and `funnel.sql.ts:149`.-`compiledTextWithProfileRefs` survives for the ONE thing still rendering text,-the field resolver (`sql.ts:332`, `funnel.sql.ts:180`).--Two proof cases exercise it end to end against the narrowed profile CTE — the-wrapper selects ``properties['country'] as `profile.properties.country` `` and-``properties['device'] as `profile.properties.device` `` exactly as-`profilePropertiesCteSelect` does, so the rewritten ref has to resolve or the-query fails with UNKNOWN_IDENTIFIER:--- `profile.properties.* / is + rewriteProfilePropertyRefs narrows the ref` —- keys `['country']`, 42,927 rows on both sides.-- `profile.properties.* / contains + rewriteProfilePropertyRefs (the value keeps- its own text)` — keys `['device']`, value `'deskto'`, 70,431 rows on both- sides. The value contains no `['`, but the point is structural: it is in- `query_params`, not in the statement, so the rewrite pass cannot reach it.--The two un-narrowed `profile.properties.*` cases (`is (single value)`,-`multi value -> IN`) run against the full-Map CTE with no rewrite, and are-identical too — so both halves of the narrowing switch are covered.--## IN / GLOBAL IN — unchanged in both directions--The rule (recipe, *Traps 2*; `docs/ENVIRONMENT.md`): a conversion changes the-binding of values and nothing about distribution semantics. The two places-`filter-where.ts` emits `IN` against a `Distributed` table are the cohort-branches, and both are still plain `IN`, as V1 wrote them.--```-$ git diff -U0 | grep -nE '^[+-].*(\bGLOBAL +IN\b|\bGLOBAL +JOIN\b)'-310:+ // change IN/GLOBAL IN in either direction (docs/ENVIRONMENT.md).-```--The only line in the whole diff that mentions `GLOBAL IN` is the comment saying-it was not touched. No `GLOBAL` was added and none was removed.--The multi-value `IN (...)` list forms became `IN {pN:Array(String)}` (recipe-idiom 9) — a value list, not a subquery, so it carries no distribution-question. The cohort subselect kept its parentheses and its `IN`:--```sql--- V1-profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('1111...') AND project_id = 'secure-privacy')--- V2-profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p1:Array(String)} AND project_id = {p2:String})-```--## The `null` binding--`sqlstring.escape(null)` produced the SQL keyword `NULL`. `sql.string(null)`-would bind a `String` param, which ClickHouse parses as the **empty string** —-so the typed-cast path binds through `sql.nullable('String', null)`-(`filter-cast.ts`, `typedValueParam`). Measured against local ClickHouse-26.1.3.52, 2026-09-07:--```bash-curl -s -G 'http://127.0.0.1:8123/' --data-urlencode 'database=openpanel' \- --data-urlencode 'default_format=JSONCompact' --data-urlencode 'param_p1=\N' \- --data-urlencode "query=SELECT toFloat64OrNull(toString({p1:Nullable(String)})) AS v2, isNull(toFloat64OrNull(toString({p1:Nullable(String)}))) AS v2_isnull, toFloat64OrNull(toString(NULL)) AS v1, isNull(toFloat64OrNull(toString(NULL))) AS v1_isnull"--- [[null,1,null,1]]--curl -s -G 'http://127.0.0.1:8123/' --data-urlencode 'database=openpanel' \- --data-urlencode 'default_format=JSONCompact' --data-urlencode 'param_p1=\N' \- --data-urlencode "query=SELECT {p1:String} AS as_string, isNull({p1:Nullable(String)}) AS as_nullable_isnull"--- [["",1]]-```--V1's `NULL` and V2's `{p:Nullable(String)}` are both NULL; a plain `String` param-would have been `''`. The `typed cast / number is with a null value` proof case-returns 0 rows on both sides and always will — a comparison against NULL is-never true — so the binding probe above is what actually proves that branch;-the case proves the two statements agree.--The untyped branches never see a raw `null`: V1 wrote `String(val).trim()`, so a-`null` value becomes the four-character string `'null'`. The `top-level column /-null in the value array` case pins that (`path IN ('null','/')` vs-`path IN {p:Array(String)}` with `["null","/"]`, 3,066 rows both sides).--## Consumer conversion: referrer-spikes.ts (clix → sql)--Not in the task's consumer list, and forced by it: `getRawWhereClause` returns a-fragment carrying params, and clix's `execute()` (`query-builder.ts:552`) has no-`query_params` slot to carry them — it passes only `query` and-`clickhouse_settings`. `packages/db` is outside this task's scope, so the three-clix queries in `modules/insight/src/referrer-spikes.ts` moved onto the tag-instead. clix always sent `session_timezone` (`query-builder.ts:562`); `chQuery`-gets the same value, and `.transform({ date })` became the same per-row map in-JS. clix's `toStartOf` ignores its timezone argument (`query-builder.ts:717-734`),-so `bucketStart` emits the same expression.--Both sides were run through the REAL functions — V1 materialised from HEAD with-its `overviewService` import pointed at HEAD's `getRawWhereClause`, V2 as-committed — behind a recording ClickHouse client that still executes and returns-the real response, so no statement here was retyped. Filters:-`[{name:'country',operator:'is',value:['US']}]`, project `secure-privacy`,-window `2026-07-01` … `2026-07-08`, interval `day`, `session_timezone=UTC` on-both sides. Queries 2 and 3 race inside `Promise.all`, so they are matched by-shape, not by recording order. `getReferrerSpikes`'s own return value is-byte-identical between the two (`JSON.stringify(v1) === JSON.stringify(v2)`).--**topReferrers** — IDENTICAL; rows V1/V2 = 8/8; rows_read V1/V2 = 65436/65436; wall V1/V2 = 37 ms / 12 ms; `meta` identical ([{"name": "referrer_name", "type": "String"}, {"name": "total", "type": "Int64"}]); clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT referrer_name, sum(sign) AS total FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND referrer_name != '' AND referrer_name IS NOT NULL AND country = 'US' GROUP BY referrer_name HAVING sum(sign) >= 10 ORDER BY total DESC LIMIT 50--- V2-SELECT referrer_name, sum(sign) AS total FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND referrer_name != '' AND referrer_name IS NOT NULL AND country = {p4:String} GROUP BY referrer_name HAVING sum(sign) >= {p5:UInt64} ORDER BY total DESC LIMIT {p6:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "2026-07-01 00:00:00", "p3": "2026-07-08 00:00:00", "p4": "US", "p5": 10, "p6": 50}-```--**perBucketSessions** — IDENTICAL; rows V1/V2 = 47/47; rows_read V1/V2 = 65436/65436; wall V1/V2 = 13 ms / 12 ms; `meta` identical ([{"name": "date", "type": "DateTime"}, {"name": "referrer_name", "type": "String"}, {"name": "sessions", "type": "Int64"}]); clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT toStartOfDay(created_at) AS date, referrer_name, sum(sign) AS sessions FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND referrer_name IN ('Google', 'https://www.bwtrailerhitches.com', 'https://www.kingandprince.com', 'https://www.propper.com', 'Bing', 'DuckDuckGo', 'Twitter', 'https://www.packetsofhope.com') AND country = 'US' GROUP BY date, referrer_name HAVING sum(sign) > 0 ORDER BY date ASC--- V2-SELECT toStartOfDay(created_at) AS date, referrer_name, sum(sign) AS sessions FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND referrer_name IN {p4:Array(String)} AND country = {p5:String} GROUP BY date, referrer_name HAVING sum(sign) > 0 ORDER BY date ASC--- V2 params: {"p1": "secure-privacy", "p2": "2026-07-01 00:00:00", "p3": "2026-07-08 00:00:00", "p4": ["Google", "https://www.bwtrailerhitches.com", "https://www.kingandprince.com", "https://www.propper.com", "Bing", "DuckDuckGo", "Twitter", "https://www.packetsofhope.com"], "p5": "US"}-```--**bucketTotals** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 65436/65436; wall V1/V2 = 14 ms / 10 ms; `meta` identical ([{"name": "date", "type": "DateTime"}, {"name": "total", "type": "Int64"}]); clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT toStartOfDay(created_at) AS date, sum(sign) AS total FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND country = 'US' GROUP BY date HAVING sum(sign) > 0--- V2-SELECT toStartOfDay(created_at) AS date, sum(sign) AS total FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND country = {p4:String} GROUP BY date HAVING sum(sign) > 0--- V2 params: {"p1": "secure-privacy", "p2": "2026-07-01 00:00:00", "p3": "2026-07-08 00:00:00", "p4": "US"}-```-## `compiledText` callers left--Every `compiledText(` / `compiledTextWithProfileRefs(` call that wrapped a-`getEventFiltersWhereClause` result is gone — `sql.ts` (two sites),-`funnel.sql.ts`, `retention.sql.ts`, `conversion.sql.ts` (via `stepCondition`),-`sankey.sql.ts` (via `sessionEventCte`) and `overview.sql.ts` (via `rawWhere`)-all interpolate the fragment directly now. What remains wraps **only**-field-resolution output or a static SQL literal — M12-003's job — plus-`filter-where.ts`'s own two calls into the field resolver:--| file:line | what it wraps |-|---|---|-| `packages/core/src/modules/chart/src/filter-where.ts:144` | `getGroupPropertySql(name)` — field resolver |-| `packages/core/src/modules/chart/src/filter-where.ts:243` | `getSelectPropertyKey(...)` — field resolver |-| `packages/core/src/modules/chart/src/sql.ts:178` | a CTE name (static) |-| `packages/core/src/modules/chart/src/sql.ts:282` | a select-field list built from field-resolution output |-| `packages/core/src/modules/chart/src/sql.ts:332` | `spliced` — field resolver + profile-ref rewrite |-| `packages/core/src/modules/chart/src/sql.ts:348` | a cohort CTE name (static) |-| `packages/core/src/modules/chart/src/sql.ts:442` | a `label_N` alias (static) |-| `packages/core/src/modules/chart/src/sql.ts:443` | a `label_N` alias (static) |-| `packages/core/src/modules/chart/src/sql.ts:476` | a math aggregate name (closed set) |-| `packages/core/src/modules/chart/src/sql.ts:587` | a `label_N` alias (static) |-| `packages/core/src/modules/chart/src/sql.ts:691` | field-resolution select expression |-| `packages/core/src/modules/chart/src/sql.ts:700` | field-resolution select expression |-| `packages/core/src/modules/chart/src/sql.ts:713` | field-resolution select expression |-| `packages/core/src/modules/chart/src/sql.ts:797` | `getSelectPropertyKey(...)` — field resolver |-| `packages/core/src/modules/chart/src/funnel.sql.ts:79` | `STRICT_INCREASE_MODE` (static) |-| `packages/core/src/modules/chart/src/funnel.sql.ts:180` | `getSelectPropertyKey(...)` — field resolver |-| `packages/core/src/modules/chart/src/funnel.sql.ts:189` | a `b_N` alias (static) |-| `packages/core/src/modules/chart/src/funnel.sql.ts:303` | a `b_N` alias (static) |-| `packages/core/src/modules/chart/src/funnel.sql.ts:310` | a profile column list (`sql.id`-validated upstream) |-| `packages/core/src/modules/chart/src/funnel.sql.ts:323` | `buildInlineCohortJoin(...)` — field resolver |-| `packages/core/src/modules/chart/src/funnel.sql.ts:362` | a `b_N` alias (static) |-| `packages/core/src/modules/chart/src/funnel.sql.ts:387` | a `b_N` normalisation expression (static) |-| `packages/core/src/modules/chart/src/conversion.sql.ts:116` | a `b_N` alias (static) |-| `packages/core/src/modules/chart/src/conversion.sql.ts:131` | field-resolution breakdown selects |-| `packages/core/src/modules/chart/src/conversion.sql.ts:135` | field-resolution breakdown expressions |-| `packages/core/src/modules/chart/src/conversion.sql.ts:151` | `buildInlineCohortJoin(...)` — field resolver |-| `packages/core/src/modules/chart/src/retention.sql.ts:170` | `SQL_START_OF[interval]` (closed set) |-| `packages/core/src/modules/chart/src/retention.sql.ts:171` | an interval unit (closed set) |-| `packages/core/src/modules/chart/src/retention.sql.ts:172` | `COUNT_CRITERIA[criteria]` (closed set) |-| `packages/core/src/modules/chart/src/retention.sql.ts:200` | a numeric column index (static) |-| `packages/core/src/modules/chart/src/retention.sql.ts:206` | a numeric column index (static) |-| `packages/core/src/modules/chart/src/sankey.sql.ts:28` | `DEDUPE_CONSECUTIVE` (static) |-| `packages/core/src/modules/chart/src/sankey.sql.ts:38` | `TRUNCATE_AT_REPEAT` (static) |-| `packages/core/src/modules/chart/src/sankey.sql.ts:48` | `TRANSITION_PAIRS` (static) |-| `packages/core/src/modules/chart/src/sankey.sql.ts:187` | `BETWEEN_SLICE` (static) |-| `packages/core/src/modules/chart/src/sankey.sql.ts:201` | a CTE name (static) |-| `packages/core/src/modules/overview/src/overview.sql.ts:117` | `toIntervalStep(interval)` (closed set) |-| `packages/core/src/modules/overview/src/overview.sql.ts:672` | `getSelectPropertyKey('properties.href')` — field resolver |--(`grep -rn "compiledText" packages/core/src --include=*.ts | grep -v src/compiled.ts`,-2026-09-07, minus the two `import` lines.)--## Tests whose assertion moved from TEXT to statement + params--| test | before | after |-|---|---|---|-| `overview.service / getRawWhereClause (UTM remapping)` › `rewrites utm_* to properties[__query.utm_*] for the events table` | `expect(where).toContain("properties['__query.utm_source']")` on the returned string | same `toContain` on `rendered(...).query`, **plus** `expect(query_params).toEqual({ p1: 'awn' })` |-| … › `keeps utm_* as a top-level column for the sessions table` | `expect(where).toMatch(/(?<![._\w])utm_source\s*=/)` on the string | same `toMatch` on `.query`, **plus** `expect(query_params).toEqual({ p1: 'awn' })` |-| … › `drops non-whitelisted filters` | `expect(where).toBe('')` | `expect(where).toBeNull()` — `joinFilterClauses` returns `null`, not `''` |-| … › `events utm_source filter parses against real events table` | `EXPLAIN` of a string-spliced statement | `EXPLAIN` of `.query` **with `query_params` passed to `ch.command`** — the params now have to bind for the EXPLAIN to pass |-| … › `sessions utm_source filter parses against real sessions table` | as above | as above |--No other test changed what it asserts. `event.sql.test.ts`,-`profile.sql.test.ts` and `session.sql.test.ts` keep their expected SQL text-byte-for-byte; only their `filterClauses` INPUT fixtures moved from-`{ f0: "(path = '/')" }` to `compiledFilterClauses({ f0: "(path = '/')" })`,-because `CompiledFilterClauses` is now `Record<string, SqlFragment>` while-`buildFilterWhere` (M12-003) still returns text. `overview.sql.test.ts` moved-its `rawFilterWhere: ''` fixtures to `rawFilterWhere: null` for the same reason.-`sql.test.ts` and `funnel.sql.test.ts` are untouched — they assert on-column expressions, which still come from the field resolver.--## Reproducing a case--Every statement above runs as written. V1:--```bash-curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC&default_format=JSONCompact' \- --data-binary "SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (path = '/')"-```--V2 — bind each `{pN:...}` / `{wN:...}` as `param_pN=` / `param_wN=`:--```bash-curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \- --data-urlencode 'default_format=JSONCompact' \- --data-urlencode 'param_w1=secure-privacy' \- --data-urlencode 'param_w2=2026-07-01 00:00:00' \- --data-urlencode 'param_w3=2026-07-08 00:00:00' \- --data-urlencode 'param_p1=/' \- --data-urlencode "query=SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (path = {p1:String})"-```--Both return `[[3066,986]]`.--## Goldens--`verification/golden/compare.sh` against the harness (`verification/harness-start`, api and worker both V2), run 2026-09-07 on this box after-`apps/api pnpm run e2e:sessions`:--```-target: http://127.0.0.1:3333-golden: http://127.0.0.1:3333 @ 2026-09-07T02:43:29Z-passed: 137/137-OK: zero diffs-```--**137/137, zero diffs, and no `stale:` line** — every one of the 137 cases-compared; none was skipped for a rolled UTC day. `full.sh` re-ran the whole-manifest against a freshly started harness later in the same session and-reported `passed: 137/137` / `OK: zero diffs` again.--The known unstable case, `insights-event-property-values`, passed in both runs.-It reads `event_property_values_mv` — an `AggregatingMergeTree` whose `ORDER BY`-does not include `created_at`, queried `ORDER BY created_at DESC LIMIT 200`, so-its top-200 reshuffles whenever a background merge lands. It is not in this-task's path either way: it is served by `eventPropertyValuesQuery`-(`packages/core/src/modules/event/src/event.sql.ts`), which imports no filter-compiler and is not in this diff.--## Verification run--All commands run in `/home/deploy/openpanel` on 2026-09-07 against the tree as-committed. `verification/` paths are in `/home/deploy/rewrite-openpanel`.--| command | result |-|---|---|-| `pnpm run typecheck` | green — every workspace `Done` |-| `cd packages/core && bun test` | `1469 pass, 12 skip, 0 fail`, 4760 expect() calls, 1481 tests across 153 files |-| `pnpm test` (`bun test --isolate` at the root) | `1469 pass, 12 skip, 0 fail`, 1481 tests across 153 files |-| `pnpm run check:deps` | `no dependency violations found (2271 modules, 9839 dependencies cruised)` |-| `bash tooling/gates/p12-grep-gates.sh --report` | TOTAL `sqlstring 115 / clix 73 / sql-builder 6` (baseline `168 / 77 / 6`); `filter-where.ts` no longer appears in the table at all |-| `test -f packages/core/src/modules/chart/src/filter-where.sql.proof.md` | present (this file) |-| `verification/harness start` | `OK: api ready on :3333 (3s)` / `OK: worker ready on :9999 (3s)`, both V2 |-| `cd apps/api && timeout 900 pnpm run e2e:sessions` | **29/29 checks passed** |-| `verification/golden/compare.sh` | **`passed: 137/137`**, `OK: zero diffs`, no stale |-| `verification/harness stop` | `OK: api stopped` / `OK: worker stopped` |-| `verification/full.sh` | **`FULL: green`, RC=0** — 22 `OK:` stages, zero `FAIL:`, zero `BLOCKED`; includes forbidden-patterns, install, typecheck api + start, `pnpm test`, golden seed, harness, `golden/compare.sh` 137/137, `contracts/auth`, `contracts/sdk` (incl. the dist gate), `golden/openapi v2-diff` |--### Gate movement--`sqlstring` dropped by 53 — all of `filter-where.ts`, which leaves the table-with 0 in every column. `clix` dropped by 4: `referrer-spikes.ts`, converted-because the fragment's params cannot cross clix's `execute()` — see *Consumer-conversion* above. Nothing else moved; `sql-builder` is unchanged at 6.--### Lint--`npx ultracite check` on the 25 changed `.ts` files reports 4 errors, all-pre-existing: the identical 4 fire on the same two files restored from HEAD-(`overview.service.ts` `useConsistentTypeDefinitions` at HEAD:98 / here:101 and-`noUnusedVariables` at HEAD:45 / here:48; two `noMisplacedAssertion` in-`overview-raw-where.sql.test.ts`, where Biome does not recognise the file's-`itCH(...)` wrapper as a test call, at HEAD:95,108 / here:115,131). Only the-line numbers move. No new lint debt.diff --git a/packages/core/src/modules/chart/src/funnel.sql.proof.md b/packages/core/src/modules/chart/src/funnel.sql.proof.mddeleted file mode 100644index 066f80a9d..000000000--- a/packages/core/src/modules/chart/src/funnel.sql.proof.md+++ /dev/null@@ -1,261 +0,0 @@-# funnel.sql.ts — V1 -> V2 result-set proof (M7-004)--Both funnel statements were executed twice against the same data — once as V1 (the `git HEAD` `packages/db/src/services/funnel.service.ts` plus the `getFunnelProfiles` composition from `chart.service.ts`, `c4760ac2`, captured by wrapping the shared ClickHouse client) and once as V2 (the fragment the core builders return) — through one `@clickhouse/client` with `format: 'JSON'` and the same `session_timezone`. The two responses were compared on `data` (every row, every column, as JSON) and `meta` (column names and types).--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static). Projects: `secure-privacy`, `verdict`, `bayse` (America/New_York), `dream-mate` (Australia/Sydney).-- **Machine**: single-node ClickHouse on a 4-vCPU box — timings are directional only; production is 2 shards x 2 replicas (`docs/ENVIRONMENT.md`). The statements contain no `IN (subquery)`; the profiles `LEFT JOIN`, the groups `ARRAY JOIN` and the cohort joins keep V1's exact shape, so no `IN` / `GLOBAL IN` decision is made or unmade here.-- **Note on `LIMIT 1000`**: the profile-list cases that return 1000 rows are capped by the statement's own `LIMIT` (V1's `FUNNEL_PROFILES_LIMIT`), and `SELECT DISTINCT ... LIMIT` carries no `ORDER BY` on either side; those cases came back with identical row *sequences* anyway, which is why they read IDENTICAL rather than IDENTICAL AS SET.--- **Verdict**: 21 cases, 0 not identical.--### funnelChartQuery — two steps, no breakdown (golden insights-funnel-two-steps shape)--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 7470531/7470531; wall V1/V2 = 198 ms / 199 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'view_lobby_item', events.name = 'view_picks') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'verdict' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND events.name IN ('view_lobby_item', 'view_picks') AND ((events.name = 'view_lobby_item') OR (events.name = 'view_picks')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((events.name = {p8:String}) OR (events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"view_lobby_item","p3":"view_picks","p4":"verdict","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":["view_lobby_item","view_picks"],"p8":"view_lobby_item","p9":"view_picks"}-```--### funnelChartQuery — three steps, profile_id group, 72h window (golden shape)--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 106489/106489; wall V1/V2 = 34 ms / 36 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT profile_id, windowFunnel(259200000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'screen_view', events.name = 'session_end') AS level FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND events.name IN ('session_start', 'screen_view', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'screen_view') OR (events.name = 'session_end')) GROUP BY profile_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT profile_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}, events.name = {p4:String}) AS level FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.name = {p9:String}) OR (events.name = {p10:String}) OR (events.name = {p11:String})) GROUP BY profile_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":259200000,"p2":"session_start","p3":"screen_view","p4":"session_end","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":["session_start","screen_view","session_end"],"p9":"session_start","p10":"screen_view","p11":"session_end"}-```--### funnelChartQuery — breakdown country (argMinIf attribution)--**IDENTICAL** — rows V1/V2 = 118/118; rows_read V1/V2 = 106489/106489; wall V1/V2 = 43 ms / 28 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'screen_view') AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(country, created_at, events.name = 'session_start') as b_0 FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND events.name IN ('session_start', 'screen_view') AND ((events.name = 'session_start') OR (events.name = 'screen_view')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(country, created_at, events.name = {p4:String}) as b_0 FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.name = {p9:String}) OR (events.name = {p10:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"screen_view","p4":"session_start","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":["session_start","screen_view"],"p9":"session_start","p10":"screen_view"}-```--### funnelChartQuery — two breakdowns (country + os)--**IDENTICAL** — rows V1/V2 = 284/284; rows_read V1/V2 = 65534/65534; wall V1/V2 = 24 ms / 24 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(country, created_at, events.name = 'session_start') as b_0, argMinIf(os, created_at, events.name = 'session_start') as b_1 FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, b_1, count() as count FROM funnel GROUP BY level, b_0, b_1 ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(country, created_at, events.name = {p4:String}) as b_0, argMinIf(os, created_at, events.name = {p5:String}) as b_1 FROM events WHERE project_id = {p6:String} AND created_at BETWEEN toDateTime({p7:String}) AND toDateTime({p8:String}) AND events.name IN {p9:Array(String)} AND ((events.name = {p10:String}) OR (events.name = {p11:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, b_1, count() as count FROM funnel GROUP BY level, b_0, b_1 ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"session_start","p5":"session_start","p6":"secure-privacy","p7":"2026-07-06 00:00:00","p8":"2026-07-09 23:59:59","p9":["session_start","session_end"],"p10":"session_start","p11":"session_end"}-```--### funnelChartQuery — step filters + step pre-filter--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 73724/73724; wall V1/V2 = 21 ms / 42 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), country = 'US' AND events.name = 'screen_view', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('screen_view', 'session_end') AND ((country = 'US' AND events.name = 'screen_view') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), country = 'US' AND events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((country = 'US' AND events.name = {p8:String}) OR (events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"screen_view","p3":"session_end","p4":"secure-privacy","p5":"2026-07-06 00:00:00","p6":"2026-07-09 23:59:59","p7":["screen_view","session_end"],"p8":"screen_view","p9":"session_end"}-```--### funnelChartQuery — profile.* filter -> profiles LEFT JOIN--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 376510/376510; wall V1/V2 = 76 ms / 68 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id FROM events LEFT JOIN (SELECT id, email FROM profiles FINAL WHERE project_id = 'secure-privacy') as profile ON profile.id = events.profile_id WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events LEFT JOIN (SELECT id, email FROM profiles FINAL WHERE project_id = {p4:String}) as profile ON profile.id = events.profile_id WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.name = {p9:String}) OR (events.name = {p10:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"secure-privacy","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-09 23:59:59","p8":["session_start","session_end"],"p9":"session_start","p10":"session_end"}-```--### funnelChartQuery — profile.properties breakdown -> narrowed properties CTE--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 376510/376510; wall V1/V2 = 103 ms / 102 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(`profile.properties.plan`, created_at, events.name = 'session_start') as b_0 FROM events LEFT JOIN (SELECT id, properties['plan'] as `profile.properties.plan` FROM profiles FINAL WHERE project_id = 'secure-privacy') as profile ON profile.id = events.profile_id WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(`profile.properties.plan`, created_at, events.name = {p4:String}) as b_0 FROM events LEFT JOIN (SELECT id, properties['plan'] as `profile.properties.plan` FROM profiles FINAL WHERE project_id = {p5:String}) as profile ON profile.id = events.profile_id WHERE project_id = {p6:String} AND created_at BETWEEN toDateTime({p7:String}) AND toDateTime({p8:String}) AND events.name IN {p9:Array(String)} AND ((events.name = {p10:String}) OR (events.name = {p11:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"session_start","p5":"secure-privacy","p6":"secure-privacy","p7":"2026-07-06 00:00:00","p8":"2026-07-09 23:59:59","p9":["session_start","session_end"],"p10":"session_start","p11":"session_end"}-```--### funnelChartQuery — group.* breakdown -> ARRAY JOIN + per-row GROUP BY--**IDENTICAL** — rows V1/V2 = 8/8; rows_read V1/V2 = 68893/68893; wall V1/V2 = 33 ms / 36 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy'), session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id, _group_id as b_0 FROM events ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id, b_0), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}), session_funnel AS (SELECT session_id, windowFunnel({p2:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p3:String}, events.name = {p4:String}) AS level, argMax(profile_id, created_at) AS profile_id, _group_id as b_0 FROM events ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.name = {p9:String}) OR (events.name = {p10:String})) GROUP BY session_id, b_0), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2 params: {"p1":"secure-privacy","p2":86400000,"p3":"session_start","p4":"session_end","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-09 23:59:59","p8":["session_start","session_end"],"p9":"session_start","p10":"session_end"}-```--### funnelChartQuery — funnelGroup "group" forces the groups ARRAY JOIN--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 68893/68893; wall V1/V2 = 27 ms / 38 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy'), session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id FROM events ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}), session_funnel AS (SELECT session_id, windowFunnel({p2:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p3:String}, events.name = {p4:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.name = {p9:String}) OR (events.name = {p10:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":"secure-privacy","p2":86400000,"p3":"session_start","p4":"session_end","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-09 23:59:59","p8":["session_start","session_end"],"p9":"session_start","p10":"session_end"}-```--### funnelChartQuery — properties.* filter + properties.* breakdown--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 65534/65534; wall V1/V2 = 29 ms / 29 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.properties['__query.utm_source'] != '' AND events.name = 'screen_view', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(properties['__path'], created_at, events.properties['__query.utm_source'] != '' AND events.name = 'screen_view') as b_0 FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('screen_view', 'session_end') AND ((events.properties['__query.utm_source'] != '' AND events.name = 'screen_view') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.properties['__query.utm_source'] != '' AND events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(properties['__path'], created_at, events.properties['__query.utm_source'] != '' AND events.name = {p4:String}) as b_0 FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.properties['__query.utm_source'] != '' AND events.name = {p9:String}) OR (events.name = {p10:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"screen_view","p3":"session_end","p4":"screen_view","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-09 23:59:59","p8":["screen_view","session_end"],"p9":"screen_view","p10":"session_end"}-```--### funnelChartQuery — unknown + all-cohorts breakdowns dropped--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 65534/65534; wall V1/V2 = 33 ms / 34 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((events.name = {p8:String}) OR (events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"secure-privacy","p5":"2026-07-06 00:00:00","p6":"2026-07-09 23:59:59","p7":["session_start","session_end"],"p8":"session_start","p9":"session_end"}-```--### funnelChartQuery — globalFilters merged into every step--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 81916/81916; wall V1/V2 = 26 ms / 28 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), os = 'iOS' AND events.name = 'session_start', os = 'iOS' AND events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((os = 'iOS' AND events.name = 'session_start') OR (os = 'iOS' AND events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), os = 'iOS' AND events.name = {p2:String}, os = 'iOS' AND events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((os = 'iOS' AND events.name = {p8:String}) OR (os = 'iOS' AND events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"secure-privacy","p5":"2026-07-06 00:00:00","p6":"2026-07-09 23:59:59","p7":["session_start","session_end"],"p8":"session_start","p9":"session_end"}-```--### funnelChartQuery — non-UTC session timezone (America/New_York)--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 7945887/7945887; wall V1/V2 = 146 ms / 161 ms; clickhouse_settings: {"session_timezone":"America/New_York"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'screen_view') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'bayse' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND events.name IN ('session_start', 'screen_view') AND ((events.name = 'session_start') OR (events.name = 'screen_view')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((events.name = {p8:String}) OR (events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"screen_view","p4":"bayse","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":["session_start","screen_view"],"p8":"session_start","p9":"screen_view"}-```--### funnelChartQuery — Sydney DST window, 168h (golden insights-funnel-syd-dst shape)--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 7962156/7962156; wall V1/V2 = 217 ms / 229 ms; clickhouse_settings: {"session_timezone":"Australia/Sydney"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(604800000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'screen_view', events.name = 'send_message') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'dream-mate' AND created_at BETWEEN toDateTime('2026-08-01 00:00:00') AND toDateTime('2026-10-31 23:59:59') AND events.name IN ('screen_view', 'send_message') AND ((events.name = 'screen_view') OR (events.name = 'send_message')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((events.name = {p8:String}) OR (events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, count() as count FROM funnel GROUP BY level ORDER BY level DESC--- V2 params: {"p1":604800000,"p2":"screen_view","p3":"send_message","p4":"dream-mate","p5":"2026-08-01 00:00:00","p6":"2026-10-31 23:59:59","p7":["screen_view","send_message"],"p8":"screen_view","p9":"send_message"}-```--### funnelChartQuery — four steps, limit 3, breakdown device--**IDENTICAL** — rows V1/V2 = 3/3; rows_read V1/V2 = 73724/73724; wall V1/V2 = 31 ms / 27 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'screen_view', events.name = 'screen_view', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(device, created_at, events.name = 'session_start') as b_0 FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'screen_view', 'screen_view', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'screen_view') OR (events.name = 'screen_view') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}, events.name = {p4:String}, events.name = {p5:String}) AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(device, created_at, events.name = {p6:String}) as b_0 FROM events WHERE project_id = {p7:String} AND created_at BETWEEN toDateTime({p8:String}) AND toDateTime({p9:String}) AND events.name IN {p10:Array(String)} AND ((events.name = {p11:String}) OR (events.name = {p12:String}) OR (events.name = {p13:String}) OR (events.name = {p14:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT level, b_0, count() as count FROM funnel GROUP BY level, b_0 ORDER BY level DESC--- V2 params: {"p1":86400000,"p2":"session_start","p3":"screen_view","p4":"screen_view","p5":"session_end","p6":"session_start","p7":"secure-privacy","p8":"2026-07-06 00:00:00","p9":"2026-07-09 23:59:59","p10":["session_start","screen_view","screen_view","session_end"],"p11":"session_start","p12":"screen_view","p13":"screen_view","p14":"session_end"}-```--### funnelProfilesQuery — level >= 2, no breakdown--**IDENTICAL** — rows V1/V2 = 1000/1000; rows_read V1/V2 = 65534/65534; wall V1/V2 = 49 ms / 32 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= 2 LIMIT 1000--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((events.name = {p8:String}) OR (events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= {p10:UInt64} LIMIT {p11:UInt64}--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"secure-privacy","p5":"2026-07-06 00:00:00","p6":"2026-07-09 23:59:59","p7":["session_start","session_end"],"p8":"session_start","p9":"session_end","p10":2,"p11":1000}-```--### funnelProfilesQuery — level = 1 dropoffs (rare second step), no breakdown--**IDENTICAL** — rows V1/V2 = 1000/1000; rows_read V1/V2 = 65534/65534; wall V1/V2 = 29 ms / 43 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'link_out') AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'link_out') AND ((events.name = 'session_start') OR (events.name = 'link_out')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level = 1 LIMIT 1000--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id FROM events WHERE project_id = {p4:String} AND created_at BETWEEN toDateTime({p5:String}) AND toDateTime({p6:String}) AND events.name IN {p7:Array(String)} AND ((events.name = {p8:String}) OR (events.name = {p9:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level = {p10:UInt64} LIMIT {p11:UInt64}--- V2 params: {"p1":86400000,"p2":"session_start","p3":"link_out","p4":"secure-privacy","p5":"2026-07-06 00:00:00","p6":"2026-07-09 23:59:59","p7":["session_start","link_out"],"p8":"session_start","p9":"link_out","p10":1,"p11":1000}-```--### funnelProfilesQuery — level >= 2, breakdown value "US"--**IDENTICAL** — rows V1/V2 = 1000/1000; rows_read V1/V2 = 65534/65534; wall V1/V2 = 45 ms / 31 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(country, created_at, events.name = 'session_start') as b_0 FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= 2 AND trim(ifNull(toString(b_0), '')) = 'US' LIMIT 1000--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(country, created_at, events.name = {p4:String}) as b_0 FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.name = {p9:String}) OR (events.name = {p10:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= {p11:UInt64} AND trim(ifNull(toString(b_0), '')) = {p12:String} LIMIT {p13:UInt64}--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"session_start","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-09 23:59:59","p8":["session_start","session_end"],"p9":"session_start","p10":"session_end","p11":2,"p12":"US","p13":1000}-```--### funnelProfilesQuery — level >= 2, breakdown value "Not set" (empty-bucket match)--**IDENTICAL** — rows V1/V2 = 1000/1000; rows_read V1/V2 = 65534/65534; wall V1/V2 = 51 ms / 56 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT session_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(properties['__query.utm_source'], created_at, events.name = 'session_start') as b_0 FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= 2 AND (trim(ifNull(toString(b_0), '')) = '' OR trim(ifNull(toString(b_0), '')) = 'Not set') LIMIT 1000--- V2-WITH session_funnel AS (SELECT session_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMax(profile_id, created_at) AS profile_id, argMinIf(properties['__query.utm_source'], created_at, events.name = {p4:String}) as b_0 FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND events.name IN {p8:Array(String)} AND ((events.name = {p9:String}) OR (events.name = {p10:String})) GROUP BY session_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= {p11:UInt64} AND (trim(ifNull(toString(b_0), '')) = '' OR trim(ifNull(toString(b_0), '')) = {p12:String}) LIMIT {p13:UInt64}--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"session_start","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-09 23:59:59","p8":["session_start","session_end"],"p9":"session_start","p10":"session_end","p11":2,"p12":"Not set","p13":1000}-```--### funnelProfilesQuery — profile.properties breakdown, profile_id group--**IDENTICAL** — rows V1/V2 = 1000/1000; rows_read V1/V2 = 376510/376510; wall V1/V2 = 87 ms / 67 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_funnel AS (SELECT profile_id, windowFunnel(86400000, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = 'session_start', events.name = 'session_end') AS level, argMinIf(`profile.properties.plan`, created_at, events.name = 'session_start') as b_0 FROM events LEFT JOIN (SELECT id, properties['plan'] as `profile.properties.plan` FROM profiles FINAL WHERE project_id = 'secure-privacy') as profile ON profile.id = events.profile_id WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-09 23:59:59') AND events.name IN ('session_start', 'session_end') AND ((events.name = 'session_start') OR (events.name = 'session_end')) GROUP BY profile_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= 2 LIMIT 1000--- V2-WITH session_funnel AS (SELECT profile_id, windowFunnel({p1:UInt64}, 'strict_increase')(toUInt64(toUnixTimestamp64Milli(created_at)), events.name = {p2:String}, events.name = {p3:String}) AS level, argMinIf(`profile.properties.plan`, created_at, events.name = {p4:String}) as b_0 FROM events LEFT JOIN (SELECT id, properties['plan'] as `profile.properties.plan` FROM profiles FINAL WHERE project_id = {p5:String}) as profile ON profile.id = events.profile_id WHERE project_id = {p6:String} AND created_at BETWEEN toDateTime({p7:String}) AND toDateTime({p8:String}) AND events.name IN {p9:Array(String)} AND ((events.name = {p10:String}) OR (events.name = {p11:String})) GROUP BY profile_id), funnel AS (SELECT * FROM session_funnel WHERE level != 0) SELECT DISTINCT profile_id FROM funnel WHERE level >= {p12:UInt64} LIMIT {p13:UInt64}--- V2 params: {"p1":86400000,"p2":"session_start","p3":"session_end","p4":"session_start","p5":"secure-privacy","p6":"secure-privacy","p7":"2026-07-06 00:00:00","p8":"2026-07-09 23:59:59","p9":["session_start","session_end"],"p10":"session_start","p11":"session_end","p12":2,"p13":1000}-```--### funnelSessionsQuery — buildSessionsCte--**IDENTICAL** — rows V1/V2 = 100/100; rows_read V1/V2 = 24553/24553; wall V1/V2 = 8 ms / 9 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-SELECT profile_id as pid, id as sid FROM sessions WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-07 00:00:00') LIMIT 100--- V2-SELECT profile_id as pid, id as sid FROM sessions WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) LIMIT 100--- V2 params: {"p1":"secure-privacy","p2":"2026-07-06 00:00:00","p3":"2026-07-07 00:00:00"}-```diff --git a/packages/core/src/modules/chart/src/funnel.sql.ts b/packages/core/src/modules/chart/src/funnel.sql.tsindex 0135d44ee..7933f6fc7 100644--- a/packages/core/src/modules/chart/src/funnel.sql.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.ts@@ -1,26 +1,19 @@// Every ClickHouse statement the funnel service runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/funnel.service.ts and-// the `getFunnelProfiles` body in packages/trpc/src/routers/chart.ts (M7-004):-// the SQL text is V1's clix output, with the project id, event names, dates,-// the funnel window, the target level and the clicked breakdown values bound-// as `{pN:Type}` parameters instead of `sqlstring`-escaped literals. Result-set-// proof: funnel.sql.proof.md.+// (ADR-013).//-// The chart and the profile list are built from ONE base (V1's-// `buildFunnelBase`): a breakdown expression only works if the join it+// The chart and the profile list are built from ONE base: a breakdown expression only works if the join it// references was added, and the joins depend on the breakdowns, so building// the selects in one place and the joins in another is exactly the bug that// made funnel "View Users" return "No users found" for profile-property and// cohort breakdowns.//-// The field resolver and filter compiler still render text (see compiled.ts);-// their output — filter clauses, breakdown expressions, the profile CTE-// columns and the cohort joins — is spliced, everything else is bound.+// The field resolver and filter compiler render text (see compiled.ts); their+// output — filter clauses, breakdown expressions, the profile CTE columns and+// the cohort joins — is spliced, everything else is bound.//-// Cluster note (docs/ENVIRONMENT.md): `events`, `profiles`, `groups` and-// `cohort_members` are Distributed on Cloud. Every join keeps V1's exact shape-// and runs under the client's `distributed_product_mode: 'allow'` as before;-// no `IN (subquery)` is introduced or removed.+// Cluster note: `events`, `profiles`, `groups` and `cohort_members` are+// Distributed on Cloud. Every join runs under the client's+// `distributed_product_mode: 'allow'`; no `IN (subquery)` is involved.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type {diff --git a/packages/core/src/modules/chart/src/retention.sql.proof.md b/packages/core/src/modules/chart/src/retention.sql.proof.mddeleted file mode 100644index 246b52f7b..000000000--- a/packages/core/src/modules/chart/src/retention.sql.proof.md+++ /dev/null@@ -1,291 +0,0 @@-# retention.sql.ts — V1 -> V2 result-set proof (M7-004)--Every builder in `retention.sql.ts` was executed twice against the same data — once as V1 (the `git HEAD` `packages/db/src/services/retention.service.ts`, `c4760ac2`, captured by wrapping its `chQuery`) and once as V2 (the fragment returned by the core builder, bound through `query_params`) — through one `@clickhouse/client` with `format: 'JSON'` and the same client settings. The two responses were compared on `data` (every row, every column, as JSON) and `meta` (column names and types).--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static). Projects: `verdict`, `secure-privacy`, `dream-mate`.-- **Machine**: single-node ClickHouse on a 4-vCPU box — timings are directional only; production is 2 shards x 2 replicas (`docs/ENVIRONMENT.md`). None of these statements contains an `IN (subquery)`: the cohort matrix is a five-CTE self-join, unchanged from V1, so no `IN` / `GLOBAL IN` decision is made or unmade here.-- **Whitespace**: V2 joins the base WHERE conditions and the interval columns with the `sql` tag's closed separator set (`' AND '`, `', '`) instead of V1's newline-indented ones. Text-only; every result set below is byte-identical.-- **Contract test**: `packages/db/src/services/retention.service.test.ts` (11 cases, seeded fixtures on `openpanel_test`) is unchanged and runs against this code through the V1 shim.--- **Verdict**: 14 cases, 0 not identical.--### retentionSeriesQuery — verdict--**IDENTICAL** — rows V1/V2 = 9/9; rows_read V1/V2 = 88473638/88473638; wall V1/V2 = 3103 ms / 3053 ms.--```sql--- V1-WITH weekly_active AS ( SELECT profile_id, toStartOfWeek(created_at) AS week FROM events WHERE project_id = 'verdict' AND profile_id != device_id GROUP BY profile_id, week ) SELECT cur.week AS date, countDistinct(cur.profile_id) AS active_users, countDistinct(nxt.profile_id) AS retained_users, (100 * (countDistinct(nxt.profile_id) / CAST(countDistinct(cur.profile_id), 'Float64'))) AS retention FROM weekly_active AS cur LEFT JOIN weekly_active AS nxt ON cur.profile_id = nxt.profile_id AND nxt.week = cur.week + toIntervalWeek(1) GROUP BY date ORDER BY date ASC -- Unmatched LEFT JOIN rows must be NULL (not the empty-string default), -- otherwise countDistinct(nxt.profile_id) counts '' as a retained user. SETTINGS join_use_nulls = 1--- V2-WITH weekly_active AS ( SELECT profile_id, toStartOfWeek(created_at) AS week FROM events WHERE project_id = {p1:String} AND profile_id != device_id GROUP BY profile_id, week ) SELECT cur.week AS date, countDistinct(cur.profile_id) AS active_users, countDistinct(nxt.profile_id) AS retained_users, (100 * (countDistinct(nxt.profile_id) / CAST(countDistinct(cur.profile_id), 'Float64'))) AS retention FROM weekly_active AS cur LEFT JOIN weekly_active AS nxt ON cur.profile_id = nxt.profile_id AND nxt.week = cur.week + toIntervalWeek(1) GROUP BY date ORDER BY date ASC -- Unmatched LEFT JOIN rows must be NULL (not the empty-string default), -- otherwise countDistinct(nxt.profile_id) counts '' as a retained user. SETTINGS join_use_nulls = 1--- V2 params: {"p1":"verdict"}-```--### retentionSeriesQuery — secure-privacy--**IDENTICAL** — rows V1/V2 = 9/9; rows_read V1/V2 = 1130322/1130322; wall V1/V2 = 85 ms / 102 ms.--```sql--- V1-WITH weekly_active AS ( SELECT profile_id, toStartOfWeek(created_at) AS week FROM events WHERE project_id = 'secure-privacy' AND profile_id != device_id GROUP BY profile_id, week ) SELECT cur.week AS date, countDistinct(cur.profile_id) AS active_users, countDistinct(nxt.profile_id) AS retained_users, (100 * (countDistinct(nxt.profile_id) / CAST(countDistinct(cur.profile_id), 'Float64'))) AS retention FROM weekly_active AS cur LEFT JOIN weekly_active AS nxt ON cur.profile_id = nxt.profile_id AND nxt.week = cur.week + toIntervalWeek(1) GROUP BY date ORDER BY date ASC -- Unmatched LEFT JOIN rows must be NULL (not the empty-string default), -- otherwise countDistinct(nxt.profile_id) counts '' as a retained user. SETTINGS join_use_nulls = 1--- V2-WITH weekly_active AS ( SELECT profile_id, toStartOfWeek(created_at) AS week FROM events WHERE project_id = {p1:String} AND profile_id != device_id GROUP BY profile_id, week ) SELECT cur.week AS date, countDistinct(cur.profile_id) AS active_users, countDistinct(nxt.profile_id) AS retained_users, (100 * (countDistinct(nxt.profile_id) / CAST(countDistinct(cur.profile_id), 'Float64'))) AS retention FROM weekly_active AS cur LEFT JOIN weekly_active AS nxt ON cur.profile_id = nxt.profile_id AND nxt.week = cur.week + toIntervalWeek(1) GROUP BY date ORDER BY date ASC -- Unmatched LEFT JOIN rows must be NULL (not the empty-string default), -- otherwise countDistinct(nxt.profile_id) counts '' as a retained user. SETTINGS join_use_nulls = 1--- V2 params: {"p1":"secure-privacy"}-```--### rollingActiveUsersQuery — AMENDED 2026-09-27 (ISSUES.md H8c)--**The three records below are superseded: V2 now DIVERGES from V1 deliberately.**--The parity was real, and both sides were wrong in the same way. `date + n` smears each-active day forward, so with no upper bound the series ran up to `days - 1` days past today.-Measured on the seeded acme-web at `days = 7` with `today()` = 2026-09-27, it returned rows-for 2026-09-28 and 2026-09-29 — the chart drew two points into the future.--V2 adds `AND date <= today()` to the outer WHERE. On that data it removes exactly those two-rows, 98 → 96, and leaves every remaining value unchanged.--```sql--- V2 now (only the outer WHERE differs from the records below)-… ARRAY JOIN range({p2:UInt64}) AS n ) WHERE project_id = {p3:String} AND date <= today() GROUP BY date-```--The row counts recorded in the three entries below are therefore pre-amendment figures.--### rollingActiveUsersQuery — verdict, 7d--**IDENTICAL** — rows V1/V2 = 62/62; rows_read V1/V2 = 73247/73247; wall V1/V2 = 355 ms / 358 ms.--```sql--- V1-SELECT date, uniqMerge(profile_id) AS users FROM ( SELECT date + n AS date, profile_id, project_id FROM ( SELECT * FROM dau_mv WHERE project_id = 'verdict' ) ARRAY JOIN range(7) AS n ) WHERE project_id = 'verdict' GROUP BY date--- V2-SELECT date, uniqMerge(profile_id) AS users FROM ( SELECT date + n AS date, profile_id, project_id FROM ( SELECT * FROM dau_mv WHERE project_id = {p1:String} ) ARRAY JOIN range({p2:UInt64}) AS n ) WHERE project_id = {p3:String} GROUP BY date--- V2 params: {"p1":"verdict","p2":7,"p3":"verdict"}-```--### rollingActiveUsersQuery — secure-privacy, 30d--**IDENTICAL** — rows V1/V2 = 85/85; rows_read V1/V2 = 73247/73247; wall V1/V2 = 312 ms / 313 ms.--```sql--- V1-SELECT date, uniqMerge(profile_id) AS users FROM ( SELECT date + n AS date, profile_id, project_id FROM ( SELECT * FROM dau_mv WHERE project_id = 'secure-privacy' ) ARRAY JOIN range(30) AS n ) WHERE project_id = 'secure-privacy' GROUP BY date--- V2-SELECT date, uniqMerge(profile_id) AS users FROM ( SELECT date + n AS date, profile_id, project_id FROM ( SELECT * FROM dau_mv WHERE project_id = {p1:String} ) ARRAY JOIN range({p2:UInt64}) AS n ) WHERE project_id = {p3:String} GROUP BY date--- V2 params: {"p1":"secure-privacy","p2":30,"p3":"secure-privacy"}-```--### rollingActiveUsersQuery — dream-mate, 1d--**IDENTICAL** — rows V1/V2 = 56/56; rows_read V1/V2 = 73247/73247; wall V1/V2 = 250 ms / 252 ms.--```sql--- V1-SELECT date, uniqMerge(profile_id) AS users FROM ( SELECT date + n AS date, profile_id, project_id FROM ( SELECT * FROM dau_mv WHERE project_id = 'dream-mate' ) ARRAY JOIN range(1) AS n ) WHERE project_id = 'dream-mate' GROUP BY date--- V2-SELECT date, uniqMerge(profile_id) AS users FROM ( SELECT date + n AS date, profile_id, project_id FROM ( SELECT * FROM dau_mv WHERE project_id = {p1:String} ) ARRAY JOIN range({p2:UInt64}) AS n ) WHERE project_id = {p3:String} GROUP BY date--- V2 params: {"p1":"dream-mate","p2":1,"p3":"dream-mate"}-```--### retentionLastSeenSeriesQuery — verdict--**IDENTICAL** — rows V1/V2 = 56/56; rows_read V1/V2 = 44236819/44236819; wall V1/V2 = 1276 ms / 1274 ms.--```sql--- V1-WITH last_active AS ( SELECT max(created_at) AS last_active, profile_id FROM events WHERE (project_id = 'verdict') AND (device_id != profile_id) GROUP BY profile_id ) SELECT dateDiff('day', last_active, today()) AS days, countDistinct(profile_id) AS users FROM last_active GROUP BY days ORDER BY days ASC--- V2-WITH last_active AS ( SELECT max(created_at) AS last_active, profile_id FROM events WHERE (project_id = {p1:String}) AND (device_id != profile_id) GROUP BY profile_id ) SELECT dateDiff('day', last_active, today()) AS days, countDistinct(profile_id) AS users FROM last_active GROUP BY days ORDER BY days ASC--- V2 params: {"p1":"verdict"}-```--### retentionLastSeenSeriesQuery — secure-privacy--**IDENTICAL** — rows V1/V2 = 56/56; rows_read V1/V2 = 565161/565161; wall V1/V2 = 46 ms / 54 ms.--```sql--- V1-WITH last_active AS ( SELECT max(created_at) AS last_active, profile_id FROM events WHERE (project_id = 'secure-privacy') AND (device_id != profile_id) GROUP BY profile_id ) SELECT dateDiff('day', last_active, today()) AS days, countDistinct(profile_id) AS users FROM last_active GROUP BY days ORDER BY days ASC--- V2-WITH last_active AS ( SELECT max(created_at) AS last_active, profile_id FROM events WHERE (project_id = {p1:String}) AND (device_id != profile_id) GROUP BY profile_id ) SELECT dateDiff('day', last_active, today()) AS days, countDistinct(profile_id) AS users FROM last_active GROUP BY days ORDER BY days ASC--- V2 params: {"p1":"secure-privacy"}-```--### retentionCohortQuery — any event, week, on_or_after (getRetentionCohortCore shape)--**IDENTICAL** — rows V1/V2 = 9/9; rows_read V1/V2 = 8945664/8945664; wall V1/V2 = 369 ms / 374 ms.--```sql--- V1-WITH cohort_users AS ( SELECT profile_id AS userID, toStartOfWeek(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-06-14 00:00:00') AND created_at <= toDateTime('2026-09-06 00:00:00') GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-06-14 00:00:00') AND created_at <= toDateTime('2026-09-06 00:00:00') + INTERVAL 12 WEEK ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff('WEEK', f.cohort_interval, toStartOfWeek(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff('WEEK', f.cohort_interval, toStartOfWeek(l.event_date)) <= 12 ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= 0) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= 1) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= 2) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= 3) AS interval_3_users, groupUniqArrayIf(profile_id, x_after_cohort >= 4) AS interval_4_users, groupUniqArrayIf(profile_id, x_after_cohort >= 5) AS interval_5_users, groupUniqArrayIf(profile_id, x_after_cohort >= 6) AS interval_6_users, groupUniqArrayIf(profile_id, x_after_cohort >= 7) AS interval_7_users, groupUniqArrayIf(profile_id, x_after_cohort >= 8) AS interval_8_users, groupUniqArrayIf(profile_id, x_after_cohort >= 9) AS interval_9_users, groupUniqArrayIf(profile_id, x_after_cohort >= 10) AS interval_10_users, groupUniqArrayIf(profile_id, x_after_cohort >= 11) AS interval_11_users, groupUniqArrayIf(profile_id, x_after_cohort >= 12) AS interval_12_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count, length(interval_4_users) AS interval_4_user_count, length(interval_5_users) AS interval_5_user_count, length(interval_6_users) AS interval_6_user_count, length(interval_7_users) AS interval_7_user_count, length(interval_8_users) AS interval_8_user_count, length(interval_9_users) AS interval_9_user_count, length(interval_10_users) AS interval_10_user_count, length(interval_11_users) AS interval_11_user_count, length(interval_12_users) AS interval_12_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2-WITH cohort_users AS ( SELECT profile_id AS userID, toStartOfWeek(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at <= toDateTime({p3:String}) GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) + INTERVAL {p7:UInt64} WEEK ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff({p8:String}, f.cohort_interval, toStartOfWeek(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff({p9:String}, f.cohort_interval, toStartOfWeek(l.event_date)) <= {p10:UInt64} ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= {p11:UInt64}) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p12:UInt64}) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p13:UInt64}) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p14:UInt64}) AS interval_3_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p15:UInt64}) AS interval_4_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p16:UInt64}) AS interval_5_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p17:UInt64}) AS interval_6_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p18:UInt64}) AS interval_7_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p19:UInt64}) AS interval_8_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p20:UInt64}) AS interval_9_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p21:UInt64}) AS interval_10_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p22:UInt64}) AS interval_11_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p23:UInt64}) AS interval_12_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count, length(interval_4_users) AS interval_4_user_count, length(interval_5_users) AS interval_5_user_count, length(interval_6_users) AS interval_6_user_count, length(interval_7_users) AS interval_7_user_count, length(interval_8_users) AS interval_8_user_count, length(interval_9_users) AS interval_9_user_count, length(interval_10_users) AS interval_10_user_count, length(interval_11_users) AS interval_11_user_count, length(interval_12_users) AS interval_12_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2 params: {"p1":"verdict","p2":"2026-06-14 00:00:00","p3":"2026-09-06 00:00:00","p4":"verdict","p5":"2026-06-14 00:00:00","p6":"2026-09-06 00:00:00","p7":12,"p8":"WEEK","p9":"WEEK","p10":12,"p11":0,"p12":1,"p13":2,"p14":3,"p15":4,"p16":5,"p17":6,"p18":7,"p19":8,"p20":9,"p21":10,"p22":11,"p23":12}-```--### retentionCohortQuery — named first+second event, day, on--**IDENTICAL** — rows V1/V2 = 7/7; rows_read V1/V2 = 163840/163840; wall V1/V2 = 42 ms / 38 ms.--```sql--- V1-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = 'verdict' AND name = 'session_start' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = 'verdict' AND name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') + INTERVAL 6 DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) <= 6 ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort = 0) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort = 1) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort = 2) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort = 3) AS interval_3_users, groupUniqArrayIf(profile_id, x_after_cohort = 4) AS interval_4_users, groupUniqArrayIf(profile_id, x_after_cohort = 5) AS interval_5_users, groupUniqArrayIf(profile_id, x_after_cohort = 6) AS interval_6_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count, length(interval_4_users) AS interval_4_user_count, length(interval_5_users) AS interval_5_user_count, length(interval_6_users) AS interval_6_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = {p1:String} AND name = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at <= toDateTime({p4:String}) GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = {p5:String} AND name = {p6:String} AND created_at >= toDateTime({p7:String}) AND created_at <= toDateTime({p8:String}) + INTERVAL {p9:UInt64} DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff({p10:String}, f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff({p11:String}, f.cohort_interval, toDate(l.event_date)) <= {p12:UInt64} ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort = {p13:UInt64}) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort = {p14:UInt64}) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort = {p15:UInt64}) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort = {p16:UInt64}) AS interval_3_users, groupUniqArrayIf(profile_id, x_after_cohort = {p17:UInt64}) AS interval_4_users, groupUniqArrayIf(profile_id, x_after_cohort = {p18:UInt64}) AS interval_5_users, groupUniqArrayIf(profile_id, x_after_cohort = {p19:UInt64}) AS interval_6_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count, length(interval_4_users) AS interval_4_user_count, length(interval_5_users) AS interval_5_user_count, length(interval_6_users) AS interval_6_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2 params: {"p1":"verdict","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"verdict","p6":"view_page","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59","p9":6,"p10":"DAY","p11":"DAY","p12":6,"p13":0,"p14":1,"p15":2,"p16":3,"p17":4,"p18":5,"p19":6}-```--### retentionCohortQuery — multi first event (IN), week, on_or_after--**IDENTICAL** — rows V1/V2 = 3/3; rows_read V1/V2 = 65536/65536; wall V1/V2 = 25 ms / 29 ms.--```sql--- V1-WITH cohort_users AS ( SELECT profile_id AS userID, toStartOfWeek(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = 'secure-privacy' AND name IN ('session_start', 'screen_view') AND created_at >= toDateTime('2026-06-01 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = 'secure-privacy' AND name IN ('screen_view', 'session_end') AND created_at >= toDateTime('2026-06-01 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') + INTERVAL 5 WEEK ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff('WEEK', f.cohort_interval, toStartOfWeek(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff('WEEK', f.cohort_interval, toStartOfWeek(l.event_date)) <= 5 ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= 0) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= 1) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= 2) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= 3) AS interval_3_users, groupUniqArrayIf(profile_id, x_after_cohort >= 4) AS interval_4_users, groupUniqArrayIf(profile_id, x_after_cohort >= 5) AS interval_5_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count, length(interval_4_users) AS interval_4_user_count, length(interval_5_users) AS interval_5_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2-WITH cohort_users AS ( SELECT profile_id AS userID, toStartOfWeek(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = {p1:String} AND name IN {p2:Array(String)} AND created_at >= toDateTime({p3:String}) AND created_at <= toDateTime({p4:String}) GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = {p5:String} AND name IN {p6:Array(String)} AND created_at >= toDateTime({p7:String}) AND created_at <= toDateTime({p8:String}) + INTERVAL {p9:UInt64} WEEK ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff({p10:String}, f.cohort_interval, toStartOfWeek(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff({p11:String}, f.cohort_interval, toStartOfWeek(l.event_date)) <= {p12:UInt64} ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= {p13:UInt64}) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p14:UInt64}) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p15:UInt64}) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p16:UInt64}) AS interval_3_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p17:UInt64}) AS interval_4_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p18:UInt64}) AS interval_5_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count, length(interval_4_users) AS interval_4_user_count, length(interval_5_users) AS interval_5_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2 params: {"p1":"secure-privacy","p2":["session_start","screen_view"],"p3":"2026-06-01 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":["screen_view","session_end"],"p7":"2026-06-01 00:00:00","p8":"2026-07-12 23:59:59","p9":5,"p10":"WEEK","p11":"WEEK","p12":5,"p13":0,"p14":1,"p15":2,"p16":3,"p17":4,"p18":5}-```--### retentionCohortQuery — month interval, any event--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 114688/114688; wall V1/V2 = 23 ms / 24 ms.--```sql--- V1-WITH cohort_users AS ( SELECT profile_id AS userID, toStartOfMonth(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-04-01 00:00:00') AND created_at <= toDateTime('2026-07-01 00:00:00') GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-04-01 00:00:00') AND created_at <= toDateTime('2026-07-01 00:00:00') + INTERVAL 3 MONTH ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff('MONTH', f.cohort_interval, toStartOfMonth(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff('MONTH', f.cohort_interval, toStartOfMonth(l.event_date)) <= 3 ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= 0) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= 1) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= 2) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= 3) AS interval_3_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2-WITH cohort_users AS ( SELECT profile_id AS userID, toStartOfMonth(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at <= toDateTime({p3:String}) GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) + INTERVAL {p7:UInt64} MONTH ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff({p8:String}, f.cohort_interval, toStartOfMonth(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff({p9:String}, f.cohort_interval, toStartOfMonth(l.event_date)) <= {p10:UInt64} ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= {p11:UInt64}) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p12:UInt64}) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p13:UInt64}) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p14:UInt64}) AS interval_3_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2 params: {"p1":"secure-privacy","p2":"2026-04-01 00:00:00","p3":"2026-07-01 00:00:00","p4":"secure-privacy","p5":"2026-04-01 00:00:00","p6":"2026-07-01 00:00:00","p7":3,"p8":"MONTH","p9":"MONTH","p10":3,"p11":0,"p12":1,"p13":2,"p14":3}-```--### retentionCohortQuery — property filter -> raw events fallback--**IDENTICAL** — rows V1/V2 = 4/4; rows_read V1/V2 = 196602/196602; wall V1/V2 = 50 ms / 57 ms.--```sql--- V1-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM events WHERE project_id = 'secure-privacy' AND profile_id != device_id AND country = 'US' AND name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-09 23:59:59') GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM events WHERE project_id = 'secure-privacy' AND profile_id != device_id AND country = 'US' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-09 23:59:59') + INTERVAL 3 DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) <= 3 ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= 0) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= 1) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= 2) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= 3) AS interval_3_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM events WHERE project_id = {p1:String} AND profile_id != device_id AND country = 'US' AND name = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at <= toDateTime({p4:String}) GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM events WHERE project_id = {p5:String} AND profile_id != device_id AND country = 'US' AND created_at >= toDateTime({p6:String}) AND created_at <= toDateTime({p7:String}) + INTERVAL {p8:UInt64} DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff({p9:String}, f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff({p10:String}, f.cohort_interval, toDate(l.event_date)) <= {p11:UInt64} ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= {p12:UInt64}) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p13:UInt64}) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p14:UInt64}) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p15:UInt64}) AS interval_3_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-09 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-09 23:59:59","p8":3,"p9":"DAY","p10":"DAY","p11":3,"p12":0,"p13":1,"p14":2,"p15":3}-```--### retentionCohortQuery — hour interval (toDate/DAY mapping), any event--**IDENTICAL** — rows V1/V2 = 3/3; rows_read V1/V2 = 3579904/3579904; wall V1/V2 = 90 ms / 95 ms.--```sql--- V1-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = 'dream-mate' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 00:00:00') GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = 'dream-mate' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 00:00:00') + INTERVAL 2 DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) <= 2 ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= 0) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= 1) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= 2) AS interval_2_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at <= toDateTime({p3:String}) GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) + INTERVAL {p7:UInt64} DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff({p8:String}, f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff({p9:String}, f.cohort_interval, toDate(l.event_date)) <= {p10:UInt64} ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= {p11:UInt64}) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p12:UInt64}) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p13:UInt64}) AS interval_2_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2 params: {"p1":"dream-mate","p2":"2026-07-06 00:00:00","p3":"2026-07-08 00:00:00","p4":"dream-mate","p5":"2026-07-06 00:00:00","p6":"2026-07-08 00:00:00","p7":2,"p8":"DAY","p9":"DAY","p10":2,"p11":0,"p12":1,"p13":2}-```--### retentionCohortQuery — ISO dates with T separator--**IDENTICAL** — rows V1/V2 = 4/4; rows_read V1/V2 = 1474560/1474560; wall V1/V2 = 55 ms / 59 ms.--```sql--- V1-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-09 23:59:59') GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-09 23:59:59') + INTERVAL 3 DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff('DAY', f.cohort_interval, toDate(l.event_date)) <= 3 ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= 0) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= 1) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= 2) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= 3) AS interval_3_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2-WITH cohort_users AS ( SELECT profile_id AS userID, toDate(min(created_at)) AS cohort_interval FROM cohort_events_mv WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at <= toDateTime({p3:String}) GROUP BY profile_id ), last_event AS ( SELECT profile_id, toDate(created_at) AS event_date FROM cohort_events_mv WHERE project_id = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) + INTERVAL {p7:UInt64} DAY ), retention_matrix AS ( SELECT f.cohort_interval, l.profile_id, dateDiff({p8:String}, f.cohort_interval, toDate(l.event_date)) AS x_after_cohort FROM cohort_users AS f INNER JOIN last_event AS l ON f.userID = l.profile_id WHERE l.event_date >= f.cohort_interval AND dateDiff({p9:String}, f.cohort_interval, toDate(l.event_date)) <= {p10:UInt64} ), interval_users AS ( SELECT cohort_interval, groupUniqArrayIf(profile_id, x_after_cohort >= {p11:UInt64}) AS interval_0_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p12:UInt64}) AS interval_1_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p13:UInt64}) AS interval_2_users, groupUniqArrayIf(profile_id, x_after_cohort >= {p14:UInt64}) AS interval_3_users FROM retention_matrix GROUP BY cohort_interval ), cohort_sizes AS ( SELECT cohort_interval, COUNT(DISTINCT userID) AS total_first_event_count FROM cohort_users GROUP BY cohort_interval ) SELECT interval_users.cohort_interval AS cohort_interval, cs.total_first_event_count AS total_first_event_count, length(interval_0_users) AS interval_0_user_count, length(interval_1_users) AS interval_1_user_count, length(interval_2_users) AS interval_2_user_count, length(interval_3_users) AS interval_3_user_count FROM interval_users LEFT JOIN cohort_sizes AS cs ON interval_users.cohort_interval = cs.cohort_interval ORDER BY cohort_interval ASC--- V2 params: {"p1":"verdict","p2":"2026-07-06 00:00:00","p3":"2026-07-09 23:59:59","p4":"verdict","p5":"2026-07-06 00:00:00","p6":"2026-07-09 23:59:59","p7":3,"p8":"DAY","p9":"DAY","p10":3,"p11":0,"p12":1,"p13":2,"p14":3}-```--## M34-002 — the REST retention series bounded to a window (Group C fix 8, remainder)--- **Date**: 2026-09-16, 09:20–09:30 UTC. **Data**: local prod-copy `openpanel`, read-only- (`readonly=2`; `events` read 321,191,857 before the run). `use_query_condition_cache=0`,- `max_memory_usage` 12 GiB. **Both statements were rendered by the builders themselves.** "Before" is- `retention.sql.ts` at `26a56aa0`, copied next to this file for the run and deleted afterwards.- "After" is this change. Parameters were bound through `param_pN=`. Timings are the median of 3- `FORMAT Null` runs, taken from `X-ClickHouse-Summary`. Each builder's three runs were back to back,- not interleaved. The result hash is the sha256 of one extra `FORMAT JSONEachRow` run. Only counts,- timings and hashes were kept; no row left the box.-- **Windows**: `1d` = 2026-08-25, `7d` = 2026-08-19 -> 08-25, `30d` = 2026-07-27 -> 08-25- (`23:59:59`-closed; the copy's last event is 2026-08-25 08:49). `default3m` is what a caller- naming no window got on the run day: `2026-06-16 00:00:00` -> `2026-09-17 00:00:00`.--Both `weekly_active` (series) and `last_active` (engagement) read every identified event the project-ever had. They now also carry `AND created_at BETWEEN toDateTime({pN:String}) AND-toDateTime({pM:String})`, the same spelling as `pages.sql.ts` and `profile/src/sql.ts`.-`/insights/:projectId/retention` and `/engagement` now accept `range` / `startDate` / `endDate`,-resolved by `resolveInsightsDateRange` like the sibling routes, with-`RETENTION_SERIES_DEFAULT_RANGE = '3m'` when `range` is omitted. That default lives **on the-routes only**. A service caller that passes no `startDate`/`endDate` still gets the all-time-statement, token-for-token and parameter-for-parameter the one at `26a56aa0` (checked by rendering-both builders). Only whitespace differs, because the bound fragment renders empty.--**The approved change:**-- series: a week before the window disappears, and a week the window cuts in half counts only its- in-window users.-- engagement: a profile whose last event is before the window is no longer counted. With `3m` it- stays wider than the 60-day `churned_60_plus` bucket, so that bucket still gets users.-- **Not changed:** the MCP tools `get_weekly_retention_series` (`mcp/.../active-users.ts`) and- `get_user_last_seen_distribution` (`mcp/.../engagement.ts`). They call the service with only- `projectId`, so they keep reading all time. Their contracts depend on that: up to- `MAX_WEEKLY_POINTS = 260` weeks, and a `churned_60_plus_days` bucket that must count profiles gone- for longer than any default window. Bounding them is a decision for the `mcp` module. It is out of- this task's scope and is handed forward.--> **Correction (attempt 2).** The first attempt put the `3m` fallback in the shared service-> functions. That silently capped both MCP tools to ~13 weeks and dropped long-churned profiles from-> the engagement distribution. Review rejected it. The fallback now lives only in-> `export.routes.ts`, and `retention.service.test.ts` keeps the no-window call asserting the full-> all-time series and all seven fixture profiles.--### Result sets and cost — before (all-time) vs after--`R` = result rows. Hash = the first 12 hex digits of the JSON result's sha256.--| project | statement | before (all-time) | after 1d | after 7d | after 30d | after `default3m` |-|---|---|---|---|---|---|---|-| `verdict` | series | 3,004 ms / 88.33 M rows / 63 MiB / R 9 / `700f4be4a890` | 36 ms / 0.60 M | 385 ms / 8.69 M | 1,648 ms / 44.59 M | 3,123 ms / 88.33 M / R 9 / **`700f4be4a890`** |-| `verdict` | lastSeen | 1,238 ms / 44.16 M / R 56 / `6476bf15f406` | 21 ms / 0.30 M | 142 ms / 4.35 M | 673 ms / 22.30 M | 1,288 ms / 44.16 M / R 56 / **`6476bf15f406`** |-| `bayse` | series | 2,423 ms / 76.49 M / R 9 / `8fdc236bf7e1` | 32 ms / 0.65 M | 334 ms / 9.30 M | 1,216 ms / 33.36 M | 2,601 ms / 76.49 M / **`8fdc236bf7e1`** |-| `bayse` | lastSeen | 1,039 ms / 38.25 M / R 56 / `0b08b3135340` | 16 ms / 0.33 M | 146 ms / 4.65 M | 522 ms / 16.68 M | 1,123 ms / 38.25 M / **`0b08b3135340`** |-| `earlysalary-production` | series | 2,159 ms / 53.58 M / 271 MiB / R 9 / `ac3fdda7c4c3` | 48 ms / 0.84 M | 285 ms / 5.96 M | 1,330 ms / 30.10 M | 2,293 ms / 53.58 M / **`ac3fdda7c4c3`** |-| `earlysalary-production` | lastSeen | 964 ms / 26.79 M / R 56 / `f9ac35c14bc3` | 24 ms / 0.42 M | 153 ms / 2.98 M | 586 ms / 15.05 M | 1,041 ms / 26.79 M / **`f9ac35c14bc3`** |-| `website-8103` | series | 131 ms / 46.25 M / R 0 | 24 ms / 0.53 M | 40 ms / 3.81 M | 185 ms / 24.24 M | 332 ms / 46.25 M / R 0 |-| `website-8103` | lastSeen | 63 ms / 23.13 M / R 0 | 11 ms / 0.26 M | 20 ms / 1.91 M | 90 ms / 12.12 M | 163 ms / 23.13 M / R 0 |-| `chatpaper` | series | 1,160 ms / 39.59 M / R 0 | 34 ms / 0.64 M | 163 ms / 4.64 M | 894 ms / 26.46 M | 1,288 ms / 39.59 M / R 0 |-| `chatpaper` | lastSeen | 583 ms / 19.80 M / R 0 | 15 ms / 0.32 M | 83 ms / 2.32 M | 447 ms / 13.23 M | 640 ms / 19.80 M / R 0 |-| `secure-privacy` | series | 75 ms / 1.11 M / R 9 / `87ee95b1e36e` | 30 ms / 0.36 M | 23 ms / 0.36 M | 50 ms / 0.97 M | 81 ms / 1.11 M / **`87ee95b1e36e`** |-| `secure-privacy` | lastSeen | 37 ms / 0.56 M / R 56 / `cddc379beaa3` | 9 ms / 0.18 M | 11 ms / 0.18 M | 27 ms / 0.48 M | 38 ms / 0.56 M / **`cddc379beaa3`** |--(`website-8103` and `chatpaper` have no identified profiles (`profile_id != device_id`), so both-statements return 0 rows either way.) The series reads each project's events **twice**, because-ClickHouse runs the `weekly_active` CTE once per reference. The self-join needs it on both sides.--**What this shows.**-- **`default3m` is byte-identical to the old all-time statement on all six projects.** On the run- day, every identified event in the copy (earliest 2026-07-01) is inside the default window, so the- answer is the same and so is the work (same `read_rows`; timings are within run-to-run noise).-- **Short windows are what gets cheaper:** 1d is 30–80x cheaper, and 7d is 7–8x cheaper.-- **This copy hides the real cost, and it cuts both ways, as with `page_titles`.** The copy holds- only ~8 weeks of data, so "all-time" here is small. In production, the old statement read the- tenant's **whole lifetime** on every call. There, a `3m` default is a strict improvement for any- tenant older than three months. The cost that is genuinely new is for **explicit windows longer- than the tenant's lifetime**, and there is none: a window can never read more rows than all-time- did. Unlike `page_titles`, this fix cannot make any statement more expensive than before. The one- thing it adds is on the REST routes: a Postgres lookup of the project timezone, the same one the- sibling `/insights` routes already do.--### Golden coverage — predicted: zero changes today, with a known date when that stops--The cases are `insights-retention-weekly` (`verdict`), `insights-retention-weekly-secure` and-`insights-engagement` (`verdict`). All three call the REST routes with **no query**, so they get-`default3m`. The-table above shows the identical result for both projects on the run day. The `insights-engagement`-normaliser works on dates and on summary sums, which are unchanged because the row set is unchanged.--**These cases stop being time-independent.** `insights-retention-weekly*` is marked-`deterministic`. That was true when the statement read all time. With a `3m` default, the window-start is `now - 3 months`. It passes the two projects' first identified event (2026-07-01, in UTC)-on **2026-10-02** (UTC; an organisation timezone other than UTC moves this by hours). From then on, the first week row (`2026-06-28`) shrinks and the cases differ-for a reason that has nothing to do with code. To stay reproducible, a re-capture would have to pin-`startDate`/`endDate`. That is M34-003's call; this task may not touch `verification/`.diff --git a/packages/core/src/modules/chart/src/retention.sql.ts b/packages/core/src/modules/chart/src/retention.sql.tsindex 04392d7c7..95f61d61e 100644--- a/packages/core/src/modules/chart/src/retention.sql.ts+++ b/packages/core/src/modules/chart/src/retention.sql.ts@@ -1,17 +1,12 @@// Every ClickHouse query the retention service runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/retention.service.ts-// (M7-004): the SQL text is V1's, with project id, event names, dates, the-// interval unit and the column count bound as `{pN:Type}` parameters instead-// of `sqlstring`-escaped literals. Result-set proofs against the local-// prod-copy are in retention.sql.proof.md.+// (ADR-013).//-// The filter compiler still renders text (see compiled.ts); its output is the-// only thing spliced into the cohort statement.+// The filter compiler renders text (see compiled.ts); its output is the only+// thing spliced into the cohort statement.//-// Cluster note (docs/ENVIRONMENT.md): `events`, `dau_mv` and `cohort_events_mv`-// are Distributed on Cloud. None of these statements contains an-// `IN (subquery)` — the cohort matrix is a CTE self-join, exactly V1's shape —-// so no `IN` / `GLOBAL IN` decision is made or unmade here.+// Cluster note: `events`, `dau_mv` and `cohort_events_mv` are Distributed on+// Cloud. None of these statements contains an `IN (subquery)` — the cohort+// matrix is a CTE self-join — so no `IN` / `GLOBAL IN` decision arises.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IChartEventFilter } from '../../report/report.constants';diff --git a/packages/core/src/modules/chart/src/sankey.sql.proof.md b/packages/core/src/modules/chart/src/sankey.sql.proof.mddeleted file mode 100644index 07bb7f260..000000000--- a/packages/core/src/modules/chart/src/sankey.sql.proof.md+++ /dev/null@@ -1,348 +0,0 @@-# sankey.sql.ts — V1 -> V2 result-set proof (M7-004)--Both statements of every sankey mode were executed twice against the same data — once as V1 (the `git HEAD` `packages/db/src/services/sankey.service.ts`, `c4760ac2`, captured by wrapping the shared ClickHouse client) and once as V2 (the fragment the core service sends) — through one `@clickhouse/client` with `format: 'JSON'` and the same `session_timezone`. The two responses were compared on `data` and `meta`. In addition, the two services' full JSON results (nodes + links, after all of the post-processing) were compared for all 12 cases: **12/12 identical**.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static). Projects: `secure-privacy`, `bayse` (America/New_York).-- **Machine**: single-node ClickHouse on a 4-vCPU box — timings are directional only; production is 2 shards x 2 replicas (`docs/ENVIRONMENT.md`).-- **Cluster note.** The `HAVING session_id IN (SELECT session_id FROM start_event_sessions)` clauses are V1's and are ported **verbatim**: no `IN` was converted to or from `GLOBAL IN`. Whether they should be `GLOBAL IN` on the 2x2 cluster is a pre-existing question this conversion neither answers nor changes (`docs/ENVIRONMENT.md`), and it is recorded as debt in the task report.-- **One case reads IDENTICAL AS SET.** The transitions statement orders by `step ASC, value DESC`, which leaves rows sharing a `(step, value)` pair in arbitrary order. Measured on 2026-09-04: **V1's own statement, executed 4 times unchanged, returned 4 different row orders and one identical row set.** Row order is therefore not part of the contract — the service groups transitions by step and source before using them — so that case is compared as a set, exactly as M7-003 compared the chart statements.--- **Amended by M27-001 (2026-09-15): the dedup expression is no longer V1's.** V1's- `arrayFilter((x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw))`- is Theta(n^2) in the longest single session's event count and could not answer at a 7-day window on- a busy project (`docs/ANALYTICS_PERFORMANCE.md` section 6.1). Every `-- V2` statement below now reads- `arrayCompact(groupArray(event_name))`; the `-- V1` statements are left exactly as V1 wrote them, so the- two columns differ in that one expression by design. Re-proved against the local prod copy on- **2026-09-15**, `use_query_condition_cache=0`, `max_memory_usage=6 GiB`, per-query `memory_usage` and- `elapsed_ns` read off `X-ClickHouse-Summary`:- - **Result sets:** `cityHash64(arraySort(groupArray(tuple(*))))` compared old vs new on every- (project, window) pair where the old spelling still survives — `earlysalary-production` 30 d and- `chatpaper` 30 d, both statements: **identical, 4/4**. One of the four (`earlysalary-production`'s- transitions statement) also differs in row ORDER between the two spellings — and equally between two- runs of either spelling, because of the `(step, value)` ties the bullet above already records. It is- compared as a set for that reason.- - **Cost, both statements, `mode: 'after'`, 3 steps, 30-day window:** `verdict` FAIL -> 2,931 ms /- 660 MiB · `bayse` FAIL -> 4,606 ms / 1,327 MiB · `earlysalary-production` 10,129 ms -> 5,927 ms /- 1,504 MiB · `website-8103` FAIL (`would use 2.03 PiB`) -> 2,607 ms / 1,035 MiB · `chatpaper`- 13,453 ms -> 12,639 ms / 2,132 MiB. `website-8103` at 1 day: FAIL (`768.88 GiB`) -> 147 ms / 20 MiB.--- **Amended by M31-004 (2026-09-16): the statements are unchanged, but windows over 93 days no longer reach them.**- `arrayCompact` turned the sankey from *fails* into *slow*; it did not make the window cheap. Both- statements still scan every event in the range and hold one `groupArray` per session, so cost is- linear in the window and `steps` bounds the answer, not the work. Re-measured on the local- production copy on **2026-09-16**, `use_query_condition_cache=0`, `max_memory_usage=6 GiB`,- `elapsed_ns` / `read_rows` / `memory_usage` read off `X-ClickHouse-Summary`, `bayse`, mode- `after`, 3 steps, per statement:-- | window | topEntries | transitions | read_rows | peak memory |- |---|---|---|---:|---|- | 7 d | 871 ms | 731 ms | 10,271,382 | 515 / 519 MiB |- | 14 d | 1,315 ms | 1,284 ms | 19,020,434 | 831 / 832 MiB |- | 30 d | 2,361 ms | 2,196 ms | 33,961,756 | 1,329 / 1,324 MiB |- | 45 d | 3,125 ms | 2,965 ms | 50,967,354 | 1,770 / 1,772 MiB |- | 56 d (the whole copy) | 3,832 ms | 3,954 ms | 76,461,848 | 2,060 / 2,061 MiB |-- **The copy holds only 56 days (2026-07-01 -> 2026-08-25), so `3m`, `6m` and `12m` all read the- same 76.46 M rows and cost the same 3.8 s + 4.0 s here** — a 12-month window cannot be measured- on this data, only extrapolated. The five points above are linear at ~60 ms and ~31 MiB per day- per statement, which puts a real 12-month tenant of bayse's shape at ~22 s and ~11.8 GiB per- statement, twice per call, against a 13.72 GiB overcommit ceiling.-- `getSankeyChart` therefore refuses a window wider than `MAX_SANKEY_WINDOW_DAYS` (93, the widest- span the picker's `3m` can produce) with a `BAD_REQUEST` naming the limit, before either- statement is built. Measured the same day, 3 runs in-process against a `deps` proxy that throws- if ClickHouse is touched: **0.474 / 0.043 / 0.012 ms, no ClickHouse contact**; the proxy is the- standing regression gate in `sankey.service.test.ts`.-- **Where the bound is applied, and what it deliberately leaves alone.** §12 fix 9's endpoint- column reads `chart.sankey` *specifically*, because it is the dashboard range picker that offers- `12m`/`lastYear`. The check therefore sits in `getSankeyChart` — the `chart.sankey` entry point,- and the place where `getChartStartEndDate` turns a picked range into dates — not in `getSankey`,- which is the shared chokepoint three other surfaces reach through `getUserFlowCore`:- the REST `/insights/:projectId/user_flow` route, the MCP `get_user_flow` tool and the assistant- tool. Those three take caller-supplied dates rather than picker ranges, are outside fix 9's- endpoint list, and keep their existing behaviour; `get_user_flow`'s own integration test asks for- `2000-01-01`..`2099-01-01` and still passes unchanged.-- **Residual (recorded, not fixed here):** those three surfaces can still ask for a 12-month- sankey and pay the ~22 s x 2 this section measures. Bounding them is a separate decision per- surface — the MCP and REST tools have their own limit vocabulary (`zLimit`, `resolveDateRange`)- and live outside this task's scope.--- **Verdict**: 23 cases, 0 not identical.--### sankey topEntries — after, screen_view, 3 steps (golden insights-user-flow-after)--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 352206/352206; wall V1/V2 = 117 ms / 81 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p11:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"screen_view","p9":3,"p10":2,"p11":3}-```--### sankey transitions — after, screen_view, 3 steps (golden insights-user-flow-after)--**IDENTICAL** — rows V1/V2 = 19/19; rows_read V1/V2 = 352206/352206; wall V1/V2 = 120 ms / 127 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('screen_view')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p11:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"screen_view","p9":3,"p10":2,"p11":["screen_view"]}-```--### sankey topEntries — before, session_end, 3 steps (golden insights-user-flow-before)--**IDENTICAL** — rows V1/V2 = 3/3; rows_read V1/V2 = 352206/352206; wall V1/V2 = 121 ms / 102 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 3 + 1), arrayFirstIndex(x -> x = 'session_end', events_deduped) - greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 3 + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = {p8:String}, events_deduped) - {p9:UInt64} + 1), arrayFirstIndex(x -> x = {p10:String}, events_deduped) - greatest(1, arrayFirstIndex(x -> x = {p11:String}, events_deduped) - {p12:UInt64} + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p14:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"session_end","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"session_end","p9":3,"p10":"session_end","p11":"session_end","p12":3,"p13":2,"p14":3}-```--### sankey transitions — before, session_end, 3 steps (golden insights-user-flow-before)--**IDENTICAL** — rows V1/V2 = 7/7; rows_read V1/V2 = 352206/352206; wall V1/V2 = 98 ms / 96 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 3 + 1), arrayFirstIndex(x -> x = 'session_end', events_deduped) - greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 3 + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('session_start', 'link_out', 'screen_view')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = {p8:String}, events_deduped) - {p9:UInt64} + 1), arrayFirstIndex(x -> x = {p10:String}, events_deduped) - greatest(1, arrayFirstIndex(x -> x = {p11:String}, events_deduped) - {p12:UInt64} + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p14:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"session_end","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"session_end","p9":3,"p10":"session_end","p11":"session_end","p12":3,"p13":2,"p14":["session_start","link_out","screen_view"]}-```--### sankey topEntries — between, session_start -> session_end, 4 steps (golden insights-user-flow-between)--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 458695/458695; wall V1/V2 = 138 ms / 170 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, 4) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT session_id, events, arrayFirstIndex(x -> x = 'session_start', events) as start_index, arrayFirstIndex(x -> x = 'session_end', events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index) SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events, events[start_index] as entry_event FROM between_sessions) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p5:String} AND name = {p6:String} AND created_at BETWEEN toDateTime({p7:String}) AND toDateTime({p8:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p9:String} AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, {p12:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}) SELECT session_id, events, arrayFirstIndex(x -> x = {p14:String}, events) as start_index, arrayFirstIndex(x -> x = {p15:String}, events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index) SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events, events[start_index] as entry_event FROM between_sessions) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p16:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"session_end","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59","p9":"secure-privacy","p10":"2026-07-06 00:00:00","p11":"2026-07-12 23:59:59","p12":4,"p13":2,"p14":"session_start","p15":"session_end","p16":3}-```--### sankey transitions — between, session_start -> session_end, 4 steps (golden insights-user-flow-between)--**IDENTICAL** — rows V1/V2 = 9/9; rows_read V1/V2 = 458695/458695; wall V1/V2 = 205 ms / 167 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, 4) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT session_id, events, arrayFirstIndex(x -> x = 'session_start', events) as start_index, arrayFirstIndex(x -> x = 'session_end', events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index), session_paths AS (SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events FROM between_sessions HAVING events[1] IN ('session_start')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p5:String} AND name = {p6:String} AND created_at BETWEEN toDateTime({p7:String}) AND toDateTime({p8:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p9:String} AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, {p12:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}) SELECT session_id, events, arrayFirstIndex(x -> x = {p14:String}, events) as start_index, arrayFirstIndex(x -> x = {p15:String}, events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index), session_paths AS (SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events FROM between_sessions HAVING events[1] IN {p16:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"session_end","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59","p9":"secure-privacy","p10":"2026-07-06 00:00:00","p11":"2026-07-12 23:59:59","p12":4,"p13":2,"p14":"session_start","p15":"session_end","p16":["session_start"]}-```--### sankey topEntries — after with exclude (golden insights-user-flow-exclude)--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 352206/352206; wall V1/V2 = 108 ms / 81 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND name NOT IN ('session_end') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND name NOT IN {p8:Array(String)} ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p9:String}, events_deduped), {p10:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p11:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p12:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":["session_end"],"p9":"screen_view","p10":3,"p11":2,"p12":3}-```--### sankey transitions — after with exclude (golden insights-user-flow-exclude)--**IDENTICAL** — rows V1/V2 = 15/15; rows_read V1/V2 = 352206/352206; wall V1/V2 = 123 ms / 113 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND name NOT IN ('session_end') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('screen_view')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND name NOT IN {p8:Array(String)} ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p9:String}, events_deduped), {p10:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p11:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p12:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":["session_end"],"p9":"screen_view","p10":3,"p11":2,"p12":["screen_view"]}-```--### sankey topEntries — after with include list--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 352206/352206; wall V1/V2 = 136 ms / 96 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND name IN ('session_start', 'session_end', 'screen_view') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND name IN {p8:Array(String)} ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p9:String}, events_deduped), {p10:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p11:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p12:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":["session_start","session_end","screen_view"],"p9":"screen_view","p10":3,"p11":2,"p12":3}-```--### sankey transitions — after with include list--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 352206/352206; wall V1/V2 = 118 ms / 102 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND name IN ('session_start', 'session_end', 'screen_view') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('screen_view')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) AND name IN {p8:Array(String)} ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p9:String}, events_deduped), {p10:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p11:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p12:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":["session_start","session_end","screen_view"],"p9":"screen_view","p10":3,"p11":2,"p12":["screen_view"]}-```--### sankey topEntries — after with a start-event filter (country is US)--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 344016/344016; wall V1/V2 = 89 ms / 73 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND country = 'US' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) AND country = 'US' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p11:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"screen_view","p9":3,"p10":2,"p11":3}-```--### sankey transitions — after with a start-event filter (country is US)--**IDENTICAL** — rows V1/V2 = 9/9; rows_read V1/V2 = 344016/344016; wall V1/V2 = 101 ms / 79 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND country = 'US' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'screen_view', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('screen_view')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) AND country = 'US' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p11:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"screen_view","p9":3,"p10":2,"p11":["screen_view"]}-```--### sankey topEntries — after, 10 steps (max)--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 352206/352206; wall V1/V2 = 122 ms / 107 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'session_start', events_deduped), 10) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p11:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"session_start","p9":10,"p10":2,"p11":3}-```--### sankey transitions — after, 10 steps (max)--**IDENTICAL** — rows V1/V2 = 21/21; rows_read V1/V2 = 352206/352206; wall V1/V2 = 106 ms / 116 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'session_start', events_deduped), 10) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('session_start')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p11:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"session_start","p9":10,"p10":2,"p11":["session_start"]}-```--### sankey topEntries — before, 2 steps (min)--**IDENTICAL** — rows V1/V2 = 3/3; rows_read V1/V2 = 352206/352206; wall V1/V2 = 101 ms / 78 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 2 + 1), arrayFirstIndex(x -> x = 'session_end', events_deduped) - greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 2 + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = {p8:String}, events_deduped) - {p9:UInt64} + 1), arrayFirstIndex(x -> x = {p10:String}, events_deduped) - greatest(1, arrayFirstIndex(x -> x = {p11:String}, events_deduped) - {p12:UInt64} + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p14:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"session_end","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"session_end","p9":2,"p10":"session_end","p11":"session_end","p12":2,"p13":2,"p14":3}-```--### sankey transitions — before, 2 steps (min)--**IDENTICAL** — rows V1/V2 = 3/3; rows_read V1/V2 = 352206/352206; wall V1/V2 = 117 ms / 132 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 2 + 1), arrayFirstIndex(x -> x = 'session_end', events_deduped) - greatest(1, arrayFirstIndex(x -> x = 'session_end', events_deduped) - 2 + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('screen_view', 'link_out', 'web_vitals_lcp')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice( events_deduped, greatest(1, arrayFirstIndex(x -> x = {p8:String}, events_deduped) - {p9:UInt64} + 1), arrayFirstIndex(x -> x = {p10:String}, events_deduped) - greatest(1, arrayFirstIndex(x -> x = {p11:String}, events_deduped) - {p12:UInt64} + 1) + 1 ) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, events_sliced as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p14:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"session_end","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"session_end","p9":2,"p10":"session_end","p11":"session_end","p12":2,"p13":2,"p14":["screen_view","link_out","web_vitals_lcp"]}-```--### sankey topEntries — between with filters on both anchors--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 475070/475070; wall V1/V2 = 80 ms / 75 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND country = 'US' GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND os = 'iOS' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, 4) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT session_id, events, arrayFirstIndex(x -> x = 'session_start', events) as start_index, arrayFirstIndex(x -> x = 'session_end', events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index) SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events, events[start_index] as entry_event FROM between_sessions) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) AND country = 'US' GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p5:String} AND name = {p6:String} AND created_at BETWEEN toDateTime({p7:String}) AND toDateTime({p8:String}) AND os = 'iOS' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p9:String} AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, {p12:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}) SELECT session_id, events, arrayFirstIndex(x -> x = {p14:String}, events) as start_index, arrayFirstIndex(x -> x = {p15:String}, events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index) SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events, events[start_index] as entry_event FROM between_sessions) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p16:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"session_end","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59","p9":"secure-privacy","p10":"2026-07-06 00:00:00","p11":"2026-07-12 23:59:59","p12":4,"p13":2,"p14":"session_start","p15":"session_end","p16":3}-```--### sankey transitions — between with filters on both anchors--**IDENTICAL** — rows V1/V2 = 4/4; rows_read V1/V2 = 475070/475070; wall V1/V2 = 79 ms / 80 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND country = 'US' GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'session_end' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') AND os = 'iOS' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, 4) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT session_id, events, arrayFirstIndex(x -> x = 'session_start', events) as start_index, arrayFirstIndex(x -> x = 'session_end', events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index), session_paths AS (SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events FROM between_sessions HAVING events[1] IN ('session_start')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH between_sessions AS (WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) AND country = 'US' GROUP BY session_id), end_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p5:String} AND name = {p6:String} AND created_at BETWEEN toDateTime({p7:String}) AND toDateTime({p8:String}) AND os = 'iOS' GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p9:String} AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, {p12:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p13:UInt64}) SELECT session_id, events, arrayFirstIndex(x -> x = {p14:String}, events) as start_index, arrayFirstIndex(x -> x = {p15:String}, events) as end_index FROM session_paths HAVING start_index > 0 AND end_index > 0 AND start_index < end_index), session_paths AS (SELECT session_id, arraySlice(events, start_index, end_index - start_index + 1) as events FROM between_sessions HAVING events[1] IN {p16:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"session_end","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59","p9":"secure-privacy","p10":"2026-07-06 00:00:00","p11":"2026-07-12 23:59:59","p12":4,"p13":2,"p14":"session_start","p15":"session_end","p16":["session_start"]}-```--### sankey topEntries — between without endEvent falls back to simple mode--**IDENTICAL** — rows V1/V2 = 2/2; rows_read V1/V2 = 106489/106489; wall V1/V2 = 63 ms / 72 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, 3) as events_sliced FROM events_deduped_cte HAVING 1 = 1) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, {p8:UInt64}) as events_sliced FROM events_deduped_cte HAVING 1 = 1) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p9:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p10:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":3,"p9":2,"p10":3}-```--### sankey transitions — between without endEvent falls back to simple mode--**IDENTICAL** — rows V1/V2 = 17/17; rows_read V1/V2 = 106489/106489; wall V1/V2 = 102 ms / 82 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, 3) as events_sliced FROM events_deduped_cte HAVING 1 = 1) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('session_start', 'screen_view')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, 1, {p8:UInt64}) as events_sliced FROM events_deduped_cte HAVING 1 = 1) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p9:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p10:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":3,"p9":2,"p10":["session_start","screen_view"]}-```--### sankey topEntries — non-UTC session timezone (America/New_York), after--**IDENTICAL** — rows V1/V2 = 1/1; rows_read V1/V2 = 7863873/7863873; wall V1/V2 = 3555 ms / 3868 ms; clickhouse_settings: {"session_timezone":"America/New_York"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'bayse' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-08 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'bayse' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-08 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'session_start', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p11:UInt64}--- V2 params: {"p1":"bayse","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-08 23:59:59","p5":"bayse","p6":"2026-07-06 00:00:00","p7":"2026-07-08 23:59:59","p8":"session_start","p9":3,"p10":2,"p11":3}-```--### sankey transitions — non-UTC session timezone (America/New_York), after--**IDENTICAL AS SET** — rows V1/V2 = 515/515; rows_read V1/V2 = 7863873/7863873; wall V1/V2 = 3533 ms / 3659 ms; clickhouse_settings: {"session_timezone":"America/New_York"} (both).--```sql--- V1-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'bayse' AND name = 'session_start' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-08 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'bayse' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-08 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'session_start', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN ('session_start')) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2-WITH session_paths_base AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}), session_paths AS (SELECT session_id, events FROM session_paths_base HAVING events[1] IN {p11:Array(String)}) SELECT pair.1 as source, pair.2 as target, pair.3 as step, count() as value FROM ((SELECT arrayJoin(arrayMap(i -> (events[i], events[i + 1], i), range(1, length(events)))) as pair FROM session_paths WHERE length(events) >= 2)) GROUP BY source, target, step ORDER BY step ASC, value DESC--- V2 params: {"p1":"bayse","p2":"session_start","p3":"2026-07-06 00:00:00","p4":"2026-07-08 23:59:59","p5":"bayse","p6":"2026-07-06 00:00:00","p7":"2026-07-08 23:59:59","p8":"session_start","p9":3,"p10":2,"p11":["session_start"]}-```--### sankey stmt0 — no matching entry events -> empty--**IDENTICAL** — rows V1/V2 = 0/0; rows_read V1/V2 = 245717/245717; wall V1/V2 = 32 ms / 34 ms; clickhouse_settings: {"session_timezone":"UTC"} (both).--```sql--- V1-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = 'secure-privacy' AND name = 'no_such_event_xyz' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-06 00:00:00') AND toDateTime('2026-07-12 23:59:59') ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayFilter( (x, i) -> i = 1 OR x != events_raw[i - 1], groupArray(event_name) as events_raw, arrayEnumerate(events_raw) ) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = 'no_such_event_xyz', events_deduped), 3) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= 2) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT 3--- V2-WITH session_paths AS (WITH start_event_sessions AS (SELECT session_id FROM events WHERE project_id = {p1:String} AND name = {p2:String} AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String}) GROUP BY session_id), events_deduped_cte AS (WITH ordered_events AS (SELECT session_id, name as event_name, created_at FROM events WHERE project_id = {p5:String} AND created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String}) ORDER BY session_id ASC, created_at ASC) SELECT session_id, arrayCompact(groupArray(event_name)) as events_deduped FROM ordered_events GROUP BY session_id), events_sliced_cte AS (SELECT session_id, arraySlice(events_deduped, arrayFirstIndex(x -> x = {p8:String}, events_deduped), {p9:UInt64}) as events_sliced FROM events_deduped_cte HAVING session_id IN (SELECT session_id FROM start_event_sessions)) SELECT session_id, if( arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) = 0, events_sliced, arraySlice( events_sliced, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(events_sliced)) - 1 ) ) as events, events[1] as entry_event FROM events_sliced_cte HAVING length(events) >= {p10:UInt64}) SELECT entry_event, count() as count FROM session_paths GROUP BY entry_event ORDER BY count DESC LIMIT {p11:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"no_such_event_xyz","p3":"2026-07-06 00:00:00","p4":"2026-07-12 23:59:59","p5":"secure-privacy","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":"no_such_event_xyz","p9":3,"p10":2,"p11":3}-```diff --git a/packages/core/src/modules/chart/src/sankey.sql.ts b/packages/core/src/modules/chart/src/sankey.sql.tsindex c66f71b32..77f5a4c81 100644--- a/packages/core/src/modules/chart/src/sankey.sql.ts+++ b/packages/core/src/modules/chart/src/sankey.sql.ts@@ -1,19 +1,13 @@// Every ClickHouse statement the sankey (user-flow) service runs, as pure-// `sql` fragments (ADR-013). Converted 1:1 from-// packages/db/src/services/sankey.service.ts (M7-004): the SQL text is V1's-// clix output, with the project id, event names, dates, the step count and the-// top-entry event list bound as `{pN:Type}` parameters instead of hand-escaped-// literals. Result-set proof: sankey.sql.proof.md.+// `sql` fragments (ADR-013).//-// The filter compiler still renders text (see compiled.ts); only its output is+// The filter compiler renders text (see compiled.ts); only its output is// spliced.//-// Cluster note (docs/ENVIRONMENT.md): `events` is Distributed on Cloud, and the+// Cluster note: `events` is Distributed on Cloud, and the// `session_id IN (SELECT session_id FROM start_event_sessions)` HAVING clauses-// are plain `IN (subquery)` over a CTE — V1's exact shape, ported verbatim. No-// `IN` is converted to or from `GLOBAL IN` here; whether these should be-// `GLOBAL IN` on a cluster is a pre-existing question this conversion neither-// answers nor changes.+// are plain `IN (subquery)` over a CTE. Whether these should be `GLOBAL IN` on+// a cluster is an open question.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { compiledText } from './compiled';diff --git a/packages/core/src/modules/chart/src/sql.proof.md b/packages/core/src/modules/chart/src/sql.proof.mddeleted file mode 100644index fca0f4ba1..000000000--- a/packages/core/src/modules/chart/src/sql.proof.md+++ /dev/null@@ -1,991 +0,0 @@-# sql.ts — V1 → V2 result-set proof (M7-003)--> **Amended 2026-09-23 (port of main `a2cbf2e8`).** Two of the five "pre-existing-> V1 defects" below are no longer reproduced: `one_event_per_user` now aliases-> its subquery `e` instead of `subQuery`, and the aggregate shape no longer-> re-emits the outer WHERE. Defects 2 and 3 in the list below, and the cases at-> "chartSeriesQuery — all-cohorts breakdown + one_event_per_user" and-> "aggregateChartQuery — one_event_per_user + breakdown path", therefore record-> V1's behaviour and V2's behaviour *before* that port. Upstream fixed them in-> main after this proof was taken; the entries are kept as the record of what-> the conversion itself did, not as a description of the current code.-> Coverage for the new behaviour is `sql.test.ts`'s two `one_event_per_user`-> cases, which EXPLAIN against local ClickHouse and fail against the old alias.--Every query builder in `sql.ts` was executed twice against the same data — once as V1 (the `git HEAD` `packages/db/src/services/chart.service.ts` `getChartSql` / `getAggregateChartSql`, and the `packages/trpc/src/routers/chart.ts` clix / `createSqlBuilder` texts, `f1573b1a`) and once as V2 (the fragment returned by the core builder, bound through `query_params`) — through one `@clickhouse/client` with `format: 'JSON'` and the same `session_timezone`. The two responses were compared on `data` (every row, every column, as JSON) and `meta` (column names and types). Chart statements were compared as row **sets**: V1's `ORDER BY date ASC WITH FILL` leaves rows sharing a `date` in arbitrary order, and three V1-vs-V1 runs of the 191-row wildcard-breakdown case produced three different orders; the engine groups rows by label, so order is not part of the contract. Statements without an `ORDER BY` (values lists, getProfiles) were compared as sets for the same reason.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static). Projects: `verdict` / `secure-privacy` (UTC), `bayse` (America/New_York), `website-8103` (Asia/Kolkata), `dream-mate` (Australia/Sydney), `authc-project-a1` (the only project with a Postgres cohort; `cohort_members` is empty in the prod-copy, so cohort cases prove statement equivalence on 0 rows — positive-row coverage is `sql.test.ts` on `openpanel_test`).-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are directional only; production is 2 shards × 2 replicas (`docs/ENVIRONMENT.md`). The chart statements contain no `IN (subquery)`; cohort membership is a CTE joined on `profile_id`, unchanged from V1. `rows_read` is often lower for V2 (e.g. 245717 → 98299 on the multi-series case): ClickHouse's index analysis treats a bound `{p:String}` differently from an inline literal for the `created_at` range, with identical result sets — a perf note, not a semantic change.-- **Verdict**: 73 cases (28 `chartSeriesQuery`, 15 `aggregateChartQuery`, 30 router queries), all IDENTICAL. 5 of the 73 are **IDENTICAL ERROR**: V1 defects reproduced byte-for-byte on both sides, listed below, not fixed here (out of scope — the task is byte-equivalence, and each is recorded as debt in the task report).--Pre-existing V1 defects reproduced identically (both sides fail with the same ClickHouse error):--1. `chartSeriesQuery` — a `profile.properties.*` / `properties.__query.*` trailing-`.*` wildcard filter: `getSelectPropertyKey` produces `arrayMap(...)` while `getEventFiltersWhereClause` treats it as a scalar (no `%` → `isWildcard` false) → `Illegal type Array(String) of argument of function like` / `Array does not start with '['`. The `[*]` form works and is proven below.-2. `chartSeriesQuery` — all-cohorts (`cohort:*`) breakdown on the series shape: the `INNER JOIN _all_cohorts` makes the unqualified `uniqState(profile_id)` ambiguous; with `one_event_per_user` it is `Unknown expression _all_cohorts.cohort_id`. The aggregate shape works and is proven below.-3. `aggregateChartQuery` — `one_event_per_user` with a named event re-emits `WHERE e.name = …` outside the subquery → `Unknown expression or function identifier e.name`. Wildcard event works and is proven below.--The harness was a throwaway script (it imported V1 and V2 side by side); each statement below is complete and reproducible with `curl http://127.0.0.1:8123/?database=openpanel`, binding the V2 params as `param_pN=`. The projectCard chart statement differs in one deliberate way: V1 appended `SETTINGS session_timezone = '<tz>'` to the text, V2 passes the same value as `clickhouse_settings.session_timezone` — the proof runs both with that setting, and the row sets (92 daily buckets in `America/New_York`) are identical.--## chartSeriesQuery--### chartSeriesQuery — golden export-charts-basic (verdict, view_page, day)--**statement** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 7649340/7470531; wall V1/V2 = 181 ms / 162 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'view_page' as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"view_page","p2":"verdict","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```-### chartSeriesQuery — golden export-charts-breakdown-country (secure-privacy, breakdown country)--**statement** — IDENTICAL; rows V1/V2 = 6/6; rows_read V1/V2 = 0/0; wall V1/V2 = 29 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1) as total_count FROM (SELECT 'view_page' as label_0, count(*) as count, toStartOfDay(created_at) as date, country as label_1, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'secure-privacy' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY date, label_1) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1) as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, country as label_1, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date, label_1) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"view_page","p2":"secure-privacy","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — golden export-charts-multi-series-filters (secure-privacy, screen_view, country is US)--**statement** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 245717/98299; wall V1/V2 = 36 ms / 27 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE country = 'US' AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE country = 'US' AND project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"screen_view","p2":"secure-privacy","p3":"screen_view","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — golden export-charts-month-week-interval (verdict, week)--**statement** — IDENTICAL; rows V1/V2 = 5/5; rows_read V1/V2 = 24600197/24600197; wall V1/V2 = 460 ms / 442 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'view_page' as label_0, count(*) as count, toStartOfWeek(created_at, 1, 'UTC') as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at <= toDateTime('2026-07-31 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfWeek(toDateTime('2026-07-01 00:00:00'), 1, 'UTC') TO toStartOfWeek(toDateTime('2026-07-31 23:59:59'), 1, 'UTC') STEP toIntervalWeek(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfWeek(created_at, 1, {p2:String}) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfWeek(toDateTime({p7:String}), 1, {p8:String}) TO toStartOfWeek(toDateTime({p9:String}), 1, {p10:String}) STEP toIntervalWeek(1)--- V2 params: {"p1":"view_page","p2":"UTC","p3":"verdict","p4":"view_page","p5":"2026-07-01 00:00:00","p6":"2026-07-31 23:59:59","p7":"2026-07-01 00:00:00","p8":"UTC","p9":"2026-07-31 23:59:59","p10":"UTC"}-```--### chartSeriesQuery — golden export-charts-nyc-dst-spring (bayse, week, America/New_York)--**statement** — IDENTICAL; rows V1/V2 = 21/21; rows_read V1/V2 = 17710659/17595974; wall V1/V2 = 341 ms / 340 ms; clickhouse_settings: session_timezone=America/New_York (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'pm_order_open' as label_0, count(*) as count, toStartOfWeek(created_at, 1, 'America/New_York') as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'bayse' AND e.name = 'pm_order_open' AND created_at >= toDateTime('2026-03-01 00:00:00') AND created_at <= toDateTime('2026-07-15 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfWeek(toDateTime('2026-03-01 00:00:00'), 1, 'America/New_York') TO toStartOfWeek(toDateTime('2026-07-15 23:59:59'), 1, 'America/New_York') STEP toIntervalWeek(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfWeek(created_at, 1, {p2:String}) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfWeek(toDateTime({p7:String}), 1, {p8:String}) TO toStartOfWeek(toDateTime({p9:String}), 1, {p10:String}) STEP toIntervalWeek(1)--- V2 params: {"p1":"pm_order_open","p2":"America/New_York","p3":"bayse","p4":"pm_order_open","p5":"2026-03-01 00:00:00","p6":"2026-07-15 23:59:59","p7":"2026-03-01 00:00:00","p8":"America/New_York","p9":"2026-07-15 23:59:59","p10":"America/New_York"}-```--### chartSeriesQuery — golden export-charts-nyc-dst-fall (bayse, day, America/New_York)--**statement** — IDENTICAL; rows V1/V2 = 99/99; rows_read V1/V2 = 12131671/12107095; wall V1/V2 = 216 ms / 209 ms; clickhouse_settings: session_timezone=America/New_York (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'pm_order_open' as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'bayse' AND e.name = 'pm_order_open' AND created_at >= toDateTime('2026-08-01 00:00:00') AND created_at <= toDateTime('2026-11-08 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-08-01 00:00:00')) TO toStartOfDay(toDateTime('2026-11-08 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"pm_order_open","p2":"bayse","p3":"pm_order_open","p4":"2026-08-01 00:00:00","p5":"2026-11-08 23:59:59","p6":"2026-08-01 00:00:00","p7":"2026-11-08 23:59:59"}-```--### chartSeriesQuery — golden export-charts-ist-hour (website-8103, hour, Asia/Kolkata)--**statement** — IDENTICAL; rows V1/V2 = 48/48; rows_read V1/V2 = 913793/890640; wall V1/V2 = 30 ms / 26 ms; clickhouse_settings: session_timezone=Asia/Kolkata (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, count(*) as count, toStartOfHour(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'website-8103' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-08-01 00:00:00') AND created_at <= toDateTime('2026-08-02 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfHour(toDateTime('2026-08-01 00:00:00')) TO toStartOfHour(toDateTime('2026-08-02 23:59:59')) STEP toIntervalHour(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfHour(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfHour(toDateTime({p6:String})) TO toStartOfHour(toDateTime({p7:String})) STEP toIntervalHour(1)--- V2 params: {"p1":"screen_view","p2":"website-8103","p3":"screen_view","p4":"2026-08-01 00:00:00","p5":"2026-08-02 23:59:59","p6":"2026-08-01 00:00:00","p7":"2026-08-02 23:59:59"}-```--### chartSeriesQuery — golden export-charts-syd-dst (dream-mate, day, Australia/Sydney)--**statement** — IDENTICAL; rows V1/V2 = 91/91; rows_read V1/V2 = 7972226/7953964; wall V1/V2 = 171 ms / 171 ms; clickhouse_settings: session_timezone=Australia/Sydney (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'dream-mate' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-08-01 00:00:00') AND created_at <= toDateTime('2026-10-31 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-08-01 00:00:00')) TO toStartOfDay(toDateTime('2026-10-31 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"screen_view","p2":"dream-mate","p3":"screen_view","p4":"2026-08-01 00:00:00","p5":"2026-10-31 23:59:59","p6":"2026-08-01 00:00:00","p7":"2026-10-31 23:59:59"}-```--### chartSeriesQuery — minute interval (verdict, 1 hour)--**statement** — IDENTICAL; rows V1/V2 = 60/60; rows_read V1/V2 = 260132/24575; wall V1/V2 = 18 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'view_page' as label_0, count(*) as count, toStartOfMinute(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-06 01:00:00') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfMinute(toDateTime('2026-07-06 00:00:00')) TO toStartOfMinute(toDateTime('2026-07-06 01:00:00')) STEP toIntervalMinute(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfMinute(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfMinute(toDateTime({p6:String})) TO toStartOfMinute(toDateTime({p7:String})) STEP toIntervalMinute(1)--- V2 params: {"p1":"view_page","p2":"verdict","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"2026-07-06 01:00:00","p6":"2026-07-06 00:00:00","p7":"2026-07-06 01:00:00"}-```--### chartSeriesQuery — month interval with timezone (bayse, America/New_York)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 25083459/25034307; wall V1/V2 = 485 ms / 468 ms; clickhouse_settings: session_timezone=America/New_York (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'pm_order_open' as label_0, count(*) as count, toStartOfMonth(created_at, 'America/New_York') as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'bayse' AND e.name = 'pm_order_open' AND created_at >= toDateTime('2026-05-01 00:00:00') AND created_at <= toDateTime('2026-07-31 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfMonth(toDateTime('2026-05-01 00:00:00'), 'America/New_York') TO toStartOfMonth(toDateTime('2026-07-31 23:59:59'), 'America/New_York') STEP toIntervalMonth(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfMonth(created_at, {p2:String}) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfMonth(toDateTime({p7:String}), {p8:String}) TO toStartOfMonth(toDateTime({p9:String}), {p10:String}) STEP toIntervalMonth(1)--- V2 params: {"p1":"pm_order_open","p2":"America/New_York","p3":"bayse","p4":"pm_order_open","p5":"2026-05-01 00:00:00","p6":"2026-07-31 23:59:59","p7":"2026-05-01 00:00:00","p8":"America/New_York","p9":"2026-07-31 23:59:59","p10":"America/New_York"}-```--### chartSeriesQuery — wildcard event '*' + segment user (verdict)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 1185604/990411; wall V1/V2 = 48 ms / 45 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT '*' as label_0, countDistinct(profile_id) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT '*' as label_0, countDistinct(profile_id) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p1:String} AND created_at >= toDateTime({p2:String}) AND created_at <= toDateTime({p3:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p4:String})) TO toStartOfDay(toDateTime({p5:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"verdict","p2":"2026-07-06 00:00:00","p3":"2026-07-08 23:59:59","p4":"2026-07-06 00:00:00","p5":"2026-07-08 23:59:59"}-```--### chartSeriesQuery — segment session (verdict)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 1185604/982645; wall V1/V2 = 45 ms / 37 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'view_page' as label_0, countDistinct(session_id) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, countDistinct(session_id) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"view_page","p2":"verdict","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"2026-07-08 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-08 23:59:59"}-```--### chartSeriesQuery — segment user_average (verdict)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 982645/982645; wall V1/V2 = 33 ms / 33 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'view_page' as label_0, COUNT(*)::float / COUNT(DISTINCT profile_id)::float as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, COUNT(*)::float / COUNT(DISTINCT profile_id)::float as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"view_page","p2":"verdict","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"2026-07-08 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-08 23:59:59"}-```--### chartSeriesQuery — segment one_event_per_user + breakdown path (verdict)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 982645/982645; wall V1/V2 = 49 ms / 52 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'view_page' as label_0, count(*) as count, toStartOfDay(created_at) as date, path as label_1 FROM ( SELECT DISTINCT ON (profile_id) * from events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') ORDER BY profile_id, created_at DESC ) as subQuery GROUP BY date, label_1 ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, path as label_1 FROM ( SELECT DISTINCT ON (profile_id) * from events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) ORDER BY profile_id, created_at DESC ) as subQuery GROUP BY date, label_1 ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"view_page","p2":"verdict","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"2026-07-08 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-08 23:59:59"}-```--### chartSeriesQuery — segment group + breakdown group.name + filter group.type (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 44/44; rows_read V1/V2 = 249076/101658; wall V1/V2 = 26 ms / 23 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2) as total_count FROM (SELECT 'screen_view' as label_0, countDistinct(_group_id) as count, toStartOfDay(created_at) as date, _g.name as label_1, _g.properties['employees'] as label_2, uniqState(profile_id) as _uc_state FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE _g.type = 'company' AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY date, label_1, label_2) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2) as total_count FROM (SELECT {p2:String} as label_0, countDistinct(_group_id) as count, toStartOfDay(created_at) as date, _g.name as label_1, _g.properties['employees'] as label_2, uniqState(profile_id) as _uc_state FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE _g.type = 'company' AND project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY date, label_1, label_2) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p7:String})) TO toStartOfDay(toDateTime({p8:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"secure-privacy","p4":"screen_view","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — profile breakdown + profile.properties filter + narrowed CTE (secure-privacy)--**statement** — IDENTICAL (row order differs — see note); rows V1/V2 = 86/86; rows_read V1/V2 = 556693/433840; wall V1/V2 = 108 ms / 97 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties['country'] as `profile.properties.country`, properties['device'] as `profile.properties.device`, email as "profile.email", first_name as "profile.first_name" FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2) as total_count FROM (SELECT 'screen_view' as label_0, count(*) as count, toStartOfDay(created_at) as date, `profile.properties.device` as label_1, profile.first_name as label_2, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE (`profile.properties.country` != '' AND `profile.properties.country` IS NOT NULL) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY date, label_1, label_2) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-WITH profile AS (SELECT id as "profile.id", properties['country'] as `profile.properties.country`, properties['device'] as `profile.properties.device`, email as "profile.email", first_name as "profile.first_name" FROM profiles FINAL WHERE project_id = {p1:String}) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2) as total_count FROM (SELECT {p2:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, `profile.properties.device` as label_1, profile.first_name as label_2, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE (`profile.properties.country` != '' AND `profile.properties.country` IS NOT NULL) AND project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY date, label_1, label_2) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p7:String})) TO toStartOfDay(toDateTime({p8:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"secure-privacy","p4":"screen_view","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — profile wildcard filter (full map) + math property_max on profile.properties.longitude (secure-privacy)--**statement** — IDENTICAL ERROR (pre-existing V1 defect, both sides fail with the same ClickHouse error).--```-V1 ERROR: Illegal type Array(String) of argument of function like: In scope SELECT 'screen_view' AS label_0, max(toFloat64OrNull(`profile.properties.longitude`)) AS count, toStartOfDay(created_at) AS date, uniqState(profile_id) AS _uc_state FROM events AS e ANY LEFT JOIN profile ON profile.id = profile_id WHERE (arrayMap(x -> trimBoth(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.*'))) LIKE '%Chrome%') AND (project_id = 'secure-privacy') AND (e.name = 'screen_view') AND (created_at >= toDateTime('2026-07-06 00:00:00')) AND (created_at <= toDateTime('2026-07-12 23:59:59')) AND (`profile.properties.longitude` IS NOT NULL) AND notEmpty(`profile.properties.longitude`) GROUP BY date.-V2 ERROR: Illegal type Array(String) of argument of function like: In scope SELECT 'screen_view' AS label_0, max(toFloat64OrNull(`profile.properties.longitude`)) AS count, toStartOfDay(created_at) AS date, uniqState(profile_id) AS _uc_state FROM events AS e ANY LEFT JOIN profile ON profile.id = profile_id WHERE (arrayMap(x -> trimBoth(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.*'))) LIKE '%Chrome%') AND (project_id = 'secure-privacy') AND (e.name = 'screen_view') AND (created_at >= toDateTime('2026-07-06 00:00:00')) AND (created_at <= toDateTime('2026-07-12 23:59:59')) AND (`profile.properties.longitude` IS NOT NULL) AND notEmpty(`profile.properties.longitude`) GROUP BY date.-```--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties['longitude'] as `profile.properties.longitude`, properties as "profile.properties" FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, max(toFloat64OrNull(`profile.properties.longitude`)) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.*'))) LIKE '%Chrome%') AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND `profile.properties.longitude` IS NOT NULL AND notEmpty(`profile.properties.longitude`) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-WITH profile AS (SELECT id as "profile.id", properties['longitude'] as `profile.properties.longitude`, properties as "profile.properties" FROM profiles FINAL WHERE project_id = {p1:String}) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p2:String} as label_0, max(toFloat64OrNull(`profile.properties.longitude`)) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.*'))) LIKE '%Chrome%') AND project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) AND `profile.properties.longitude` IS NOT NULL AND notEmpty(`profile.properties.longitude`) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p7:String})) TO toStartOfDay(toDateTime({p8:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"secure-privacy","p4":"screen_view","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — properties breakdown __title + filters: properties.__query.gclid isNotNull, value gt, path regex, referrerName alias, utm_source bare (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 6/6; rows_read V1/V2 = 245717/0; wall V1/V2 = 40 ms / 18 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2, label_3) as total_count FROM (SELECT 'screen_view' as label_0, count(*) as count, toStartOfDay(created_at) as date, e.properties['__title'] as label_1, referrer_type as label_2, e.properties['__query.utm_medium'] as label_3, uniqState(profile_id) as _uc_state FROM events e WHERE (e.properties['__query.gclid'] != '' AND e.properties['__query.gclid'] IS NOT NULL) AND (toFloat64OrZero(e.properties['value']) > toFloat64('1')) AND (match(path, '^\\/.*')) AND (referrer_name = '' OR referrer_name IS NULL) AND (e.properties['__query.utm_source'] = '' OR e.properties['__query.utm_source'] IS NULL) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY date, label_1, label_2, label_3) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2, label_3) as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, e.properties['__title'] as label_1, referrer_type as label_2, e.properties['__query.utm_medium'] as label_3, uniqState(profile_id) as _uc_state FROM events e WHERE (e.properties['__query.gclid'] != '' AND e.properties['__query.gclid'] IS NOT NULL) AND (toFloat64OrZero(e.properties['value']) > toFloat64('1')) AND (match(path, '^\\/.*')) AND (referrer_name = '' OR referrer_name IS NULL) AND (e.properties['__query.utm_source'] = '' OR e.properties['__query.utm_source'] IS NULL) AND project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date, label_1, label_2, label_3) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"screen_view","p2":"secure-privacy","p3":"screen_view","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — math property_sum on numeric column duration + has_profile true + wildcard properties.* is (secure-privacy)--**statement** — IDENTICAL ERROR (pre-existing V1 defect, both sides fail with the same ClickHouse error).--```-V1 ERROR: Array does not start with '[' character: while converting '' to Array(String): while executing function notEquals on arguments arrayMap(x String -> trimBoth(x), mapValues(mapExtractKeyLike(__table2.properties, '__query.*'_String))) Array(String) Array(size = 0, UInt64(size = 0), String(size = 0)), ''_String String Const(size = 0, String(size = 1)).-V2 ERROR: Array does not start with '[' character: while converting '' to Array(String): while executing function notEquals on arguments arrayMap(x String -> trimBoth(x), mapValues(mapExtractKeyLike(__table2.properties, '__query.*'_String))) Array(String) Array(size = 0, UInt64(size = 0), String(size = 0)), ''_String String Const(size = 0, String(size = 1)).-```--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, sum(duration) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE profile_id != device_id AND (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.*'))) != '' AND arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.*'))) IS NOT NULL) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND duration IS NOT NULL GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, sum(duration) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE profile_id != device_id AND (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.*'))) != '' AND arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.*'))) IS NOT NULL) AND project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) AND duration IS NOT NULL GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"screen_view","p2":"secure-privacy","p3":"screen_view","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — math property_average on properties.ttfb + typed number filter (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 6/6; rows_read V1/V2 = 245717/0; wall V1/V2 = 35 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, avg(toFloat64OrNull(e.properties['ttfb'])) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE (toFloat64OrNull(toString(e.properties['renderDelay'])) >= toFloat64OrNull(toString('10'))) AND (toFloat64(duration) < toFloat64('100000')) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND e.properties['ttfb'] IS NOT NULL AND notEmpty(e.properties['ttfb']) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, avg(toFloat64OrNull(e.properties['ttfb'])) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE (toFloat64OrNull(toString(e.properties['renderDelay'])) >= toFloat64OrNull(toString('10'))) AND (toFloat64(duration) < toFloat64('100000')) AND project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) AND e.properties['ttfb'] IS NOT NULL AND notEmpty(e.properties['ttfb']) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"screen_view","p2":"secure-privacy","p3":"screen_view","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — inCohort / notInCohort filters + cohort:<id> breakdown (unknown cohort, empty members) (verdict)--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 0/0; wall V1/V2 = 22 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH `cohort-33333333-3333-4333-8333-333333333333` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = '33333333-3333-4333-8333-333333333333' AND project_id = 'verdict' ) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1) as total_count FROM (SELECT 'view_page' as label_0, count(*) as count, toStartOfDay(created_at) as date, if(notEmpty(cohort_33333333_3333_4333_8333_333333333333.profile_id), 'In Cohort', 'Not In Cohort') as label_1, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN `cohort-33333333-3333-4333-8333-333333333333` AS cohort_33333333_3333_4333_8333_333333333333 ON cohort_33333333_3333_4333_8333_333333333333.profile_id = e.profile_id WHERE e.profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222') AND project_id = 'verdict') AND e.profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('33333333-3333-4333-8333-333333333333') AND project_id = 'verdict') AND project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY date, label_1) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-WITH `cohort-33333333-3333-4333-8333-333333333333` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p1:String} AND project_id = {p2:String} ) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1) as total_count FROM (SELECT {p3:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, if(notEmpty(cohort_33333333_3333_4333_8333_333333333333.profile_id), {p4:String}, {p5:String}) as label_1, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN `cohort-33333333-3333-4333-8333-333333333333` AS cohort_33333333_3333_4333_8333_333333333333 ON cohort_33333333_3333_4333_8333_333333333333.profile_id = e.profile_id WHERE e.profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222') AND project_id = 'verdict') AND e.profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('33333333-3333-4333-8333-333333333333') AND project_id = 'verdict') AND project_id = {p6:String} AND e.name = {p7:String} AND created_at >= toDateTime({p8:String}) AND created_at <= toDateTime({p9:String}) GROUP BY date, label_1) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p10:String})) TO toStartOfDay(toDateTime({p11:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"33333333-3333-4333-8333-333333333333","p2":"verdict","p3":"view_page","p4":"In Cohort","p5":"Not In Cohort","p6":"verdict","p7":"view_page","p8":"2026-07-06 00:00:00","p9":"2026-07-08 23:59:59","p10":"2026-07-06 00:00:00","p11":"2026-07-08 23:59:59"}-```--### chartSeriesQuery — notInCohort filter only + cohort:<id> breakdown with named cohort (authc-project-a1)--**statement** — IDENTICAL ERROR (pre-existing V1 defect, both sides fail with the same ClickHouse error).--```-V1 ERROR: JOIN INNER JOIN ... ON _all_cohorts.profile_id = e.profile_id ambiguous identifier 'profile_id'. In scope SELECT '*' AS label_0, count(*) AS count, toStartOfDay(created_at) AS date, if(notEmpty(cohort_cccccccc_0000_4000_8000_000000000001.profile_id), 'Auth contract cohort', 'Not Auth contract cohort') AS label_1, transform(_all_cohorts.cohort_id, ['cccccccc-0000-4000-8000-000000000001'], ['Auth contract cohort'], 'Unknown') AS label_2, uniqState(profile_id) AS _uc_state FROM events AS e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id ANY LEFT JOIN `cohort-cccccccc-0000-4000-8000-000000000001` AS cohort_cccccccc_0000_4000_8000_000000000001 ON cohort_cccccccc_0000_4000_8000_000000000001.profile_id = e.profile_id WHERE (e.profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE (cohort_id IN ('cccccccc-0000-4000-8000-000000000001')) AND (project_id = 'authc-project-a1'))) AND (project_id = 'authc-project-a1') AND (created_at >= toDateTime('2026-07-06 00:00:00')) AND (created_at <= toDateTime('2026-07-08 23:59:59')) GROUP BY date, label_1, label_2.-V2 ERROR: JOIN INNER JOIN ... ON _all_cohorts.profile_id = e.profile_id ambiguous identifier 'profile_id'. In scope SELECT '*' AS label_0, count(*) AS count, toStartOfDay(created_at) AS date, if(notEmpty(cohort_cccccccc_0000_4000_8000_000000000001.profile_id), 'Auth contract cohort', 'Not Auth contract cohort') AS label_1, transform(_all_cohorts.cohort_id, _CAST(['cccccccc-0000-4000-8000-000000000001'], 'Array(String)'), _CAST(['Auth contract cohort'], 'Array(String)'), 'Unknown') AS label_2, uniqState(profile_id) AS _uc_state FROM events AS e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id ANY LEFT JOIN `cohort-cccccccc-0000-4000-8000-000000000001` AS cohort_cccccccc_0000_4000_8000_000000000001 ON cohort_cccccccc_0000_4000_8000_000000000001.profile_id = e.profile_id WHERE (e.profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE (cohort_id IN ('cccccccc-0000-4000-8000-000000000001')) AND (project_id = 'authc-project-a1'))) AND (project_id = 'authc-project-a1') AND (created_at >= toDateTime('2026-07-06 00:00:00')) AND (created_at <= toDateTime('2026-07-08 23:59:59')) GROUP BY date, label_1, label_2.-```--```sql--- V1-WITH _all_cohorts AS ( SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = 'authc-project-a1' ), `cohort-cccccccc-0000-4000-8000-000000000001` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cccccccc-0000-4000-8000-000000000001' AND project_id = 'authc-project-a1' ) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2) as total_count FROM (SELECT '*' as label_0, count(*) as count, toStartOfDay(created_at) as date, if(notEmpty(cohort_cccccccc_0000_4000_8000_000000000001.profile_id), 'Auth contract cohort', 'Not Auth contract cohort') as label_1, transform(_all_cohorts.cohort_id, ['cccccccc-0000-4000-8000-000000000001'], ['Auth contract cohort'], 'Unknown') as label_2, uniqState(profile_id) as _uc_state FROM events e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id LEFT ANY JOIN `cohort-cccccccc-0000-4000-8000-000000000001` AS cohort_cccccccc_0000_4000_8000_000000000001 ON cohort_cccccccc_0000_4000_8000_000000000001.profile_id = e.profile_id WHERE e.profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('cccccccc-0000-4000-8000-000000000001') AND project_id = 'authc-project-a1') AND project_id = 'authc-project-a1' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY date, label_1, label_2) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-WITH _all_cohorts AS ( SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = {p1:String} ), `cohort-cccccccc-0000-4000-8000-000000000001` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String} ) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1, label_2) as total_count FROM (SELECT '*' as label_0, count(*) as count, toStartOfDay(created_at) as date, if(notEmpty(cohort_cccccccc_0000_4000_8000_000000000001.profile_id), {p4:String}, {p5:String}) as label_1, transform(_all_cohorts.cohort_id, {p6:Array(String)}, {p7:Array(String)}, {p8:String}) as label_2, uniqState(profile_id) as _uc_state FROM events e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id LEFT ANY JOIN `cohort-cccccccc-0000-4000-8000-000000000001` AS cohort_cccccccc_0000_4000_8000_000000000001 ON cohort_cccccccc_0000_4000_8000_000000000001.profile_id = e.profile_id WHERE e.profile_id NOT IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('cccccccc-0000-4000-8000-000000000001') AND project_id = 'authc-project-a1') AND project_id = {p9:String} AND created_at >= toDateTime({p10:String}) AND created_at <= toDateTime({p11:String}) GROUP BY date, label_1, label_2) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p12:String})) TO toStartOfDay(toDateTime({p13:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"authc-project-a1","p2":"cccccccc-0000-4000-8000-000000000001","p3":"authc-project-a1","p4":"Auth contract cohort","p5":"Not Auth contract cohort","p6":["cccccccc-0000-4000-8000-000000000001"],"p7":["Auth contract cohort"],"p8":"Unknown","p9":"authc-project-a1","p10":"2026-07-06 00:00:00","p11":"2026-07-08 23:59:59","p12":"2026-07-06 00:00:00","p13":"2026-07-08 23:59:59"}-```--### chartSeriesQuery — all-cohorts breakdown dropped when project has no cohorts (verdict)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 982645/982645; wall V1/V2 = 49 ms / 33 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'view_page' as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"view_page","p2":"verdict","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"2026-07-08 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-08 23:59:59"}-```--### chartSeriesQuery — endDate before startDate: no WITH FILL (verdict)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 243749/0; wall V1/V2 = 13 ms / 7 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'view_page' as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-08 00:00:00') AND created_at <= toDateTime('2026-07-06 00:00:00') GROUP BY date) ORDER BY date ASC--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date) ORDER BY date ASC--- V2 params: {"p1":"view_page","p2":"verdict","p3":"view_page","p4":"2026-07-08 00:00:00","p5":"2026-07-06 00:00:00"}-```-### chartSeriesQuery — profile wildcard filter profile.properties.x[*] (full map CTE) + math property_max on profile.properties.longitude (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 6/6; rows_read V1/V2 = 417465/417465; wall V1/V2 = 150 ms / 96 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties['longitude'] as `profile.properties.longitude`, properties as "profile.properties" FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, max(toFloat64OrNull(`profile.properties.longitude`)) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE arrayExists(x -> x LIKE '%Chrome%', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.browser.%')))) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND `profile.properties.longitude` IS NOT NULL AND notEmpty(`profile.properties.longitude`) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-WITH profile AS (SELECT id as "profile.id", properties['longitude'] as `profile.properties.longitude`, properties as "profile.properties" FROM profiles FINAL WHERE project_id = {p1:String}) SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p2:String} as label_0, max(toFloat64OrNull(`profile.properties.longitude`)) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE arrayExists(x -> x LIKE '%Chrome%', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.browser.%')))) AND project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) AND `profile.properties.longitude` IS NOT NULL AND notEmpty(`profile.properties.longitude`) GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p7:String})) TO toStartOfDay(toDateTime({p8:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"secure-privacy","p4":"screen_view","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":"2026-07-06 00:00:00","p8":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — math property_sum on numeric column duration + has_profile true + wildcard properties.__query[*] isNotNull (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 245717/81916; wall V1/V2 = 27 ms / 31 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT 'screen_view' as label_0, sum(duration) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE profile_id != device_id AND arrayExists(x -> x != '' AND x IS NOT NULL, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.%')))) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND duration IS NOT NULL GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER () as total_count FROM (SELECT {p1:String} as label_0, sum(duration) as count, toStartOfDay(created_at) as date, uniqState(profile_id) as _uc_state FROM events e WHERE profile_id != device_id AND arrayExists(x -> x != '' AND x IS NOT NULL, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.%')))) AND project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) AND duration IS NOT NULL GROUP BY date) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"screen_view","p2":"secure-privacy","p3":"screen_view","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — wildcard properties.__query[*] breakdown + is filter + has_profile false (secure-privacy)--**statement** — IDENTICAL (row order differs — see note); rows V1/V2 = 191/191; rows_read V1/V2 = 245717/98299; wall V1/V2 = 29 ms / 44 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1) as total_count FROM (SELECT 'screen_view' as label_0, count(*) as count, toStartOfDay(created_at) as date, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.%'))) as label_1, uniqState(profile_id) as _uc_state FROM events e WHERE profile_id = device_id AND arrayExists(x -> x = '1' OR x = '2', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.%')))) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY date, label_1) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-12 23:59:59')) STEP toIntervalDay(1)--- V2-SELECT * EXCEPT (_uc_state), uniqMerge(_uc_state) OVER (PARTITION BY label_1) as total_count FROM (SELECT {p1:String} as label_0, count(*) as count, toStartOfDay(created_at) as date, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.%'))) as label_1, uniqState(profile_id) as _uc_state FROM events e WHERE profile_id = device_id AND arrayExists(x -> x = '1' OR x = '2', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(e.properties, '__query.%')))) AND project_id = {p2:String} AND e.name = {p3:String} AND created_at >= toDateTime({p4:String}) AND created_at <= toDateTime({p5:String}) GROUP BY date, label_1) ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p6:String})) TO toStartOfDay(toDateTime({p7:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"screen_view","p2":"secure-privacy","p3":"screen_view","p4":"2026-07-06 00:00:00","p5":"2026-07-12 23:59:59","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### chartSeriesQuery — all-cohorts breakdown + one_event_per_user (authc-project-a1)--**statement** — IDENTICAL ERROR (pre-existing V1 defect, both sides fail with the same ClickHouse error): `Unknown expression or function identifier `_all_cohorts.cohort_id` in scope WITH _all_cohorts AS (SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = 'authc-project-a1') SELECT '*' AS label_0, count(*) AS count, toStartOfDay(created_at) AS date, transform(_all_cohorts.cohort_id, ['cccccccc-0000-4000-8000-000000000001'], ['Auth contract cohort'], 'Unknown') AS label_1 FROM (SELECT * FROM events AS e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id WHERE (project_id = 'authc-project-a1') AND (created_at >= toDateTime('2026-07-06 00:00:00')) AND (created_at <= toDateTime('2026-07-08 23:59:59')) ORDER BY profile_id ASC, created_at DESC LIMIT 1 BY profile_id) AS subQuery GROUP BY date, label_1 ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1). Maybe you meant: ['_all_cohorts.profile_id'].`--```sql--- V1-WITH _all_cohorts AS ( SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = 'authc-project-a1' ) SELECT '*' as label_0, count(*) as count, toStartOfDay(created_at) as date, transform(_all_cohorts.cohort_id, ['cccccccc-0000-4000-8000-000000000001'], ['Auth contract cohort'], 'Unknown') as label_1 FROM ( SELECT DISTINCT ON (profile_id) * from events e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id WHERE project_id = 'authc-project-a1' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') ORDER BY profile_id, created_at DESC ) as subQuery GROUP BY date, label_1 ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime('2026-07-06 00:00:00')) TO toStartOfDay(toDateTime('2026-07-08 23:59:59')) STEP toIntervalDay(1)--- V2-WITH _all_cohorts AS ( SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = {p1:String} ) SELECT '*' as label_0, count(*) as count, toStartOfDay(created_at) as date, transform(_all_cohorts.cohort_id, {p2:Array(String)}, {p3:Array(String)}, {p4:String}) as label_1 FROM ( SELECT DISTINCT ON (profile_id) * from events e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id WHERE project_id = {p5:String} AND created_at >= toDateTime({p6:String}) AND created_at <= toDateTime({p7:String}) ORDER BY profile_id, created_at DESC ) as subQuery GROUP BY date, label_1 ORDER BY date ASC WITH FILL FROM toStartOfDay(toDateTime({p8:String})) TO toStartOfDay(toDateTime({p9:String})) STEP toIntervalDay(1)--- V2 params: {"p1":"authc-project-a1","p2":["cccccccc-0000-4000-8000-000000000001"],"p3":["Auth contract cohort"],"p4":"Unknown","p5":"authc-project-a1","p6":"2026-07-06 00:00:00","p7":"2026-07-08 23:59:59","p8":"2026-07-06 00:00:00","p9":"2026-07-08 23:59:59"}-```--## aggregateChartQuery--### aggregateChartQuery — basic (verdict, view_page, limit 10)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 7649340/7470531; wall V1/V2 = 101 ms / 69 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'view_page' as label_0, '2026-07-06 00:00:00' as date, count(*) as count FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY label_0 ORDER BY count DESC LIMIT 10--- V2-SELECT {p1:String} as label_0, {p2:String} as date, count(*) as count FROM events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY label_0 ORDER BY count DESC LIMIT {p7:UInt64}--- V2 params: {"p1":"view_page","p2":"2026-07-06 00:00:00","p3":"verdict","p4":"view_page","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":10}-```--### aggregateChartQuery — breakdown country + path, limit 25 (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 8 ms / 6 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'view_page' as label_0, '2026-07-06 00:00:00' as date, country as label_1, path as label_2, count(*) as count FROM events e WHERE project_id = 'secure-privacy' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT 25--- V2-SELECT {p1:String} as label_0, {p2:String} as date, country as label_1, path as label_2, count(*) as count FROM events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT {p7:UInt64}--- V2 params: {"p1":"view_page","p2":"2026-07-06 00:00:00","p3":"secure-privacy","p4":"view_page","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":25}-```--### aggregateChartQuery — wildcard event + segment user + breakdown referrerName alias, no limit (verdict)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1185604/998587; wall V1/V2 = 36 ms / 33 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT '*' as label_0, '2026-07-06 00:00:00' as date, referrer_name as label_1, countDistinct(profile_id) as count FROM events e WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY label_1, label_0 ORDER BY count DESC--- V2-SELECT '*' as label_0, {p1:String} as date, referrer_name as label_1, countDistinct(profile_id) as count FROM events e WHERE project_id = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at <= toDateTime({p4:String}) GROUP BY label_1, label_0 ORDER BY count DESC--- V2 params: {"p1":"2026-07-06 00:00:00","p2":"verdict","p3":"2026-07-06 00:00:00","p4":"2026-07-08 23:59:59"}-```--### aggregateChartQuery — segment session + filter contains (verdict)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 1185604/0; wall V1/V2 = 21 ms / 7 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'view_page' as label_0, '2026-07-06 00:00:00' as date, countDistinct(session_id) as count FROM events e WHERE (path LIKE '%/%') AND project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY label_0 ORDER BY count DESC LIMIT 5--- V2-SELECT {p1:String} as label_0, {p2:String} as date, countDistinct(session_id) as count FROM events e WHERE (path LIKE '%/%') AND project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY label_0 ORDER BY count DESC LIMIT {p7:UInt64}--- V2 params: {"p1":"view_page","p2":"2026-07-06 00:00:00","p3":"verdict","p4":"view_page","p5":"2026-07-06 00:00:00","p6":"2026-07-08 23:59:59","p7":5}-```--### aggregateChartQuery — segment user_average + breakdown properties.__title (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 245717/98299; wall V1/V2 = 26 ms / 47 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'screen_view' as label_0, '2026-07-06 00:00:00' as date, e.properties['__title'] as label_1, COUNT(*)::float / COUNT(DISTINCT profile_id)::float as count FROM events e WHERE project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY label_1, label_0 ORDER BY count DESC LIMIT 20--- V2-SELECT {p1:String} as label_0, {p2:String} as date, e.properties['__title'] as label_1, COUNT(*)::float / COUNT(DISTINCT profile_id)::float as count FROM events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY label_1, label_0 ORDER BY count DESC LIMIT {p7:UInt64}--- V2 params: {"p1":"screen_view","p2":"2026-07-06 00:00:00","p3":"secure-privacy","p4":"screen_view","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59","p7":20}-```--### aggregateChartQuery — segment group + breakdown group.name + group.properties.country + filter group.properties.employees gt (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 109848/109848; wall V1/V2 = 29 ms / 36 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT 'screen_view' as label_0, '2026-07-06 00:00:00' as date, _g.name as label_1, _g.properties['country'] as label_2, countDistinct(_group_id) as count FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE (_g.properties['employees'] != '' AND _g.properties['employees'] IS NOT NULL) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT 20--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT {p2:String} as label_0, {p3:String} as date, _g.name as label_1, _g.properties['country'] as label_2, countDistinct(_group_id) as count FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE (_g.properties['employees'] != '' AND _g.properties['employees'] IS NOT NULL) AND project_id = {p4:String} AND e.name = {p5:String} AND created_at >= toDateTime({p6:String}) AND created_at <= toDateTime({p7:String}) GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT {p8:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"secure-privacy","p5":"screen_view","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":20}-```--### aggregateChartQuery — profile breakdown profile.properties.os + profile.last_name + filter profile.email endsWith (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 16/16; rows_read V1/V2 = 409275/409275; wall V1/V2 = 133 ms / 88 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", email as "profile.email", properties['os'] as `profile.properties.os`, last_name as "profile.last_name" FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT 'screen_view' as label_0, '2026-07-06 00:00:00' as date, `profile.properties.os` as label_1, profile.last_name as label_2, count(*) as count FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT 20--- V2-WITH profile AS (SELECT id as "profile.id", email as "profile.email", properties['os'] as `profile.properties.os`, last_name as "profile.last_name" FROM profiles FINAL WHERE project_id = {p1:String}) SELECT {p2:String} as label_0, {p3:String} as date, `profile.properties.os` as label_1, profile.last_name as label_2, count(*) as count FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE project_id = {p4:String} AND e.name = {p5:String} AND created_at >= toDateTime({p6:String}) AND created_at <= toDateTime({p7:String}) GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT {p8:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"secure-privacy","p5":"screen_view","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":20}-```--### aggregateChartQuery — math property_sum on properties.value (project-resolved) + profile wildcard breakdown (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 556693/0; wall V1/V2 = 84 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH profile AS (SELECT id as "profile.id", properties as "profile.properties" FROM profiles FINAL WHERE project_id = 'secure-privacy') SELECT 'screen_view' as label_0, '2026-07-06 00:00:00' as date, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.browser.%'))) as label_1, sum(toFloat64OrNull(e.properties['value'])) as count FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND e.properties['value'] IS NOT NULL AND notEmpty(e.properties['value']) GROUP BY label_1, label_0 ORDER BY count DESC LIMIT 20--- V2-WITH profile AS (SELECT id as "profile.id", properties as "profile.properties" FROM profiles FINAL WHERE project_id = {p1:String}) SELECT {p2:String} as label_0, {p3:String} as date, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(profile.properties, 'profile.properties.browser.%'))) as label_1, sum(toFloat64OrNull(e.properties['value'])) as count FROM events e LEFT ANY JOIN profile ON profile.id = profile_id WHERE project_id = {p4:String} AND e.name = {p5:String} AND created_at >= toDateTime({p6:String}) AND created_at <= toDateTime({p7:String}) AND e.properties['value'] IS NOT NULL AND notEmpty(e.properties['value']) GROUP BY label_1, label_0 ORDER BY count DESC LIMIT {p8:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"secure-privacy","p5":"screen_view","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59","p8":20}-```--### aggregateChartQuery — math property_average on duration (numeric column) + typed date filter on created_at (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 245717/98291; wall V1/V2 = 20 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'screen_view' as label_0, '2026-07-06 00:00:00' as date, avg(duration) as count FROM events e WHERE (toDate(parseDateTimeBestEffortOrNull(toString(created_at))) >= toDate(parseDateTimeBestEffortOrNull(toString('2026-07-08')))) AND project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND duration IS NOT NULL GROUP BY label_0 ORDER BY count DESC--- V2-SELECT {p1:String} as label_0, {p2:String} as date, avg(duration) as count FROM events e WHERE (toDate(parseDateTimeBestEffortOrNull(toString(created_at))) >= toDate(parseDateTimeBestEffortOrNull(toString('2026-07-08')))) AND project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) AND duration IS NOT NULL GROUP BY label_0 ORDER BY count DESC--- V2 params: {"p1":"screen_view","p2":"2026-07-06 00:00:00","p3":"secure-privacy","p4":"screen_view","p5":"2026-07-06 00:00:00","p6":"2026-07-12 23:59:59"}-```--### aggregateChartQuery — math property_max on group.properties.employees (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 109848/109848; wall V1/V2 = 28 ms / 59 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') SELECT 'screen_view' as label_0, '2026-07-06 00:00:00' as date, max(toFloat64OrNull(_g.properties['employees'])) as count FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE project_id = 'secure-privacy' AND e.name = 'screen_view' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-12 23:59:59') AND _g.properties['employees'] IS NOT NULL AND notEmpty(_g.properties['employees']) GROUP BY label_0 ORDER BY count DESC--- V2-WITH _g AS (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) SELECT {p2:String} as label_0, {p3:String} as date, max(toFloat64OrNull(_g.properties['employees'])) as count FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN _g ON _g.id = _group_id WHERE project_id = {p4:String} AND e.name = {p5:String} AND created_at >= toDateTime({p6:String}) AND created_at <= toDateTime({p7:String}) AND _g.properties['employees'] IS NOT NULL AND notEmpty(_g.properties['employees']) GROUP BY label_0 ORDER BY count DESC--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":"2026-07-06 00:00:00","p4":"secure-privacy","p5":"screen_view","p6":"2026-07-06 00:00:00","p7":"2026-07-12 23:59:59"}-```--### aggregateChartQuery — one_event_per_user + breakdown path (verdict) — V1 re-emits WHERE--**statement** — IDENTICAL ERROR (pre-existing V1 defect, both sides fail with the same ClickHouse error): `Unknown expression or function identifier `e.name` in scope SELECT 'view_page' AS label_0, '2026-07-06 00:00:00' AS date, path AS label_1, count(*) AS count FROM (SELECT * FROM events AS e WHERE (project_id = 'verdict') AND (e.name = 'view_page') AND (created_at >= toDateTime('2026-07-06 00:00:00')) AND (created_at <= toDateTime('2026-07-08 23:59:59')) ORDER BY profile_id ASC, created_at DESC LIMIT 1 BY profile_id) AS subQuery WHERE (project_id = 'verdict') AND (e.name = 'view_page') AND (created_at >= toDateTime('2026-07-06 00:00:00')) AND (created_at <= toDateTime('2026-07-08 23:59:59')) GROUP BY label_1, label_0.`--```sql--- V1-SELECT 'view_page' as label_0, '2026-07-06 00:00:00' as date, path as label_1, count(*) as count FROM ( SELECT DISTINCT ON (profile_id) * from events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') ORDER BY profile_id, created_at DESC ) as subQuery WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY label_1, label_0--- V2-SELECT {p1:String} as label_0, {p2:String} as date, path as label_1, count(*) as count FROM ( SELECT DISTINCT ON (profile_id) * from events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) ORDER BY profile_id, created_at DESC ) as subQuery WHERE project_id = {p7:String} AND e.name = {p8:String} AND created_at >= toDateTime({p9:String}) AND created_at <= toDateTime({p10:String}) GROUP BY label_1, label_0--- V2 params: {"p1":"view_page","p2":"2026-07-06 00:00:00","p3":"verdict","p4":"view_page","p5":"2026-07-06 00:00:00","p6":"2026-07-08 23:59:59","p7":"verdict","p8":"view_page","p9":"2026-07-06 00:00:00","p10":"2026-07-08 23:59:59"}-```--### aggregateChartQuery — one_event_per_user, wildcard event, no breakdown (verdict)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 841552/622225; wall V1/V2 = 110 ms / 73 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT '*' as label_0, '2026-07-06 00:00:00' as date, count(*) as count FROM ( SELECT DISTINCT ON (profile_id) * from events e WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-07 23:59:59') ORDER BY profile_id, created_at DESC ) as subQuery WHERE project_id = 'verdict' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-07 23:59:59') GROUP BY label_0--- V2-SELECT '*' as label_0, {p1:String} as date, count(*) as count FROM ( SELECT DISTINCT ON (profile_id) * from events e WHERE project_id = {p2:String} AND created_at >= toDateTime({p3:String}) AND created_at <= toDateTime({p4:String}) ORDER BY profile_id, created_at DESC ) as subQuery WHERE project_id = {p5:String} AND created_at >= toDateTime({p6:String}) AND created_at <= toDateTime({p7:String}) GROUP BY label_0--- V2 params: {"p1":"2026-07-06 00:00:00","p2":"verdict","p3":"2026-07-06 00:00:00","p4":"2026-07-07 23:59:59","p5":"verdict","p6":"2026-07-06 00:00:00","p7":"2026-07-07 23:59:59"}-```--### aggregateChartQuery — all-cohorts breakdown with named cohort + cohort:<id> breakdown (authc-project-a1)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 11 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH _all_cohorts AS ( SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = 'authc-project-a1' ), `cohort-cccccccc-0000-4000-8000-000000000001` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cccccccc-0000-4000-8000-000000000001' AND project_id = 'authc-project-a1' ) SELECT '*' as label_0, '2026-07-06 00:00:00' as date, transform(_all_cohorts.cohort_id, ['cccccccc-0000-4000-8000-000000000001'], ['Auth contract cohort'], 'Unknown') as label_1, if(notEmpty(cohort_cccccccc_0000_4000_8000_000000000001.profile_id), 'Auth contract cohort', 'Not Auth contract cohort') as label_2, count(*) as count FROM events e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id LEFT ANY JOIN `cohort-cccccccc-0000-4000-8000-000000000001` AS cohort_cccccccc_0000_4000_8000_000000000001 ON cohort_cccccccc_0000_4000_8000_000000000001.profile_id = e.profile_id WHERE project_id = 'authc-project-a1' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT 10--- V2-WITH _all_cohorts AS ( SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = {p1:String} ), `cohort-cccccccc-0000-4000-8000-000000000001` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String} ) SELECT '*' as label_0, {p4:String} as date, transform(_all_cohorts.cohort_id, {p5:Array(String)}, {p6:Array(String)}, {p7:String}) as label_1, if(notEmpty(cohort_cccccccc_0000_4000_8000_000000000001.profile_id), {p8:String}, {p9:String}) as label_2, count(*) as count FROM events e INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id LEFT ANY JOIN `cohort-cccccccc-0000-4000-8000-000000000001` AS cohort_cccccccc_0000_4000_8000_000000000001 ON cohort_cccccccc_0000_4000_8000_000000000001.profile_id = e.profile_id WHERE project_id = {p10:String} AND created_at >= toDateTime({p11:String}) AND created_at <= toDateTime({p12:String}) GROUP BY label_1, label_2, label_0 ORDER BY count DESC LIMIT {p13:UInt64}--- V2 params: {"p1":"authc-project-a1","p2":"cccccccc-0000-4000-8000-000000000001","p3":"authc-project-a1","p4":"2026-07-06 00:00:00","p5":["cccccccc-0000-4000-8000-000000000001"],"p6":["Auth contract cohort"],"p7":"Unknown","p8":"Auth contract cohort","p9":"Not Auth contract cohort","p10":"authc-project-a1","p11":"2026-07-06 00:00:00","p12":"2026-07-08 23:59:59","p13":10}-```--### aggregateChartQuery — cohort:<id> breakdown unknown cohort + inCohort filter (verdict)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 11 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-WITH `cohort-44444444-4444-4444-8444-444444444444` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = '44444444-4444-4444-8444-444444444444' AND project_id = 'verdict' ) SELECT 'view_page' as label_0, '2026-07-06 00:00:00' as date, if(notEmpty(cohort_44444444_4444_4444_8444_444444444444.profile_id), 'In Cohort', 'Not In Cohort') as label_1, count(*) as count FROM events e LEFT ANY JOIN `cohort-44444444-4444-4444-8444-444444444444` AS cohort_44444444_4444_4444_8444_444444444444 ON cohort_44444444_4444_4444_8444_444444444444.profile_id = e.profile_id WHERE e.profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('44444444-4444-4444-8444-444444444444') AND project_id = 'verdict') AND project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY label_1, label_0 ORDER BY count DESC LIMIT 10--- V2-WITH `cohort-44444444-4444-4444-8444-444444444444` AS ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p1:String} AND project_id = {p2:String} ) SELECT {p3:String} as label_0, {p4:String} as date, if(notEmpty(cohort_44444444_4444_4444_8444_444444444444.profile_id), {p5:String}, {p6:String}) as label_1, count(*) as count FROM events e LEFT ANY JOIN `cohort-44444444-4444-4444-8444-444444444444` AS cohort_44444444_4444_4444_8444_444444444444 ON cohort_44444444_4444_4444_8444_444444444444.profile_id = e.profile_id WHERE e.profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('44444444-4444-4444-8444-444444444444') AND project_id = 'verdict') AND project_id = {p7:String} AND e.name = {p8:String} AND created_at >= toDateTime({p9:String}) AND created_at <= toDateTime({p10:String}) GROUP BY label_1, label_0 ORDER BY count DESC LIMIT {p11:UInt64}--- V2 params: {"p1":"44444444-4444-4444-8444-444444444444","p2":"verdict","p3":"view_page","p4":"2026-07-06 00:00:00","p5":"In Cohort","p6":"Not In Cohort","p7":"verdict","p8":"view_page","p9":"2026-07-06 00:00:00","p10":"2026-07-08 23:59:59","p11":10}-```--### aggregateChartQuery — all-cohorts breakdown dropped (verdict, no cohorts) + unknown field dropped--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 1185604/982645; wall V1/V2 = 36 ms / 32 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT 'view_page' as label_0, '2026-07-06 00:00:00' as date, if(profile_id != device_id, 'true', 'false') as label_1, count(*) as count FROM events e WHERE project_id = 'verdict' AND e.name = 'view_page' AND created_at >= toDateTime('2026-07-06 00:00:00') AND created_at <= toDateTime('2026-07-08 23:59:59') GROUP BY label_1, label_0 ORDER BY count DESC LIMIT 10--- V2-SELECT {p1:String} as label_0, {p2:String} as date, if(profile_id != device_id, 'true', 'false') as label_1, count(*) as count FROM events e WHERE project_id = {p3:String} AND e.name = {p4:String} AND created_at >= toDateTime({p5:String}) AND created_at <= toDateTime({p6:String}) GROUP BY label_1, label_0 ORDER BY count DESC LIMIT {p7:UInt64}--- V2 params: {"p1":"view_page","p2":"2026-07-06 00:00:00","p3":"verdict","p4":"view_page","p5":"2026-07-06 00:00:00","p6":"2026-07-08 23:59:59","p7":10}-```--## Router queries (projectCard, events, properties, values, getProfiles)--### projectCardChartQuery — projectCard chart (verdict, UTC)--**statement** — IDENTICAL; rows V1/V2 = 92/92; rows_read V1/V2 = 1273247/1273247; wall V1/V2 = 99 ms / 62 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT uniqHLL12(profile_id) as value, toStartOfDay(created_at) as date, sum(revenue * sign) as revenue FROM sessions WHERE project_id = 'verdict' AND created_at >= now() - interval '3 month' GROUP BY date ORDER BY date ASC WITH FILL FROM toStartOfDay(now() - interval '3 month') TO toStartOfDay(now()) STEP INTERVAL 1 day SETTINGS session_timezone = 'UTC'--- V2-SELECT uniqHLL12(profile_id) as value, toStartOfDay(created_at) as date, sum(revenue * sign) as revenue FROM sessions WHERE project_id = {p1:String} AND created_at >= now() - interval '3 month' GROUP BY date ORDER BY date ASC WITH FILL FROM toStartOfDay(now() - interval '3 month') TO toStartOfDay(now()) STEP INTERVAL 1 day--- V2 params: {"p1":"verdict"}-```--### projectCardMetricsQuery — projectCard metrics (verdict, UTC)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1273247/1273247; wall V1/V2 = 67 ms / 60 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT uniqHLL12(if(created_at >= (now() - toIntervalMonth(3)), profile_id, null)) AS months_3, uniqHLL12(if(created_at >= (now() - toIntervalMonth(6)) AND created_at < (now() - toIntervalMonth(3)), profile_id, null)) AS months_3_prev, uniqHLL12(if(created_at >= (now() - toIntervalMonth(1)), profile_id, null)) AS month, uniqHLL12(if(created_at >= (now() - toIntervalDay(1)), profile_id, null)) AS day, uniqHLL12(if(created_at >= (now() - toIntervalDay(2)) AND created_at < (now() - toIntervalDay(1)), profile_id, null)) AS day_prev, sum(revenue * sign) as revenue FROM sessions WHERE project_id = 'verdict' AND created_at >= (now() - toIntervalMonth(6))--- V2-SELECT uniqHLL12(if(created_at >= (now() - toIntervalMonth(3)), profile_id, null)) AS months_3, uniqHLL12(if(created_at >= (now() - toIntervalMonth(6)) AND created_at < (now() - toIntervalMonth(3)), profile_id, null)) AS months_3_prev, uniqHLL12(if(created_at >= (now() - toIntervalMonth(1)), profile_id, null)) AS month, uniqHLL12(if(created_at >= (now() - toIntervalDay(1)), profile_id, null)) AS day, uniqHLL12(if(created_at >= (now() - toIntervalDay(2)) AND created_at < (now() - toIntervalDay(1)), profile_id, null)) AS day_prev, sum(revenue * sign) as revenue FROM sessions WHERE project_id = {p1:String} AND created_at >= (now() - toIntervalMonth(6))--- V2 params: {"p1":"verdict"}-```--### projectCardChartQuery — projectCard chart (bayse, America/New_York)--**statement** — IDENTICAL; rows V1/V2 = 92/92; rows_read V1/V2 = 835382/835382; wall V1/V2 = 46 ms / 65 ms; clickhouse_settings: session_timezone=America/New_York (both).--```sql--- V1-SELECT uniqHLL12(profile_id) as value, toStartOfDay(created_at) as date, sum(revenue * sign) as revenue FROM sessions WHERE project_id = 'bayse' AND created_at >= now() - interval '3 month' GROUP BY date ORDER BY date ASC WITH FILL FROM toStartOfDay(now() - interval '3 month') TO toStartOfDay(now()) STEP INTERVAL 1 day SETTINGS session_timezone = 'America/New_York'--- V2-SELECT uniqHLL12(profile_id) as value, toStartOfDay(created_at) as date, sum(revenue * sign) as revenue FROM sessions WHERE project_id = {p1:String} AND created_at >= now() - interval '3 month' GROUP BY date ORDER BY date ASC WITH FILL FROM toStartOfDay(now() - interval '3 month') TO toStartOfDay(now()) STEP INTERVAL 1 day--- V2 params: {"p1":"bayse"}-```--### projectCardMetricsQuery — projectCard metrics (bayse, America/New_York)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 835382/835382; wall V1/V2 = 43 ms / 68 ms; clickhouse_settings: session_timezone=America/New_York (both).--```sql--- V1-SELECT uniqHLL12(if(created_at >= (now() - toIntervalMonth(3)), profile_id, null)) AS months_3, uniqHLL12(if(created_at >= (now() - toIntervalMonth(6)) AND created_at < (now() - toIntervalMonth(3)), profile_id, null)) AS months_3_prev, uniqHLL12(if(created_at >= (now() - toIntervalMonth(1)), profile_id, null)) AS month, uniqHLL12(if(created_at >= (now() - toIntervalDay(1)), profile_id, null)) AS day, uniqHLL12(if(created_at >= (now() - toIntervalDay(2)) AND created_at < (now() - toIntervalDay(1)), profile_id, null)) AS day_prev, sum(revenue * sign) as revenue FROM sessions WHERE project_id = 'bayse' AND created_at >= (now() - toIntervalMonth(6))--- V2-SELECT uniqHLL12(if(created_at >= (now() - toIntervalMonth(3)), profile_id, null)) AS months_3, uniqHLL12(if(created_at >= (now() - toIntervalMonth(6)) AND created_at < (now() - toIntervalMonth(3)), profile_id, null)) AS months_3_prev, uniqHLL12(if(created_at >= (now() - toIntervalMonth(1)), profile_id, null)) AS month, uniqHLL12(if(created_at >= (now() - toIntervalDay(1)), profile_id, null)) AS day, uniqHLL12(if(created_at >= (now() - toIntervalDay(2)) AND created_at < (now() - toIntervalDay(1)), profile_id, null)) AS day_prev, sum(revenue * sign) as revenue FROM sessions WHERE project_id = {p1:String} AND created_at >= (now() - toIntervalMonth(6))--- V2 params: {"p1":"bayse"}-```--### eventNamesWithCountQuery — events (verdict)--**Amended 2026-09-27 (ISSUES.md M1): V2 now DIVERGES from V1 deliberately.**--The parity recorded below was real — both statements returned the same numbers because both-were wrong in the same way. `count(name)` counts rows of `distinct_event_names_mv`, and that-MV holds one row per name per insert part, so the report builder's event picker showed the-number of insert parts rather than the number of events. On the `large` seed acme-web showed-**52** for `screen_view`, which has **974,387** occurrences.--`sum(event_count)` reads the total the MV already stores. Verified against the seeded data:-it equals `SELECT count() FROM events GROUP BY name` exactly for every name (974387 / 659361 /-659361 / 95582 / 46334 / 34533 across the top six on acme-web).--```sql--- V1 (and V2 before this amendment) — counts MV rows, not events-SELECT name, count(name) as count FROM distinct_event_names_mv WHERE project_id = 'verdict' GROUP BY name ORDER BY count DESC, name ASC--- V2 now-SELECT name, sum(event_count) as count FROM distinct_event_names_mv WHERE project_id = {p1:String} GROUP BY name ORDER BY count DESC, name ASC--- V2 params: {"p1":"verdict"}-```--Original record, kept for the paper trail:--**statement** — IDENTICAL; rows V1/V2 = 85/85; rows_read V1/V2 = 221184/221184; wall V1/V2 = 11 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both).--### eventPropertyKeysQuery — properties (secure-privacy, event=undefined)--**statement** — IDENTICAL; rows V1/V2 = 174/174; rows_read V1/V2 = 128264/128264; wall V1/V2 = 18 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct property_key, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = 'secure-privacy' GROUP BY property_key ORDER BY created_at DESC, property_key ASC LIMIT 50000--- V2-SELECT distinct property_key, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = {p1:String} GROUP BY property_key ORDER BY created_at DESC, property_key ASC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":50000}-```--### eventPropertyKeysQuery — properties (secure-privacy, event=*)--**statement** — IDENTICAL; rows V1/V2 = 174/174; rows_read V1/V2 = 128264/128264; wall V1/V2 = 11 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct property_key, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = 'secure-privacy' GROUP BY property_key ORDER BY created_at DESC, property_key ASC LIMIT 50000--- V2-SELECT distinct property_key, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = {p1:String} GROUP BY property_key ORDER BY created_at DESC, property_key ASC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":50000}-```--### eventPropertyKeysQuery — properties (secure-privacy, event=screen_view)--**statement** — IDENTICAL; rows V1/V2 = 156/156; rows_read V1/V2 = 128264/128264; wall V1/V2 = 13 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct property_key, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = 'secure-privacy' AND name = 'screen_view' GROUP BY property_key ORDER BY created_at DESC, property_key ASC LIMIT 50000--- V2-SELECT distinct property_key, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = {p1:String} AND name = {p2:String} GROUP BY property_key ORDER BY created_at DESC, property_key ASC LIMIT {p3:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":50000}-```--### eventPropertyValuesQuery — values properties.__title (secure-privacy, event='*')--**statement** — IDENTICAL; rows V1/V2 = 500/500; rows_read V1/V2 = 270336/172032; wall V1/V2 = 30 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct property_value, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = 'secure-privacy' AND property_key = '__title' GROUP BY property_value ORDER BY created_at DESC, property_value ASC LIMIT 500--- V2-SELECT distinct property_value, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = {p1:String} AND property_key = {p2:String} GROUP BY property_value ORDER BY created_at DESC, property_value ASC LIMIT {p3:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"__title","p3":500}-```--### eventPropertyValuesQuery — values properties.__query.gclid (secure-privacy, event='screen_view')--**statement** — IDENTICAL; rows V1/V2 = 500/500; rows_read V1/V2 = 131072/114688; wall V1/V2 = 16 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct property_value, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = 'secure-privacy' AND property_key = '__query.gclid' AND name = 'screen_view' GROUP BY property_value ORDER BY created_at DESC, property_value ASC LIMIT 500--- V2-SELECT distinct property_value, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = {p1:String} AND property_key = {p2:String} AND name = {p3:String} GROUP BY property_value ORDER BY created_at DESC, property_value ASC LIMIT {p4:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"__query.gclid","p3":"screen_view","p4":500}-```--### eventPropertyValuesQuery — values properties.value (secure-privacy, event='')--**statement** — IDENTICAL; rows V1/V2 = 500/500; rows_read V1/V2 = 270336/221184; wall V1/V2 = 14 ms / 12 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct property_value, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = 'secure-privacy' AND property_key = 'value' GROUP BY property_value ORDER BY created_at DESC, property_value ASC LIMIT 500--- V2-SELECT distinct property_value, max(created_at) as created_at FROM event_property_values_mv WHERE project_id = {p1:String} AND property_key = {p2:String} GROUP BY property_value ORDER BY created_at DESC, property_value ASC LIMIT {p3:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"value","p3":500}-```--### profilePropertyValuesQuery — values profile.email (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 1251/1251; rows_read V1/V2 = 310976/310976; wall V1/V2 = 32 ms / 33 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct email as values FROM profiles FINAL WHERE project_id = 'secure-privacy' AND email != '' AND email IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct email as values FROM profiles FINAL WHERE project_id = {p1:String} AND email != '' AND email IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### profilePropertyValuesQuery — values profile.properties.os (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 12/12; rows_read V1/V2 = 310976/310976; wall V1/V2 = 82 ms / 71 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct properties['os'] as values FROM profiles FINAL WHERE project_id = 'secure-privacy' AND properties['os'] != '' AND properties['os'] IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct properties['os'] as values FROM profiles FINAL WHERE project_id = {p1:String} AND properties['os'] != '' AND properties['os'] IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### profilePropertyValuesQuery — values profile.properties.it's"odd (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 310976/310976; wall V1/V2 = 65 ms / 67 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct properties['it\'s\"odd'] as values FROM profiles FINAL WHERE project_id = 'secure-privacy' AND properties['it\'s\"odd'] != '' AND properties['it\'s\"odd'] IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct properties['it\'s\"odd'] as values FROM profiles FINAL WHERE project_id = {p1:String} AND properties['it\'s\"odd'] != '' AND properties['it\'s\"odd'] IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### profilePropertyValuesQuery — values profile.unknown (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 100000/100000; rows_read V1/V2 = 310976/310976; wall V1/V2 = 96 ms / 116 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct id as values FROM profiles FINAL WHERE project_id = 'secure-privacy' AND id != '' AND id IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct id as values FROM profiles FINAL WHERE project_id = {p1:String} AND id != '' AND id IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### groupPropertyValuesQuery — values group.name (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 345/345; rows_read V1/V2 = 3359/3359; wall V1/V2 = 8 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct name as values FROM groups FINAL WHERE project_id = 'secure-privacy' AND deleted = 0 AND name != '' AND name IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct name as values FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0 AND name != '' AND name IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### groupPropertyValuesQuery — values group.type (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3359/3359; wall V1/V2 = 6 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct type as values FROM groups FINAL WHERE project_id = 'secure-privacy' AND deleted = 0 AND type != '' AND type IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct type as values FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0 AND type != '' AND type IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### groupPropertyValuesQuery — values group.properties.employees (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 3359/3359; wall V1/V2 = 9 ms / 9 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct properties['employees'] as values FROM groups FINAL WHERE project_id = 'secure-privacy' AND deleted = 0 AND properties['employees'] != '' AND properties['employees'] IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct properties['employees'] as values FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0 AND properties['employees'] != '' AND properties['employees'] IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### groupPropertyValuesQuery — values group.id (secure-privacy)--**statement** — IDENTICAL; rows V1/V2 = 347/347; rows_read V1/V2 = 3359/3359; wall V1/V2 = 7 ms / 7 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct id as values FROM groups FINAL WHERE project_id = 'secure-privacy' AND deleted = 0 AND id != '' AND id IS NOT NULL ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct id as values FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0 AND id != '' AND id IS NOT NULL ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### eventFieldValuesQuery — values country (secure-privacy, event='*')--**statement** — IDENTICAL; rows V1/V2 = 185/185; rows_read V1/V2 = 606120/606120; wall V1/V2 = 29 ms / 20 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct country as values FROM events WHERE project_id = 'secure-privacy' AND created_at > (now() - INTERVAL 6 MONTH) ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct country as values FROM events WHERE project_id = {p1:String} AND created_at > (now() - INTERVAL 6 MONTH) ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### eventFieldValuesQuery — values referrerName (secure-privacy, event='screen_view')--**statement** — IDENTICAL; rows V1/V2 = 826/826; rows_read V1/V2 = 606120/606120; wall V1/V2 = 29 ms / 25 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct referrer_name as values FROM events WHERE project_id = 'secure-privacy' AND created_at > (now() - INTERVAL 6 MONTH) AND name = 'screen_view' ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct referrer_name as values FROM events WHERE project_id = {p1:String} AND created_at > (now() - INTERVAL 6 MONTH) AND name = {p2:String} ORDER BY created_at DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":100000}-```--### eventFieldValuesQuery — values utm_source (secure-privacy, event='screen_view')--**statement** — IDENTICAL; rows V1/V2 = 89/89; rows_read V1/V2 = 606120/606120; wall V1/V2 = 59 ms / 53 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct properties['__query.utm_source'] as values FROM events WHERE project_id = 'secure-privacy' AND created_at > (now() - INTERVAL 6 MONTH) AND name = 'screen_view' ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct properties['__query.utm_source'] as values FROM events WHERE project_id = {p1:String} AND created_at > (now() - INTERVAL 6 MONTH) AND name = {p2:String} ORDER BY created_at DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":100000}-```--### eventFieldValuesQuery — values properties.__query[*] (secure-privacy, event='*')--**statement** — IDENTICAL; rows V1/V2 = 6532/6532; rows_read V1/V2 = 606120/606120; wall V1/V2 = 79 ms / 86 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%'))) as values FROM events WHERE project_id = 'secure-privacy' AND created_at > (now() - INTERVAL 6 MONTH) ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%'))) as values FROM events WHERE project_id = {p1:String} AND created_at > (now() - INTERVAL 6 MONTH) ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"secure-privacy","p2":100000}-```--### eventFieldValuesQuery — values path (secure-privacy, event='screen_view')--**statement** — IDENTICAL; rows V1/V2 = 6454/6454; rows_read V1/V2 = 606120/606120; wall V1/V2 = 49 ms / 41 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT distinct path as values FROM events WHERE project_id = 'secure-privacy' AND created_at > (now() - INTERVAL 6 MONTH) AND name = 'screen_view' ORDER BY created_at DESC LIMIT 100000--- V2-SELECT distinct path as values FROM events WHERE project_id = {p1:String} AND created_at > (now() - INTERVAL 6 MONTH) AND name = {p2:String} ORDER BY created_at DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"screen_view","p3":100000}-```--**Amended by M31-001 (2026-09-16): the six `chartBucketProfilesQuery` statements below are no longer-V1-identical, by decision.** V1's bucket statement has no `LIMIT`, so one chart data point hands the-drill-down modal every distinct profile in the bucket — 31,447 ids on `chatpaper`, which the modal's-virtual list never shows and which the `profiles FINAL` follow-up then pays for in 158 batches-(`docs/ANALYTICS_PERFORMANCE.md` §6.7, Group C fix 6; approved by Carl on 2026-09-15). Every `-- V2`-statement below now ends in `LIMIT {pN:UInt64}`, bound to `BUCKET_PROFILES_LIMIT = 1000` — the same-cap `getFunnelStepProfiles` already applies to the same modal. The `-- V1` statements are left exactly-as V1 wrote them, so the two columns differ in that one clause by design.--Re-measured against the local prod copy on **2026-09-16**, `use_query_condition_cache=0`,-`session_timezone=UTC`, `default_format=Null`, `wait_end_of_query=1`; `result_rows`/`read_rows`/-`elapsed_ns` read off `X-ClickHouse-Summary`. Old = the same rendered statement with the `LIMIT`-clause stripped. Wall clock is the **range over the runs stated per block** — this is a 4-core box-and its run-to-run spread is wider than most of the deltas here, so only ranges are reported.--Six statement cases, 2 runs each side:--| case | old rows / read / ms | new rows / read / ms |-|---|---|---|-| day bucket, screen_view, no breakdowns | 4,092 / 212,951 / 14.8-16.7 | **1,000** / 188,385-196,575 / 14.4-15.6 |-| hour bucket, wildcard event, country filter | 181 / 212,951 / 10.8-12.1 | 181 / 212,951 / 12.0-12.7 |-| minute bucket | 8 / 212,951 / 13.7-15.7 | 8 / 212,951 / 10.2-15.8 |-| week bucket + breakdowns country/path | 0 / 204,759 / 16.1-17.5 | 0 / 204,759 / 16.9-19.1 |-| month bucket + profile filter/breakdown join | 0 / 573,041 / 101.5-136.6 | 0 / 573,041 / 102.4-105.7 |-| day bucket + group filter/breakdown join | 0 / 216,310 / 23.1-26.9 | 0 / 216,310 / 19.9-23.3 |--§6.7's worst case — `chatpaper`, `screen_view`, day bucket `2026-08-20` (the bucket that yields-§6.7's 31,447) — 3 runs each:--| variant | rows / read / ms |-|---|---|-| old, no `LIMIT` | 31,447 / 573,385 / 35.6-42.9 |-| new, `LIMIT 1000` | **1,000** / 24,573-73,724 / 10.7-12.6 |-| `ORDER BY profile_id LIMIT 1000` (not taken) | 1,000 / 573,385 / 46.6-48.4 |--**Five of the six statement cases still return the same rows as V1** — they yield fewer than 1,000-ids, so the cap never bites, and their wall-clock columns overlap in both directions: the `LIMIT` is-free, not faster, where it does not truncate. Only the day bucket truncates among the six; the-`chatpaper` case is the one where it pays.--Where the cap does bite, the capped result is a **strict subset** of the old one:-`profile_id NOT IN (old set)` counted **0** on both truncating buckets, each returned 1,000 rows-holding 1,000 distinct ids (`DISTINCT` is applied before `LIMIT`). ClickHouse stops reading once the-cap is met, so `chatpaper` falls from 573,385 rows read to 24,573-73,724 — that figure is a range,-not a constant, because where the readers stop varies per run.--**Which 1,000 is not deterministic, by inheritance.** The statement has no `ORDER BY` — neither does-`getFunnelStepProfiles`' bounded equivalent — so the subset depends on which parts the reader-finishes first. Measured on `chatpaper`'s bucket: 7 runs at default settings produced 2 distinct-result sets (`cityHash64(arraySort(groupArray(profile_id)))`), and `max_threads=1` produced a third,-stable across its own 3 runs. Making it stable costs the whole read saving: `ORDER BY profile_id-LIMIT 1000` reads the full pre-fix 573,385 rows and is *slower* than the unbounded original.-Recorded, not taken — this task is the `LIMIT` only, and the funnel sibling has the same property-today.--### chartBucketProfilesQuery — getProfiles day bucket, screen_view, no breakdowns--**statement** — was IDENTICAL as captured on 2026-09-04 (rows V1/V2 = 4092/4092; rows_read V1/V2 = 212951/49148; wall V1/V2 = 18 ms / 17 ms; clickhouse_settings: session_timezone=UTC (both)); **since M31-001 this is the one case among the six whose result the `LIMIT` truncates — V2 returns 1,000 of those 4,092 ids** (see the amendment above).--```sql--- V1-SELECT DISTINCT profile_id FROM events e WHERE project_id = 'secure-privacy' AND toStartOfDay(created_at) = toDate('2026-07-07 00:00:00') AND name = 'screen_view'--- V2-SELECT DISTINCT profile_id FROM events e WHERE project_id = {p1:String} AND toStartOfDay(created_at) = toDate({p2:String}) AND name = {p3:String} LIMIT {p4:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"2026-07-07 00:00:00","p3":"screen_view","p4":1000}-```--### chartBucketProfilesQuery — getProfiles hour bucket, wildcard event, country filter--**statement** — IDENTICAL; rows V1/V2 = 181/181; rows_read V1/V2 = 212951/8192; wall V1/V2 = 17 ms / 6 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT DISTINCT profile_id FROM events e WHERE country = 'US' AND project_id = 'secure-privacy' AND toStartOfHour(created_at) = toDateTime('2026-07-07 10:00:00')--- V2-SELECT DISTINCT profile_id FROM events e WHERE country = 'US' AND project_id = {p1:String} AND toStartOfHour(created_at) = toDateTime({p2:String}) LIMIT {p3:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"2026-07-07 10:00:00","p3":1000}-```--### chartBucketProfilesQuery — getProfiles minute bucket--**statement** — IDENTICAL; rows V1/V2 = 8/8; rows_read V1/V2 = 212951/8192; wall V1/V2 = 11 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT DISTINCT profile_id FROM events e WHERE project_id = 'secure-privacy' AND toStartOfMinute(created_at) = toDateTime('2026-07-07 10:15:00') AND name = 'screen_view'--- V2-SELECT DISTINCT profile_id FROM events e WHERE project_id = {p1:String} AND toStartOfMinute(created_at) = toDateTime({p2:String}) AND name = {p3:String} LIMIT {p4:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"2026-07-07 10:15:00","p3":"screen_view","p4":1000}-```--### chartBucketProfilesQuery — getProfiles week bucket + breakdowns country/path--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 204759/0; wall V1/V2 = 16 ms / 6 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT DISTINCT profile_id FROM events e WHERE project_id = 'secure-privacy' AND toStartOfWeek(toDateTime(created_at)) = toDate('2026-07-06 00:00:00') AND name = 'screen_view' AND country = 'US' AND path = '/'--- V2-SELECT DISTINCT profile_id FROM events e WHERE project_id = {p1:String} AND toStartOfWeek(toDateTime(created_at)) = toDate({p2:String}) AND name = {p3:String} AND country = {p4:String} AND path = {p5:String} LIMIT {p6:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"2026-07-06 00:00:00","p3":"screen_view","p4":"US","p5":"/","p6":1000}-```--### chartBucketProfilesQuery — getProfiles month bucket + profile filter/breakdown join--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 671345/671345; wall V1/V2 = 118 ms / 107 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT DISTINCT profile_id FROM events e LEFT ANY JOIN (SELECT id, email, properties, first_name FROM profiles FINAL WHERE project_id = 'secure-privacy') as profile on profile.id = profile_id WHERE project_id = 'secure-privacy' AND toStartOfMonth(toDateTime(created_at)) = toDate('2026-07-01 00:00:00') AND name = 'screen_view' AND profile.properties['os'] = 'Mac OS' AND profile.first_name = 'x'--- V2-SELECT DISTINCT profile_id FROM events e LEFT ANY JOIN (SELECT id, email, properties, first_name FROM profiles FINAL WHERE project_id = {p1:String}) as profile on profile.id = profile_id WHERE project_id = {p2:String} AND toStartOfMonth(toDateTime(created_at)) = toDate({p3:String}) AND name = {p4:String} AND profile.properties['os'] = {p5:String} AND profile.first_name = {p6:String} LIMIT {p7:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"secure-privacy","p3":"2026-07-01 00:00:00","p4":"screen_view","p5":"Mac OS","p6":"x","p7":1000}-```--### chartBucketProfilesQuery — getProfiles day bucket + group filter/breakdown join--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 216310/3359; wall V1/V2 = 16 ms / 9 ms; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT DISTINCT profile_id FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') AS _g ON _g.id = _group_id WHERE _g.type = 'company' AND project_id = 'secure-privacy' AND toStartOfDay(created_at) = toDate('2026-07-07 00:00:00') AND name = 'screen_view' AND _g.name = 'Secureprivacy' AND properties['__title'] = 'Secure Privacy'--- V2-SELECT DISTINCT profile_id FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) AS _g ON _g.id = _group_id WHERE _g.type = 'company' AND project_id = {p2:String} AND toStartOfDay(created_at) = toDate({p3:String}) AND name = {p4:String} AND _g.name = {p5:String} AND properties['__title'] = {p6:String} LIMIT {p7:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"secure-privacy","p3":"2026-07-07 00:00:00","p4":"screen_view","p5":"Secureprivacy","p6":"Secure Privacy","p7":1000}-```diff --git a/packages/core/src/modules/chart/src/sql.ts b/packages/core/src/modules/chart/src/sql.tsindex f1fa6ab65..f099dafa6 100644--- a/packages/core/src/modules/chart/src/sql.ts+++ b/packages/core/src/modules/chart/src/sql.ts@@ -1,27 +1,17 @@// Every ClickHouse query the chart module runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/chart.service.ts-// (`getChartSql`, `getAggregateChartSql`) and packages/trpc/src/routers/-// chart.ts (M7-003): the SQL text is V1's, with every chart-level value —-// project id, event name, dates, timezone, cohort ids and names, limits —-// bound as a `{pN:Type}` parameter instead of an escaped literal. Each-// builder's result set was diffed against V1's on the local prod-copy; the-// statements, params, row counts and timings are in sql.proof.md.+// (ADR-013).//-// The field resolver and filter compiler still render text (see compiled.ts);-// their output is spliced, everything else is bound. Dates bind as V1's own-// strings: a String param in a DateTime position is parsed exactly like the-// literal it replaces.+// The field resolver and filter compiler render text (see compiled.ts); their+// output is spliced, everything else is bound. Dates bind as strings: a String+// param in a DateTime position is parsed exactly like the literal it replaces.//-// Cluster note (docs/ENVIRONMENT.md): `events`, `profiles`, `groups` and-// `cohort_members` are Distributed on Cloud. The cohort CTEs, the profile,-// group and cohort LEFT ANY JOINs and any `IN (SELECT ...)` a filter compiles-// keep V1's exact shape and run under the client's-// `distributed_product_mode: 'allow'` as before.+// Cluster note: `events`, `profiles`, `groups` and `cohort_members` are+// Distributed on Cloud. The cohort CTEs, the profile / group / cohort+// LEFT ANY JOINs and any `IN (SELECT ...)` a filter compiles run under the+// client's `distributed_product_mode: 'allow'`.//// The keyed part records below are a local, function-scoped builder (ADR-013-// R5): V1 assigned and re-assigned `sb.select.count`, `sb.where.property`,-// ... by key, and a keyed record keeps that exact clause order — which is-// what makes the proof diff a pure literal→param diff.+// R5): assigning clauses by key keeps a stable clause order.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type {diff --git a/packages/core/src/modules/chart/src/table-filter-where.ts b/packages/core/src/modules/chart/src/table-filter-where.tsindex 6f2d9ff73..617cddf47 100644--- a/packages/core/src/modules/chart/src/table-filter-where.ts+++ b/packages/core/src/modules/chart/src/table-filter-where.ts@@ -1,16 +1,12 @@/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */-// Moved from packages/db/src/services/filter-where.service.ts (M8-005), then-// converted onto the `sql` tag (M12-003). V1's filter compiler for the-// sessions/profiles/events tables — distinct from `./filter-where.ts`'s-// `getEventFiltersWhereClause` (event-property filters), which converted in-// M12-002. Every VALUE binds as a `{name:Type}` param; every identifier goes-// through `sql.id` or a static fragment. Result-set proof:-// field-resolution.sql.proof.md.+// The filter compiler for the sessions/profiles/events tables — distinct from+// `./filter-where.ts`'s `getEventFiltersWhereClause`, which compiles+// event-property filters. Every VALUE binds as a `{name:Type}` param; every+// identifier goes through `sql.id` or a static fragment.//-// Cluster note (docs/ENVIRONMENT.md): `events`, `profiles`, `groups` and-// `cohort_members` are Distributed on Cloud. The cohort / profile / group /-// performed_event subselects keep V1's plain `IN`; no `IN` was converted to-// `GLOBAL IN` or back.+// Cluster note: `events`, `profiles`, `groups` and `cohort_members` are+// Distributed on Cloud. The cohort / profile / group / performed_event+// subselects use plain `IN`.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import {diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.tsindex 4d070e654..42597d6d4 100644--- a/packages/core/src/modules/cohort/cohort.service.ts+++ b/packages/core/src/modules/cohort/cohort.service.ts@@ -1,34 +1,10 @@-// Moved from packages/db/src/services/cohort.service.ts (M5-003). The-// producer wrapper (`enqueueCohortCompute`) moves here too — db cannot hold-// producers (ADR-007's discovery: "packages/db/src/services/cohort.service.ts:12-// imports cohortComputeQueue from @openpanel/queue" was flagged as reaching-// back into infrastructure it should not know about; @openpanel/queue itself-// was deleted at M11-004). packages/db lost this file entirely: nothing-// outside the now-deleted trpc/worker and this module's own tests reached it-// through @openpanel/db's barrel.+// Cohort definitions, membership computation and the compute enqueue.//-// M12-004 converted every ClickHouse statement here onto the ADR-013 `sql`-// tag: values bind as `{pN:Type}` params, identifiers go through `sql.id`,-// structure composes with `sql.join`. `sqlstring` is gone from this module.-// The proof (V1 vs V2 result sets, per branch, against local ClickHouse) is-// `cohort.sql.proof.md` beside this file. Table names are-// a local literal map (`TABLE`, below), not @openpanel/db's `TABLE_NAMES`: the-// latter lives in the same module as `ch`/`chQuery` (clickhouse/client.ts,-// which constructs a real pino logger at import time — the exact cost the lazy-// loads elsewhere in this file exist to defer), and this module's SQL builders-// are pure sync functions the P2 SQL-shape tests call with no ClickHouse-// connection at all.-//-// V1's trpc router (packages/trpc/src/routers/cohort.ts) and worker cron job-// (apps/worker/src/jobs/cron.cohort-refresh.ts) used to stay live (DELEGATE-// PATTERN) and enqueue by calling @openpanel/queue's cohortComputeQueue-// directly, same as gsc's V1 router/worker did for gscQueue (M5-002) —-// @openpanel/queue itself imported @openpanel/core for its logger, so core-// could not import @openpanel/queue back without a real package cycle. Both-// delegates are gone now (apps/worker at P9, packages/trpc/packages/queue at-// M11-004). `CohortService.enqueueCompute` (below) is the canonical,-// ctx.queues-based wrapper for callers that already have a Ctx (this-// module's own rpc mutations and its cron fragment).+// Table names are a local literal map (`TABLE`, below) rather than+// @openpanel/db's `TABLE_NAMES`: that lives in the same module as `ch` /+// `chQuery` (clickhouse/client.ts), which constructs a real pino logger at+// import time, and this module's SQL builders are pure sync functions the+// shape tests call with no ClickHouse connection at all.import type { ClickHouseSettings } from '@clickhouse/client';import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/cohort/cohort.sql.proof.md b/packages/core/src/modules/cohort/cohort.sql.proof.mddeleted file mode 100644index 2654dc807..000000000--- a/packages/core/src/modules/cohort/cohort.sql.proof.md+++ /dev/null@@ -1,1443 +0,0 @@-# cohort.service.ts — V1 → V2 result-set proof (M12-004)--`packages/core/src/modules/cohort/cohort.service.ts` at commit-**54c4fe7af3c57af90b25733a5b8419ab8fde81bb** (this task's parent) held 46-`sqlstring.escape()` sites across every cohort statement. M12-004 moves all of-them onto the ADR-013 `sql` tag. The pre-change file was copied verbatim out of-git (`git show HEAD:… > __v1_m12004.service.ts`, placed inside the module so its-relative imports resolve, deleted after this proof) and **both sides were-imported into one Bun process and called** — no V1 text was retyped. Statements-that are not returned by a builder (the `cohort_members` reads, the two-`DELETE`s) were captured off a fake `deps.ch` that records-`{query, query_params, clickhouse_settings}`, from V1 and V2 identically.-Both sides then went through **one `@clickhouse/client` 1.18.5**, `format:-'JSON'`, same database, same settings; V1 as `query`, V2 as `query` +-`query_params`. `data` and `meta` were compared for every case. Cases whose V1-text has no total `ORDER BY` were compared **as sets** (marked below); the one-case where that is still not enough — a bare `LIMIT` — is treated separately in-§C22 with a V1-vs-V1 control.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, **319,850,695 events**, 18,630,719- profiles. Project **`secure-privacy`** (118,502 profile rows, 30 distinct- event names, `event_date` range 2026-07-01 … 2026-08-25) is the fixture for- groups A, B and C.- **`cohort_members` and `cohort_metadata` are both EMPTY in the prod copy- (`SELECT count()` = 0 / 0).** Postgres holds exactly one `cohort` row —- `cccccccc-0000-4000-8000-000000000001` ("Auth contract cohort", project- `authc-project-a1`), an auth-contract harness fixture whose `definition` is- `{}` and whose `profileCount` is 0. It has no members in ClickHouse and no- definition to compute, so it is nameable but not usable. Group D- therefore executes the seven `cohort_members` statements against the prod copy- for statement equivalence at 0 rows, and group **E repeats all seven on the- isolated `openpanel_test` database** seeded with cohorts `m12004-a`,- `m12004-b` and `m12004-keep` under project `m12004-proof` (7 member rows, 3- metadata rows, 120 events) so every one of them has a **non-zero** row count.- The same split, for the same reason, is the `chart.sql.proof.md` precedent.- The `openpanel_test` fixtures were deleted again after the run.-- **Machine**: single-node ClickHouse **26.1.3.52** on a **4-vCPU** box —- timings are directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). Four statements contain `IN (subquery)` against the- Distributed `cohort_members` (`listCohortMemberProfiles`,- `getCohortMemberEvents`, `getCohortEventsPerDay`, `getCohortMemberRoutes`).- **No `IN` was rewritten to `GLOBAL IN` or the reverse** — see §Distribution.-- **Verdict**: **65 cases, all IDENTICAL** — 58 on the prod copy and 7 on- `openpanel_test`, plus the executed `DELETE` pair in §D8/D9. **64 are- IDENTICAL row-for-row (or as sets, where marked). The 65th, C22, is a V1- defect reproduced identically**: `buildPropertyBasedCohortQuery` emits- `LIMIT n` with no `ORDER BY`, so V1 disagrees with *itself* across- consecutive runs of the same text (control in §C22). It is IDENTICAL on row- count, `meta`, and set-membership in the unrestricted result, and the bare- `LIMIT`'s row identity is recorded as not-a-contract rather than sorted away.- Three deliberate behaviour changes are recorded in §Behaviour changes — none- of them is a difference in any executed result set.--- **Amended by M36-005 (2026-09-16): `getCohortMemberEvents` (D4/E4) and- `getCohortMemberRoutes` (D6/E6) are bounded to a window.** They had no date- filter, so they read the project's whole event history however small the- cohort was (`docs/UNPROVEN_ENDPOINTS.md` §4.4, cause D). Each now carries- `created_at BETWEEN toDateTime({pN:String}) AND toDateTime({pN:String})`- right after `project_id`, spelled as M31-003 spelled it, and the procedures- default to the `3m` range `profile.powerUsers` got. This is a deliberate- semantic change, so D4/D6/E4/E6 below are the record of the old text, not- the current one. Measurements are in the M36-005 section at the end.--## A — `buildEventCriteriaQuery`: every event-criteria branch--The two summary MVs, the three timeframe shapes, the three frequency operators and all six event-property operator branches (`is` / `isNot` single and multi, `contains`, `doesNotContain`, the `default` fall-through) plus the no-property path. `buildTimeConstraint`'s column is now a parameter rather than a `.replace('created_at','event_date')` over finished text; A1–A3 are the proof that the substituted column is byte-identical.--### A1 no filters, relative timeframe--**statement** — IDENTICAL; rows V1/V2 = 892/892; rows_read V1/V2 = 73728/73728; wall V1/V2 = 30 ms / 14 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY)--- V2-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY)--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365}-```--### A2 no filters, absolute BETWEEN--**statement** — IDENTICAL; rows V1/V2 = 892/892; rows_read V1/V2 = 73728/65536; wall V1/V2 = 13 ms / 8 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date BETWEEN toDate('2026-07-01') AND toDate('2026-08-31')--- V2-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date BETWEEN toDate({p3:String}) AND toDate({p4:String})--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": "2026-07-01", "p4": "2026-08-31"}-```--### A3 no filters, absolute open-ended--**statement** — IDENTICAL; rows V1/V2 = 892/892; rows_read V1/V2 = 73728/65536; wall V1/V2 = 9 ms / 11 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate('2026-07-01')--- V2-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate({p3:String})--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": "2026-07-01"}-```--### A4 frequency gte--**statement** — IDENTICAL; rows V1/V2 = 403/403; rows_read V1/V2 = 73728/73728; wall V1/V2 = 13 ms / 11 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND event_date >= toDate(now() - INTERVAL 365 DAY) GROUP BY profile_id HAVING countMerge(event_count) >= 3--- V2-SELECT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) GROUP BY profile_id HAVING countMerge(event_count) >= {p4:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "screen_view", "p3": 365, "p4": 3}-```--### A5 frequency eq--**statement** — IDENTICAL; rows V1/V2 = 47/47; rows_read V1/V2 = 73728/73728; wall V1/V2 = 10 ms / 10 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND event_date >= toDate(now() - INTERVAL 365 DAY) GROUP BY profile_id HAVING countMerge(event_count) = 1--- V2-SELECT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) GROUP BY profile_id HAVING countMerge(event_count) = {p4:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "screen_view", "p3": 365, "p4": 1}-```--### A6 frequency lte--**statement** — IDENTICAL; rows V1/V2 = 71/71; rows_read V1/V2 = 73728/73728; wall V1/V2 = 9 ms / 11 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'screen_view' AND event_date >= toDate(now() - INTERVAL 365 DAY) GROUP BY profile_id HAVING countMerge(event_count) <= 2--- V2-SELECT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) GROUP BY profile_id HAVING countMerge(event_count) <= {p4:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "screen_view", "p3": 365, "p4": 2}-```--### A7 property is (single value)--**statement** — IDENTICAL; rows V1/V2 = 810/810; rows_read V1/V2 = 155648/155648; wall V1/V2 = 31 ms / 15 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value = 'Web Small'))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value = {p5:String}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": "Web Small"}-```--### A8 property is (multi value)--**statement** — IDENTICAL; rows V1/V2 = 810/810; rows_read V1/V2 = 155648/155648; wall V1/V2 = 16 ms / 16 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value IN ('Web Small', 'Web Medium')))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value IN {p5:Array(String)}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": ["Web Small", "Web Medium"]}-```--### A9 property isNot (single value)--**statement** — IDENTICAL; rows V1/V2 = 82/82; rows_read V1/V2 = 155648/155648; wall V1/V2 = 18 ms / 15 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value != 'Web Small'))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value != {p5:String}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": "Web Small"}-```--### A10 property isNot (multi value)--**statement** — IDENTICAL; rows V1/V2 = 82/82; rows_read V1/V2 = 155648/155648; wall V1/V2 = 16 ms / 16 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value NOT IN ('Web Small', 'Web Medium')))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value NOT IN {p5:Array(String)}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": ["Web Small", "Web Medium"]}-```--### A11 property contains--**statement** — IDENTICAL; rows V1/V2 = 808/808; rows_read V1/V2 = 155648/155648; wall V1/V2 = 17 ms / 17 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'signUpSource' AND (property_value LIKE '%Google%' OR property_value LIKE '%o\'brien-%_%')))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND (property_value LIKE {p5:String} OR property_value LIKE {p6:String})))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "signUpSource", "p5": "%Google%", "p6": "%o'brien-%_%"}-```--### A12 property doesNotContain--**statement** — IDENTICAL; rows V1/V2 = 46/46; rows_read V1/V2 = 155648/155648; wall V1/V2 = 13 ms / 14 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'signUpSource' AND (property_value NOT LIKE '%Google%')))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND (property_value NOT LIKE {p5:String})))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "signUpSource", "p5": "%Google%"}-```--### A13 property default operator (startsWith falls through to IN)--**statement** — IDENTICAL; rows V1/V2 = 810/810; rows_read V1/V2 = 155648/155648; wall V1/V2 = 16 ms / 15 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value IN ('Web Small')))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value IN {p5:Array(String)}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": ["Web Small"]}-```--### A14 two property filters OR-ed--**statement** — IDENTICAL; rows V1/V2 = 810/810; rows_read V1/V2 = 155648/155648; wall V1/V2 = 16 ms / 18 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value = 'Web Small') OR (property_key = 'signUpSource' AND property_value = 'Google Tag'))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value = {p5:String}) OR (property_key = {p6:String} AND property_value = {p7:String}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": "Web Small", "p6": "signUpSource", "p7": "Google Tag"}-```--### A15 property filter + frequency--**statement** — IDENTICAL; rows V1/V2 = 810/810; rows_read V1/V2 = 155648/155648; wall V1/V2 = 21 ms / 19 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value = 'Web Small')) GROUP BY profile_id HAVING countMerge(event_count) >= 1--- V2-SELECT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value = {p5:String})) GROUP BY profile_id HAVING countMerge(event_count) >= {p6:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": "Web Small", "p6": 1}-```--### A16 property is with an empty value list (V1 IN ())--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 5 ms / 5 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--0 rows on both sides is the point: V1's literal `IN ()` and V2's `IN {p:Array(String)}` with `[]` both match nothing. Recipe idiom 10.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value IN ()))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value IN {p5:Array(String)}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": []}-```--### A17 quote in the comparand--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 155648/155648; wall V1/V2 = 9 ms / 11 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--0 rows on both sides — no `signed_up` event carries `Web 'Small'`. The case exists for the escaping half: V1 emits `'Web \'Small\''`, V2 never puts the value in the text. Positive-row coverage for a quote is C20.--```sql--- V1-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value = 'Web \'Small\''))--- V2-SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value = {p5:String}))--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "productName", "p5": "Web 'Small'"}-```--### A18 profile.properties filter is NOT an event-property filter--**statement** — IDENTICAL; rows V1/V2 = 892/892; rows_read V1/V2 = 73728/73728; wall V1/V2 = 8 ms / 9 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY)--- V2-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY)--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365}-```--## B — combining criteria: `INTERSECT` / `UNION DISTINCT`, and the count wrapper--`sql.join`'s separator set is closed and holds neither keyword, so the criteria fold left — the same associativity `queries.join(' INTERSECT ')` produced. Captured off the real `computeEventBasedCohort` / `countEventBasedCohort`, not rebuilt.--### B1 computeEventBasedCohort — INTERSECT (operator: and)--**statement** — IDENTICAL; rows V1/V2 = 214/214; rows_read V1/V2 = 147456/147456; wall V1/V2 = 12 ms / 12 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) INTERSECT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'user_logged_in' AND event_date >= toDate(now() - INTERVAL 365 DAY)--- V2-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) INTERSECT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p4:String} AND name = {p5:String} AND event_date >= toDate(now() - INTERVAL {p6:UInt64} DAY)--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "secure-privacy", "p5": "user_logged_in", "p6": 365}-```--### B2 computeEventBasedCohort — UNION DISTINCT (operator: or)--**statement** — IDENTICAL; rows V1/V2 = 989/989; rows_read V1/V2 = 147456/147456; wall V1/V2 = 12 ms / 12 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) UNION DISTINCT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'user_logged_in' AND event_date >= toDate(now() - INTERVAL 365 DAY)--- V2-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) UNION DISTINCT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p4:String} AND name = {p5:String} AND event_date >= toDate(now() - INTERVAL {p6:UInt64} DAY)--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "secure-privacy", "p5": "user_logged_in", "p6": 365}-```--### B3 computeEventBasedCohort — UNION DISTINCT with LIMIT--**statement** — IDENTICAL; rows V1/V2 = 989/989; rows_read V1/V2 = 147456/147456; wall V1/V2 = 11 ms / 12 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) UNION DISTINCT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'user_logged_in' AND event_date >= toDate(now() - INTERVAL 365 DAY) LIMIT 500--- V2-SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) UNION DISTINCT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p4:String} AND name = {p5:String} AND event_date >= toDate(now() - INTERVAL {p6:UInt64} DAY) LIMIT {p7:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "secure-privacy", "p5": "user_logged_in", "p6": 365, "p7": 500}-```--### B4 countEventBasedCohort — INTERSECT--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 147456/147456; wall V1/V2 = 11 ms / 12 ms.--```sql--- V1-SELECT count() as count FROM ( SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) INTERSECT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'user_logged_in' AND event_date >= toDate(now() - INTERVAL 365 DAY) )--- V2-SELECT count() as count FROM ( SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) INTERSECT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p4:String} AND name = {p5:String} AND event_date >= toDate(now() - INTERVAL {p6:UInt64} DAY) )--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "secure-privacy", "p5": "user_logged_in", "p6": 365}-```--### B5 countEventBasedCohort — UNION DISTINCT--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 147456/147456; wall V1/V2 = 11 ms / 11 ms.--```sql--- V1-SELECT count() as count FROM ( SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) UNION DISTINCT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'user_logged_in' AND event_date >= toDate(now() - INTERVAL 365 DAY) )--- V2-SELECT count() as count FROM ( SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) UNION DISTINCT SELECT DISTINCT profile_id FROM event_profile_summary_mv WHERE project_id = {p4:String} AND name = {p5:String} AND event_date >= toDate(now() - INTERVAL {p6:UInt64} DAY) )--- V2 params: {"p1": "secure-privacy", "p2": "signed_up", "p3": 365, "p4": "secure-privacy", "p5": "user_logged_in", "p6": 365}-```--## C — `buildPropertyBasedCohortQuery`: every profile-filter kind--All thirteen operators `getProfileFiltersWhereClause` distinguishes, on both column shapes (a `properties[...]` Map lookup and a plain column), `AND` and `OR`, the shared `argMax` row key including its dedup, the `WHERE 1=0` guard, the limit, and the two count/compute wrappers.--### C1 is (single value), map column--**statement** — IDENTICAL; rows V1/V2 = 1579/1579; rows_read V1/V2 = 212832/212832; wall V1/V2 = 98 ms / 93 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'SE')--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String})--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE"}-```--### C2 is (multi value), map column--**statement** — IDENTICAL; rows V1/V2 = 1661/1661; rows_read V1/V2 = 212832/212832; wall V1/V2 = 88 ms / 89 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) IN ('SE', 'NO'))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) IN {p4:Array(String)})--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": ["SE", "NO"]}-```--### C3 isNot (single value)--**statement** — IDENTICAL; rows V1/V2 = 116923/116923; rows_read V1/V2 = 212832/212832; wall V1/V2 = 126 ms / 127 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) != 'SE')--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) != {p4:String})--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE"}-```--### C4 isNot (multi value)--**statement** — IDENTICAL; rows V1/V2 = 116841/116841; rows_read V1/V2 = 212832/212832; wall V1/V2 = 120 ms / 138 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) NOT IN ('SE', 'NO'))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) NOT IN {p4:Array(String)})--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": ["SE", "NO"]}-```--### C5 contains--**statement** — IDENTICAL; rows V1/V2 = 107590/107590; rows_read V1/V2 = 212832/212832; wall V1/V2 = 128 ms / 120 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.properties['browser'], tuple(last_seen_at, cityHash64(profiles.properties['browser']))) LIKE '%Chrome%'))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) LIKE {p4:String}))--- V2 params: {"p1": "secure-privacy", "p2": "browser", "p3": "browser", "p4": "%Chrome%"}-```--### C6 doesNotContain--**statement** — IDENTICAL; rows V1/V2 = 10912/10912; rows_read V1/V2 = 212832/212832; wall V1/V2 = 98 ms / 87 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.properties['browser'], tuple(last_seen_at, cityHash64(profiles.properties['browser']))) NOT LIKE '%Chrome%'))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) NOT LIKE {p4:String}))--- V2 params: {"p1": "secure-privacy", "p2": "browser", "p3": "browser", "p4": "%Chrome%"}-```--### C7 startsWith--**statement** — IDENTICAL; rows V1/V2 = 103568/103568; rows_read V1/V2 = 212832/212832; wall V1/V2 = 113 ms / 122 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.properties['browser'], tuple(last_seen_at, cityHash64(profiles.properties['browser']))) LIKE 'Chr%'))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) LIKE {p4:String}))--- V2 params: {"p1": "secure-privacy", "p2": "browser", "p3": "browser", "p4": "Chr%"}-```--### C8 endsWith--**statement** — IDENTICAL; rows V1/V2 = 13252/13252; rows_read V1/V2 = 212832/212832; wall V1/V2 = 89 ms / 92 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.properties['os'], tuple(last_seen_at, cityHash64(profiles.properties['os']))) LIKE '%OS'))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) LIKE {p4:String}))--- V2 params: {"p1": "secure-privacy", "p2": "os", "p3": "os", "p4": "%OS"}-```--### C9 isNull--**statement** — IDENTICAL; rows V1/V2 = 117249/117249; rows_read V1/V2 = 212832/212832; wall V1/V2 = 96 ms / 89 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) IS NULL OR argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) = ''))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) IS NULL OR argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) = ''))--- V2 params: {"p1": "secure-privacy"}-```--### C10 isNotNull--**statement** — IDENTICAL; rows V1/V2 = 1253/1253; rows_read V1/V2 = 212832/212832; wall V1/V2 = 79 ms / 57 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) IS NOT NULL AND argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) != ''))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) IS NOT NULL AND argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) != ''))--- V2 params: {"p1": "secure-privacy"}-```--### C11 gt (numeric cast)--**statement** — IDENTICAL; rows V1/V2 = 2528/2528; rows_read V1/V2 = 212832/212832; wall V1/V2 = 86 ms / 93 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties['latitude'], tuple(last_seen_at, cityHash64(profiles.properties['latitude'])))) > 55)--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}])))) > {p4:Float64})--- V2 params: {"p1": "secure-privacy", "p2": "latitude", "p3": "latitude", "p4": 55}-```--### C12 lt (numeric cast)--**statement** — IDENTICAL; rows V1/V2 = 115973/115973; rows_read V1/V2 = 212832/212832; wall V1/V2 = 125 ms / 122 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties['latitude'], tuple(last_seen_at, cityHash64(profiles.properties['latitude'])))) < 55)--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}])))) < {p4:Float64})--- V2 params: {"p1": "secure-privacy", "p2": "latitude", "p3": "latitude", "p4": 55}-```--### C13 gte (numeric cast)--**statement** — IDENTICAL; rows V1/V2 = 2528/2528; rows_read V1/V2 = 212832/212832; wall V1/V2 = 96 ms / 93 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties['latitude'], tuple(last_seen_at, cityHash64(profiles.properties['latitude'])))) >= 55)--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}])))) >= {p4:Float64})--- V2 params: {"p1": "secure-privacy", "p2": "latitude", "p3": "latitude", "p4": 55}-```--### C14 lte (numeric cast, negative comparand)--**statement** — IDENTICAL; rows V1/V2 = 72747/72747; rows_read V1/V2 = 212832/212832; wall V1/V2 = 110 ms / 132 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties['longitude'], tuple(last_seen_at, cityHash64(profiles.properties['longitude'])))) <= -1.5)--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}])))) <= {p4:Float64})--- V2 params: {"p1": "secure-privacy", "p2": "longitude", "p3": "longitude", "p4": -1.5}-```--### C15 gt with a non-numeric comparand (V1 emitted a bare NaN)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 212832/212832; wall V1/V2 = 75 ms / 68 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--`Number('abc')` is `NaN`. V1 spliced the bare token `NaN` (a legal ClickHouse Float64 literal); V2 binds `{p4:Float64}`, which the driver puts on the wire as `nan`. Both compare false for every row — 0 rows on both sides, and `> NaN` is false by IEEE rules, not by an error.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties['latitude'], tuple(last_seen_at, cityHash64(profiles.properties['latitude'])))) > NaN)--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (toFloat64OrNull(argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}])))) > {p4:Float64})--- V2 params: {"p1": "secure-privacy", "p2": "latitude", "p3": "latitude", "p4": null}-```--### C16 plain column (profile.email) via sql.id--**statement** — IDENTICAL; rows V1/V2 = 1253/1253; rows_read V1/V2 = 212832/212832; wall V1/V2 = 54 ms / 55 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) LIKE '%@%'))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.email))) LIKE {p2:String}))--- V2 params: {"p1": "secure-privacy", "p2": "%@%"}-```--### C17 AND of a map column and a plain column--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 212832/212832; wall V1/V2 = 84 ms / 86 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country'], profiles.email))) = 'SE' AND (argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties['country'], profiles.email))) IS NOT NULL AND argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties['country'], profiles.email))) != ''))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}], profiles.email))) = {p4:String} AND (argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties[{p5:String}], profiles.email))) IS NOT NULL AND argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties[{p6:String}], profiles.email))) != ''))--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE", "p5": "country", "p6": "country"}-```--### C18 OR of two columns--**statement** — IDENTICAL; rows V1/V2 = 1661/1661; rows_read V1/V2 = 212832/212832; wall V1/V2 = 80 ms / 82 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'SE' OR argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'NO')--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String} OR argMax(profiles.properties[{p5:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p6:String}]))) = {p7:String})--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE", "p5": "country", "p6": "country", "p7": "NO"}-```--### C19 quote in a user-controlled property key--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 212832/212832; wall V1/V2 = 63 ms / 64 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--0 rows on both sides — no profile has a property literally named `coun'try`. The case exists for the key-escaping half: V1 emits `profiles.properties['coun\'try']`, V2 emits `profiles.properties[{p2:String}]` with the raw key bound. C20 carries the positive-row quote coverage (1 row, `O'Fallon`).--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['coun\'try'], tuple(last_seen_at, cityHash64(profiles.properties['coun\'try']))) = 'SE')--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String})--- V2 params: {"p1": "secure-privacy", "p2": "coun'try", "p3": "coun'try", "p4": "SE"}-```--### C20 quote in the comparand--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 212832/212832; wall V1/V2 = 65 ms / 64 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['city'], tuple(last_seen_at, cityHash64(profiles.properties['city']))) = 'O\'Fallon')--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String})--- V2 params: {"p1": "secure-privacy", "p2": "city", "p3": "city", "p4": "O'Fallon"}-```--### C21 every filter dropped as empty (WHERE 1=0)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 4 ms / 3 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--0 rows on both sides by construction — `WHERE 1=0` is the guard that keeps an all-empty filter set from becoming "match everything". Recipe trap 6.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE 1=0--- V2-SELECT id as profile_id FROM profiles WHERE 1=0-```--### C22 limit applied--**statement** — DIFFERENT data; rows V1/V2 = 25/25; rows_read V1/V2 = 212832/212832; wall V1/V2 = 50 ms / 74 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--**Not comparable row-for-row, and not because of the conversion** — `LIMIT` with no `ORDER BY`. See §C22 below for the V1-vs-V1 control and what this case *is* held to (row count, `meta`, subset of the unrestricted result, and the rendered `LIMIT {p5:UInt64}` / `p5 = 25`).--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'SE') LIMIT 25--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String}) LIMIT {p5:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE", "p5": 25}-```--### C23 duplicate column deduped in the shared row key--**statement** — IDENTICAL; rows V1/V2 = 1661/1661; rows_read V1/V2 = 212832/212832; wall V1/V2 = 108 ms / 86 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'SE' OR argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'NO')--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String} OR argMax(profiles.properties[{p5:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p6:String}]))) = {p7:String})--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE", "p5": "country", "p6": "country", "p7": "NO"}-```--### C24 countPropertyBasedCohort wrapper (SELECT count() FROM (...))--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 212832/212832; wall V1/V2 = 61 ms / 65 ms.--```sql--- V1-SELECT count() as count FROM ( SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'SE') )--- V2-SELECT count() as count FROM ( SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String}) )--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE"}-```--### C25 computePropertyBasedCohort (limit + PROFILE_COHORT_QUERY_SETTINGS)--**statement** — IDENTICAL; rows V1/V2 = 100/100; rows_read V1/V2 = 212832/212832; wall V1/V2 = 52 ms / 72 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country']))) = 'SE') LIMIT 100--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) = {p4:String}) LIMIT {p5:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "SE", "p5": 100}-```--### C26 isNull on a MAP column (columnAccess rendered twice)--**statement** — IDENTICAL; rows V1/V2 = 98300/98300; rows_read V1/V2 = 212832/212832; wall V1/V2 = 158 ms / 145 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--The column fragment is interpolated **twice** in one statement (`IS NULL OR … = ''`) and each copy carries the shared row key, so the one map key `model` renders as **four** placeholders `p2`–`p5`, each bound to `model`. Fragments are name-free until `toStatement()` assigns from a single counter, so repeated rendering multiplies placeholders rather than colliding them (ADR-013 R2) — and the result set is identical to V1's four inline copies of `'model'`.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.properties['model'], tuple(last_seen_at, cityHash64(profiles.properties['model']))) IS NULL OR argMax(profiles.properties['model'], tuple(last_seen_at, cityHash64(profiles.properties['model']))) = ''))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) IS NULL OR argMax(profiles.properties[{p4:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p5:String}]))) = ''))--- V2 params: {"p1": "secure-privacy", "p2": "model", "p3": "model", "p4": "model", "p5": "model"}-```--### C27 isNotNull on a MAP column (columnAccess rendered twice)--**statement** — IDENTICAL; rows V1/V2 = 20202/20202; rows_read V1/V2 = 212832/212832; wall V1/V2 = 109 ms / 88 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING ((argMax(profiles.properties['model'], tuple(last_seen_at, cityHash64(profiles.properties['model']))) IS NOT NULL AND argMax(profiles.properties['model'], tuple(last_seen_at, cityHash64(profiles.properties['model']))) != ''))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING ((argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}]))) IS NOT NULL AND argMax(profiles.properties[{p4:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p5:String}]))) != ''))--- V2 params: {"p1": "secure-privacy", "p2": "model", "p3": "model", "p4": "model", "p5": "model"}-```--### C28 three filters sharing one argMax row key--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 212832/212832; wall V1/V2 = 110 ms / 108 ms.--Compared as a **set** — V1 has no total `ORDER BY` on this statement, so row order is arbitrary.--One `latestPerProfileKey` fragment shared by four `argMax` calls (`isNotNull` uses two), itself carrying two map-key params: **13** placeholders rendered from four distinct fragments, every one bound to the right value, and the shared key text byte-identical at all four sites — which is the invariant `buildProfileCohortHavingClause`'s comment exists to protect.--```sql--- V1-SELECT id as profile_id FROM profiles WHERE project_id = 'secure-privacy' GROUP BY id HAVING (argMax(profiles.properties['country'], tuple(last_seen_at, cityHash64(profiles.properties['country'], profiles.properties['browser'], profiles.email))) = 'SE' AND (argMax(profiles.properties['browser'], tuple(last_seen_at, cityHash64(profiles.properties['country'], profiles.properties['browser'], profiles.email))) LIKE '%Chrome%') AND (argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties['country'], profiles.properties['browser'], profiles.email))) IS NOT NULL AND argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties['country'], profiles.properties['browser'], profiles.email))) != ''))--- V2-SELECT id as profile_id FROM profiles WHERE project_id = {p1:String} GROUP BY id HAVING (argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}], profiles.properties[{p4:String}], profiles.email))) = {p5:String} AND (argMax(profiles.properties[{p6:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p7:String}], profiles.properties[{p8:String}], profiles.email))) LIKE {p9:String}) AND (argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties[{p10:String}], profiles.properties[{p11:String}], profiles.email))) IS NOT NULL AND argMax(profiles.email, tuple(last_seen_at, cityHash64(profiles.properties[{p12:String}], profiles.properties[{p13:String}], profiles.email))) != ''))--- V2 params: {"p1": "secure-privacy", "p2": "country", "p3": "country", "p4": "browser", "p5": "SE", "p6": "browser", "p7": "country", "p8": "browser", "p9": "%Chrome%", "p10": "country", "p11": "browser", "p12": "country", "p13": "browser"}-```-## D — the `cohort_members` statements, on the prod copy--`cohort_members` and `cohort_metadata` are **empty** in the prod copy, so these seven prove statement equivalence at 0 rows. Group E re-runs all seven with rows.--### D1 getCohortMembers (no limit/offset)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 19 ms / 3 ms.--0 rows: `cohort_members` is EMPTY in the prod copy. Positive-row coverage is E1.--```sql--- V1-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = 'secure-privacy' AND cohort_id = 'm12004-proof-cohort' ORDER BY matched_at DESC--- V2-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String} ORDER BY matched_at DESC--- V2 params: {"p1": "secure-privacy", "p2": "m12004-proof-cohort"}-```--### D2 getCohortMembers (limit + offset)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 3 ms / 3 ms.--0 rows, empty table. See E2.--```sql--- V1-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = 'secure-privacy' AND cohort_id = 'm12004-proof-cohort' ORDER BY matched_at DESC LIMIT 5 OFFSET 2--- V2-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String} ORDER BY matched_at DESC LIMIT {p3:UInt64} OFFSET {p4:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "m12004-proof-cohort", "p3": 5, "p4": 2}-```--### D3 getCohortCount (stale cache → ClickHouse)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 5 ms / 4 ms.--```sql--- V1-SELECT count() as count FROM cohort_members FINAL WHERE project_id = 'secure-privacy' AND cohort_id = 'm12004-proof-cohort'--- V2-SELECT count() as count FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String}--- V2 params: {"p1": "secure-privacy", "p2": "m12004-proof-cohort"}-```--### D4 getCohortMemberEvents--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 16 ms / 12 ms.--0 rows, empty `cohort_members`. See E4.--```sql--- V1-SELECT name, count() AS count FROM events WHERE project_id = 'secure-privacy' AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'm12004-proof-cohort' AND project_id = 'secure-privacy' ) AND name NOT IN ('screen_view', 'session_start', 'session_end') GROUP BY name ORDER BY count DESC LIMIT 10--- V2-SELECT name, count() AS count FROM events WHERE project_id = {p1:String} AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String} ) AND name NOT IN ('screen_view', 'session_start', 'session_end') GROUP BY name ORDER BY count DESC LIMIT {p4:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "m12004-proof-cohort", "p3": "secure-privacy", "p4": 10}-```--### D5 getCohortEventsPerDay--**statement** — IDENTICAL; rows V1/V2 = 31/31; rows_read V1/V2 = 0/0; wall V1/V2 = 9 ms / 11 ms.--```sql--- V1-SELECT toDate(created_at) AS date, count() AS count FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDate(now() - INTERVAL 30 DAY) AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'm12004-proof-cohort' AND project_id = 'secure-privacy' ) GROUP BY date ORDER BY date ASC WITH FILL FROM toDate(now() - INTERVAL 30 DAY) TO toDate(now() + INTERVAL 1 DAY) STEP INTERVAL 1 DAY--- V2-SELECT toDate(created_at) AS date, count() AS count FROM events WHERE project_id = {p1:String} AND created_at >= toDate(now() - INTERVAL {p2:UInt64} DAY) AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p3:String} AND project_id = {p4:String} ) GROUP BY date ORDER BY date ASC WITH FILL FROM toDate(now() - INTERVAL {p5:UInt64} DAY) TO toDate(now() + INTERVAL 1 DAY) STEP INTERVAL 1 DAY--- V2 params: {"p1": "secure-privacy", "p2": 30, "p3": "m12004-proof-cohort", "p4": "secure-privacy", "p5": 30}-```--### D6 getCohortMemberRoutes--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 14 ms / 9 ms.--0 rows, empty `cohort_members`. See E6.--```sql--- V1-SELECT path, count() AS count FROM events WHERE project_id = 'secure-privacy' AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'm12004-proof-cohort' AND project_id = 'secure-privacy' ) AND name = 'screen_view' AND path != '' GROUP BY path ORDER BY count DESC LIMIT 10--- V2-SELECT path, count() AS count FROM events WHERE project_id = {p1:String} AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String} ) AND name = 'screen_view' AND path != '' GROUP BY path ORDER BY count DESC LIMIT {p4:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "m12004-proof-cohort", "p3": "secure-privacy", "p4": 10}-```--### D7 getProfilesInCohort (limit 100000)--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 4 ms / 6 ms.--0 rows, empty `cohort_members`. See E7.--```sql--- V1-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = 'secure-privacy' AND cohort_id = 'm12004-proof-cohort' ORDER BY matched_at DESC LIMIT 100000--- V2-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String} ORDER BY matched_at DESC LIMIT {p3:UInt64}--- V2 params: {"p1": "secure-privacy", "p2": "m12004-proof-cohort", "p3": 100000}-```--## E — the same `cohort_members` statements on seeded `openpanel_test`--Isolated test database, project `m12004-proof`: cohorts `m12004-a` (3 members), `m12004-b` (3 members, byte-identical fixture for the DELETE comparison) and `m12004-keep` (1 member, must survive), 3 `cohort_metadata` rows and 120 events across 4 profiles. Every case here has a non-zero row count. Fixtures deleted after the run.--### E1 getCohortMembers (no limit/offset)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 7/7; wall V1/V2 = 17 ms / 6 ms.--```sql--- V1-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = 'm12004-proof' AND cohort_id = 'm12004-a' ORDER BY matched_at DESC--- V2-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String} ORDER BY matched_at DESC--- V2 params: {"p1": "m12004-proof", "p2": "m12004-a"}-```--### E2 getCohortMembers (limit 2, offset 1)--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 7/7; wall V1/V2 = 6 ms / 5 ms.--```sql--- V1-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = 'm12004-proof' AND cohort_id = 'm12004-a' ORDER BY matched_at DESC LIMIT 2 OFFSET 1--- V2-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String} ORDER BY matched_at DESC LIMIT {p3:UInt64} OFFSET {p4:UInt64}--- V2 params: {"p1": "m12004-proof", "p2": "m12004-a", "p3": 2, "p4": 1}-```--### E3 getCohortCount--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 7/7; wall V1/V2 = 5 ms / 6 ms.--```sql--- V1-SELECT count() as count FROM cohort_members FINAL WHERE project_id = 'm12004-proof' AND cohort_id = 'm12004-a'--- V2-SELECT count() as count FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String}--- V2 params: {"p1": "m12004-proof", "p2": "m12004-a"}-```--### E4 getCohortMemberEvents--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 127/127; wall V1/V2 = 9 ms / 8 ms.--```sql--- V1-SELECT name, count() AS count FROM events WHERE project_id = 'm12004-proof' AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'm12004-a' AND project_id = 'm12004-proof' ) AND name NOT IN ('screen_view', 'session_start', 'session_end') GROUP BY name ORDER BY count DESC LIMIT 10--- V2-SELECT name, count() AS count FROM events WHERE project_id = {p1:String} AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String} ) AND name NOT IN ('screen_view', 'session_start', 'session_end') GROUP BY name ORDER BY count DESC LIMIT {p4:UInt64}--- V2 params: {"p1": "m12004-proof", "p2": "m12004-a", "p3": "m12004-proof", "p4": 10}-```--### E5 getCohortEventsPerDay--**statement** — IDENTICAL; rows V1/V2 = 31/31; rows_read V1/V2 = 127/127; wall V1/V2 = 12 ms / 8 ms.--```sql--- V1-SELECT toDate(created_at) AS date, count() AS count FROM events WHERE project_id = 'm12004-proof' AND created_at >= toDate(now() - INTERVAL 30 DAY) AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'm12004-a' AND project_id = 'm12004-proof' ) GROUP BY date ORDER BY date ASC WITH FILL FROM toDate(now() - INTERVAL 30 DAY) TO toDate(now() + INTERVAL 1 DAY) STEP INTERVAL 1 DAY--- V2-SELECT toDate(created_at) AS date, count() AS count FROM events WHERE project_id = {p1:String} AND created_at >= toDate(now() - INTERVAL {p2:UInt64} DAY) AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p3:String} AND project_id = {p4:String} ) GROUP BY date ORDER BY date ASC WITH FILL FROM toDate(now() - INTERVAL {p5:UInt64} DAY) TO toDate(now() + INTERVAL 1 DAY) STEP INTERVAL 1 DAY--- V2 params: {"p1": "m12004-proof", "p2": 30, "p3": "m12004-a", "p4": "m12004-proof", "p5": 30}-```--### E6 getCohortMemberRoutes--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 127/127; wall V1/V2 = 8 ms / 8 ms.--```sql--- V1-SELECT path, count() AS count FROM events WHERE project_id = 'm12004-proof' AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'm12004-a' AND project_id = 'm12004-proof' ) AND name = 'screen_view' AND path != '' GROUP BY path ORDER BY count DESC LIMIT 10--- V2-SELECT path, count() AS count FROM events WHERE project_id = {p1:String} AND profile_id IN ( SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String} ) AND name = 'screen_view' AND path != '' GROUP BY path ORDER BY count DESC LIMIT {p4:UInt64}--- V2 params: {"p1": "m12004-proof", "p2": "m12004-a", "p3": "m12004-proof", "p4": 10}-```--### E7 getProfilesInCohort (limit 100000)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 7/7; wall V1/V2 = 5 ms / 5 ms.--```sql--- V1-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = 'm12004-proof' AND cohort_id = 'm12004-a' ORDER BY matched_at DESC LIMIT 100000--- V2-SELECT profile_id, count() OVER() as total FROM cohort_members FINAL WHERE project_id = {p1:String} AND cohort_id = {p2:String} ORDER BY matched_at DESC LIMIT {p3:UInt64}--- V2 params: {"p1": "m12004-proof", "p2": "m12004-a", "p3": 100000}-```--## The `_all_cohorts` material--The `_all_cohorts` CTE that chart's cohort breakdowns `INNER JOIN` against is-built by `chart/src/chart.sql.ts` (`allCohortsCte`, `chart.sql.ts:224-229`), and-that file has been on the `sql` tag since M7 — it is not this module's SQL and-is untouched here:--```sql-SELECT profile_id, cohort_id FROM cohort_members FINAL WHERE project_id = {pN:String}-```--What *this* module owns is the **material it reads**: every row in-`cohort_members` is written by `storeCohortMembership` (a `ch.insert`, no SQL-text, unchanged) and removed by the two `DELETE`s, and the membership itself is-decided by the `computeCohort` statements in groups A–C. All of those are-converted and proved above; §D8/D9 executes the two deletes and shows a-non-targeted cohort surviving. `cohortMembershipCte` and `allCohortsLabelExpr`-in `chart.sql.ts` read the same `cohort_members` columns-(`project_id, cohort_id, profile_id`) this module writes, and neither column-list nor `FINAL` placement moved on either side — the goldens' cohort-breakdown-cases are the end-to-end check, and they are 137/137 with zero diffs.--## C22 — `LIMIT` with no `ORDER BY`: V1 disagrees with itself--`buildPropertyBasedCohortQuery(projectId, definition, limit)` emits-`LIMIT n` with no `ORDER BY`, so *which* n rows come back is not a contract.-Comparing the two sides row-for-row therefore fails against V1 as readily as-against V2. Measured 2026-09-07, the same V1 text run three times in a row:--```-V1-vs-V1, 3 runs of the SAME text, distinct result sets: 3 (first control)-V1-vs-V1, 3 runs of the SAME text, distinct result sets: 2 (second control)-```--What the conversion can be held to, and was:--```-limited rows V1/V2: 25 / 25-meta identical: true-V1 limited rows ⊆ full set: true-V2 limited rows ⊆ full set: true-unrestricted rows V1/V2: 1579 / 1579 (result sets identical — case C1)-rows_read V1/V2: 212832 / 212832 ; wall 80 ms / 79 ms-```--The `LIMIT` clause itself is proved by C25 — `computePropertyBasedCohort` with-`limit: 100` — which came back IDENTICAL row-for-row on this run, and by the-rendered `LIMIT {p5:UInt64}` + `p5 = 25` above. The row *identity* under a bare-`LIMIT` is recorded here as not-a-contract rather than sorted away.--## Distribution — `IN` / `GLOBAL IN` unchanged--The module contains **no `GLOBAL`** before or after:--```-$ grep -rn "GLOBAL" /tmp/m12004/v1-cohort.service.ts packages/core/src/modules/cohort/-(none on either side)-```--The four `IN (subquery)` sites — all against the Distributed `cohort_members` —-are at the same four statements on both sides and were not touched:--```-$ grep -n "IN ($" <V1> $ grep -n "IN ($" <V2>-845: AND id IN ( 908: AND id IN (-883: AND profile_id IN ( 949: AND profile_id IN (-911: AND profile_id IN ( 979: AND profile_id IN (-939: AND profile_id IN ( 1008: AND profile_id IN (-```--(The first is `listCohortMemberProfiles`, already converted at M12-003 and-untouched here.) The whole-file `IN (` count drops 11 → 10 because-**value-list** `IN ('a', 'b')` becomes `IN {p:Array(String)}` — a binding-change, not a distribution one; both forms are single-node-local and-shard-irrelevant. Three of the four subquery sites gained a one-line comment-saying the plain `IN` is V1's and is kept as written.--Whether any of those four *should* be `GLOBAL IN` is the pre-existing question-`retention.sql.ts:14` and `sankey.sql.ts:14-16` also record and do not answer.--## `{cluster}` is a macro, not a placeholder--`updateCohortMembership` and `deleteCohortMembership` target-`getReplicatedTableName(t)`, which under `CLICKHOUSE_CLUSTER` renders-`<t>_replicated ON CLUSTER '{cluster}'` — not an identifier, so it cannot go-through `sql.id` whole. V2 rebuilds the same text from a validated identifier-plus literal template text (`replicatedTarget`, asserted byte-equal to-`getReplicatedTableName` in `src/cohort-sql.test.ts`). Rendered side by side-with `CLICKHOUSE_CLUSTER`/`SELF_HOSTED` unset (i.e. clustered):--```sql--- V1-DELETE FROM cohort_members_replicated ON CLUSTER '{cluster}' WHERE cohort_id = 'c1' AND project_id = 'p1'-DELETE FROM cohort_metadata_replicated ON CLUSTER '{cluster}' WHERE cohort_id = 'c1' AND project_id = 'p1'--- V2-DELETE FROM cohort_members_replicated ON CLUSTER '{cluster}' WHERE cohort_id = {p1:String} AND project_id = {p2:String}-DELETE FROM cohort_metadata_replicated ON CLUSTER '{cluster}' WHERE cohort_id = {p1:String} AND project_id = {p2:String}--- V2 params: {"p1": "c1", "p2": "p1"}-```--That form cannot be *executed* on a single node (this box has the `cluster`-macro but no such cluster), so the interaction that matters — does adding-`query_params` to a statement break the `{cluster}` macro? — was measured-directly instead:--```bash-$ curl -s -G 'http://127.0.0.1:8123/?database=openpanel&default_format=JSONCompact' \- --data-urlencode 'param_p1=abc' \- --data-urlencode "query=SELECT {p1:String} AS bound, '{cluster}' AS macro_left_alone"-[["abc","{cluster}"]]--$ curl -s -X POST 'http://127.0.0.1:8123/?database=openpanel_test¶m_p1=nope' \- --data-binary "DELETE FROM cohort_members ON CLUSTER '{cluster}' WHERE cohort_id = {p1:String}"-Code: 701. DB::Exception: Requested cluster 'openpanel_cluster' not found. (CLUSTER_DOESNT_EXIST)-```--Parameter substitution ignores `{cluster}` (no `:Type` suffix), and the second-call got all the way past parsing and substitution to the cluster lookup with-both a macro and a bound param in one statement. The non-clustered rendering-(`SELF_HOSTED=true`) is what §D8/D9 and §E executed.--## D8 / D9 — the two DELETE paths, executed--Executed on `openpanel_test`: V1 deleted cohort `m12004-a`, V2 deleted the-byte-identical fixture `m12004-b`, and `m12004-keep` had to survive both.--| | a_members | b_members | keep_members | a_metadata | b_metadata |-|---|---|---|---|---|---|-| before | 3 | 3 | 1 | 1 | 1 |-| after (V1 on a, V2 on b) | **0** | **0** | **1** | **0** | **0** |--Rendered (`SELF_HOSTED=true`, i.e. non-clustered):--```sql--- D8 updateCohortMembership, clickhouse_settings {"lightweight_deletes_sync":"1"} on both sides--- V1-DELETE FROM cohort_members WHERE cohort_id = 'm12004-a' AND project_id = 'm12004-proof'--- V2-DELETE FROM cohort_members WHERE cohort_id = {p1:String} AND project_id = {p2:String}--- V2 params: {"p1": "m12004-a", "p2": "m12004-proof"}---- D9 deleteCohortMembership, clickhouse_settings {"lightweight_deletes_sync":"0"} on both sides--- V1-DELETE FROM cohort_members WHERE cohort_id = 'x' AND project_id = 'y'-DELETE FROM cohort_metadata WHERE cohort_id = 'x' AND project_id = 'y'--- V2-DELETE FROM cohort_members WHERE cohort_id = {p1:String} AND project_id = {p2:String}-DELETE FROM cohort_metadata WHERE cohort_id = {p1:String} AND project_id = {p2:String}--- V2 params: {"p1": "x", "p2": "y"}-```--`storeCohortMembership` is untouched: it was already `ch.insert({table, values,-format: 'JSONEachRow'})` with no SQL text, and the capture confirms both sides-issue the same inserts (`cohort_metadata` × 1 with an empty member list,-`cohort_members` + `cohort_metadata` when there are members).--## Numeric bindings — which ClickHouse type, and why--There is no "the number type" (recipe, *Numbers*). Every numeric this module-binds, with the value's provenance:--| site | V1 emitted | V2 binds | why |-|---|---|---|---|-| `INTERVAL n DAY` (relative timeframe) | `INTERVAL 365 DAY` | `sql.uint64` | `n` comes from `/^(\d+)d$/` on a `z.enum(['7d','30d','90d','180d','365d'])` — never negative. Cases A1, D5/E5 |-| `HAVING countMerge(event_count) >= n` | `>= 3` | `sql.uint64` | `zFrequency.count` is `z.number().int().min(1)`. Cases A4–A6, A15 |-| `LIMIT` / `OFFSET` | `LIMIT 25` | `sql.uint64` | `COHORT_MATERIALIZE_LIMIT` is a validated positive int; the rpc's `limit`/`offset` are `z.number().int().min(0)`. Cases C22, C25, B3, E2, E4, E6 |-| `toFloat64OrNull(col) > n` | `> 55`, `> -1.5`, `> NaN` | `sql.float64` | the comparand is `Number(value[0])` — fractional, signed and `NaN` all reachable. Cases C11–C15 |--`sql.float64` is the correct type and not a cast-deleting shortcut: V1 wrote a-**bare** `${Number(v)}` here — not a quoted comparand fed to `toFloat64`, which-is the shape `chart/src/filter-where.ts` has and which is why *that* file binds-`String`. There is no cast to preserve, so `Float64` is the value's own type.-C15 pins the `NaN` end of it: the driver puts `NaN` on the wire as the literal-`nan`, ClickHouse parses it as a Float64 NaN, and every comparison is false —-the same 0 rows V1's bare `NaN` token returned.--The `UInt64` choices carry one real difference, recorded in §Behaviour changes-item 3.--## Behaviour changes--Three, all deliberate, none visible in any executed result set above.--### 1. A non-identifier profile column is now rejected, not inlined (ADR-013 R3)--V1's `profileColumnAccess` returned `profiles.<name>` **verbatim** for anything-that was not a `properties.` lookup — the site ADR-013 names as having "no guard-today". V2 routes it through `sql.id`, which throws. Measured 2026-09-07, both-sides called with the same filter name:--| filter `name` | V1 emitted / executed | V2 |-|---|---|---|-| `profile.email` | `argMax(profiles.email, …)` → **0 rows, no error** | identical text, `{p2:String}` comparand |-| `profile.foo.bar` | `argMax(profiles.foo.bar, …)` → **`UNKNOWN_IDENTIFIER` (47)** | `SqlIdentifierError: Refusing to inline identifier "profiles.foo.bar": more than 2 dot-separated parts` |-| `profile.email); DROP` | `HAVING (argMax(profiles.email); DROP, tuple(…` → **`SYNTAX_ERROR` (62)** | `SqlIdentifierError: … "email); DROP" is not a bare identifier` |--Every input V1 could actually *serve* is served identically; the inputs whose-behaviour changes are exactly the ones V1 turned into a ClickHouse error, and-V2 rejects them before the round trip. No `allowed` whitelist is passed, because-V1 had no closed column set here and adding one would drop filters V1 accepted.--### 2. `escapeDate` has no successor — and never applied here--Trap 1 of the recipe. This module never used clix, so no expression relied on-`escapeDate`'s implicit re-quoting; the two date-shaped values it handles-(`timeframe.start` / `timeframe.end`) were already inside explicit-`toDate('…')` calls in V1 and are inside `toDate({pN:String})` in V2 — cases A2-and A3, both IDENTICAL. `session_timezone` (trap 3) likewise does not arise:-no cohort statement went through clix, so none of them ever sent one, and none-sends one now. The only per-query settings in the module are-`PROFILE_COHORT_QUERY_SETTINGS` (unchanged, passed through — case C25) and the-two `lightweight_deletes_sync` values (unchanged — §D8/D9).--### 3. A negative `LIMIT` / `OFFSET` / frequency count now fails instead of returning a row--Measured 2026-09-07:--```-SELECT number FROM numbers(10) LIMIT -1 -> rows 1, [[9]] (V1's shape)-SELECT 1 LIMIT {p1:UInt64} with param_p1=-1 -> Code: 457. Value -1 cannot be- parsed as UInt64 … (BAD_QUERY_PARAMETER)-```--So ClickHouse **accepts** a negative literal `LIMIT` (it does not error, it-returns one row), while a negative `{p:UInt64}` is rejected at the server. This-is the recipe's stated intent — "a limit that went negative is a bug, not a-row" — and it is the only place a bound type is stricter than V1's literal.--Nothing in the module can reach it today: `COHORT_MATERIALIZE_LIMIT` is-`parsePositiveInt`-guarded, `getCohortMembers`' `limit`/`offset` are-`z.number().int().min(0)` on the rpc, and `zFrequency.count` is-`z.number().int().min(1)`. The one unvalidated path is-`updateCohortMembership`, which reads `cohort.definition` back out of Prisma's-JSON column and casts it without re-running zod — a `frequency.count` persisted-before that schema tightened would now fail loudly rather than quietly. No such-row exists here: the prod copy's only Postgres `cohort` row-(`cccccccc-0000-4000-8000-000000000001`) has `definition = {}`. Recorded rather-than guessed at.--## Tests that used to compare SQL text--`packages/core/src/modules/cohort/src/cohort-sql.test.ts` is the only-text-comparing test over this module. Every assertion in it now runs against-`toStatement()` — the rendered `query` plus `query_params` — and none changed-what it claims:--| test | before | after |-|---|---|---|-| `resolves the newest row per profile without FINAL` | `argMax(profiles.properties['experiment'], tuple(last_seen_at, cityHash64(profiles.properties['experiment'])))` | `argMax(profiles.properties[{p2:String}], tuple(last_seen_at, cityHash64(profiles.properties[{p3:String}])))` |-| `orders every aggregate by ONE shared row key` | same key text twice | same key text twice, with placeholders |-| `filters aggregates in HAVING, not WHERE` | unchanged (index comparison on the rendered query) | unchanged |-| `wraps plain columns too…` | unchanged | unchanged |-| `wraps numeric comparisons inside the cast` | `toFloat64OrNull(argMax(profiles.properties['age'], tuple(last_seen_at,` | `toFloat64OrNull(argMax(profiles.properties[{p2:String}], tuple(last_seen_at,` |-| `applies the limit` | `toContain('LIMIT 10')` | `toContain('LIMIT {p5:UInt64}')` **and** `query_params.p5 === 10` |-| `matches nothing when every filter was dropped as empty` | unchanged | unchanged |-| **`escapes quotes in user-controlled property keys`** → **`binds user-controlled property keys instead of escaping them`** | asserted the escaped literal `profiles.properties['pl\'an']` was present | asserts the key is **absent** from the SQL text, that the text reads `profiles.properties[{p2:String}]`, and that `pl'an` is among the bound params |--The last row is the one whose *assertion* had to change rather than merely-re-render: V1's claim ("the quote is escaped inside the literal") describes a-literal that no longer exists. The property it was protecting — a quote in a-user-controlled key cannot terminate a string — is now stronger and is what the-new assertion states. One test was **added**: `replicatedTarget renders exactly-what getReplicatedTableName produces`, which is what keeps the `ON CLUSTER`-rebuild from drifting from `shared/ch-tables.ts`.--`cohort.service.test.ts`, `cohort.rpc.test.ts` and `cohort.jobs.test.ts` assert-on behaviour, not text, and are unmodified.--## Reproducing a case with curl--Every V2 statement above is runnable as written; bind each `pN` as `param_pN`.-Array params go on the wire in ClickHouse's literal form-(`param_p1=['a','b']`), which is what `@clickhouse/client` sends. Case A7:--```bash-curl -s 'http://127.0.0.1:8123/?database=openpanel&default_format=JSONCompact' \- --data-binary "SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = 'secure-privacy' AND name = 'signed_up' AND event_date >= toDate(now() - INTERVAL 365 DAY) AND ((property_key = 'productName' AND property_value = 'Web Small'))" | tail -5--curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'default_format=JSONCompact' \- --data-urlencode 'param_p1=secure-privacy' --data-urlencode 'param_p2=signed_up' \- --data-urlencode 'param_p3=365' --data-urlencode 'param_p4=productName' \- --data-urlencode 'param_p5=Web Small' \- --data-urlencode "query=SELECT DISTINCT profile_id FROM event_property_profile_summary_mv WHERE project_id = {p1:String} AND name = {p2:String} AND event_date >= toDate(now() - INTERVAL {p3:UInt64} DAY) AND ((property_key = {p4:String} AND property_value = {p5:String}))" | tail -5-```--Both return 810 rows.--## P12 grep gate--```-$ bash tooling/gates/p12-grep-gates.sh --report | grep cohort-(no line — packages/core/src/modules/cohort/** scores 0 in every column)--before (54c4fe7a): 46 sqlstring, 0 clix, 0 sql-builder cohort.service.ts-after: (absent from the report)-TOTAL sqlstring 82 → 36 clix 73 → 73 sql-builder 6 → 6-```--Nothing else moved. The one surviving `sqlstring` token in the module is the-word inside this file's and the service's header comments, which the gate does-not count.--## M36-005 — the window on `mostEvents` / `popularRoutes` (2026-09-16)--**What changed.** `cohortMemberEventsQuery` / `cohortMemberRoutesQuery` (now-pure builders, pinned by `src/cohort-activity-sql.test.ts`) add-`AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String})`-after `project_id`. `cohort.mostEvents` / `cohort.popularRoutes` accept the-report vocabulary's `range` / `startDate` / `endDate`, and `range` defaults to-**`3m`**. The cohort detail route passes no range, so every user gets `3m`. The-`IN (subquery)` on `cohort_members` is unchanged (see §Distribution). The-window changes no distribution semantics.--**Method.** The HEAD service file was copied into the module, and both it and-the new one were called in one Bun process against a fake `deps.ch` that-recorded `{query, query_params}`. No statement was retyped. The copy was deleted-afterwards. Each statement then ran against the local prod copy through the-HTTP interface, with `database=openpanel` and `use_query_condition_cache=0`.-The only edit was `FROM cohort_members`, which was qualified to a scratch-database, the same cross-database method as `UNPROVEN_ENDPOINTS_RAW.md` §3.3.-The numbers come from `X-ClickHouse-Summary`. Each statement ran 3 times,-interleaved, and the median is shown. Rows and bytes did not vary between runs.-The run was on 2026-09-16, 15:29–15:32 UTC.--**Cohorts.** `cohort_members` is empty in the prod copy, so real profile ids-were written to a scratch database, `openpanel_m36005` (dropped afterwards).-`openpanel` was only read: `events` = 321,192,037 before and after. Each anchor-got two cohorts:--- `spread-1000`: 1,000 ids in `cityHash64` order, spread across the project.-- `heavy-1000`: the 1,000 ids with the most events. This is the skew a real- predicate-selected cohort has.--`bayse` also used M33's 10,000-member cohort (`openpanel_m33`, read only). Ids-are identified ones (`profile_id != device_id`). `chatpaper` has no identified-profiles, so it uses anonymous ids. **`website-8103` could not be measured:**-every event has `profile_id = ''`, so no cohort there can match an event.--**The caveat this copy forces (the same one M31-003 hit).** Every anchor's-events span 2026-07-01 → 2026-08-25, about 8 weeks. That is inside any `3m`-window, whether it is anchored on today (`2026-06-16 → 2026-09-17`, what the-code produced) or on the copy's last day (`2026-05-25 → 2026-08-26`, what a live-server would read). **So at the default the window prunes nothing here.** The-`30d` and `7d` columns (anchored on the copy's last day) show what the window-buys once a tenant is older than it. On a live tenant older than three months,-the default moves from the "default" column toward those columns. No project on-this box can show that directly.--### Cost: rows read, then median wall time--| statement | project, cohort | unbounded (before) | default `3m` (after) | `30d` | `7d` |-|---|---|---|---|---|---|-| events | `bayse`, spread-1000 | 38,253,027 / 663 ms | 38,253,027 / 978 ms | 17,060,606 / 461 ms | 5,256,379 / 147 ms |-| events | `bayse`, heavy-1000 | 38,253,027 / 908 ms | 38,253,027 / 1,261 ms | 17,060,606 / 571 ms | 5,256,379 / 193 ms |-| events | `bayse`, M33 10,000 | 38,257,027 / 897 ms | 38,257,027 / 1,258 ms | 17,064,606 / 569 ms | 5,260,379 / 189 ms |-| routes | `bayse`, spread-1000 | 38,253,027 / 485 ms | 38,253,027 / 650 ms | 17,060,606 / 311 ms | 5,256,379 / 97 ms |-| routes | `bayse`, heavy-1000 | 38,253,027 / 592 ms | 38,253,027 / 760 ms | 17,060,606 / 362 ms | 5,256,379 / 113 ms |-| routes | `bayse`, M33 10,000 | 38,257,027 / 588 ms | 38,257,027 / 773 ms | 17,064,606 / 364 ms | 5,260,379 / 118 ms |-| events | `verdict`, spread-1000 | 44,170,383 / 841 ms | 44,170,383 / 1,124 ms | 23,202,147 / 635 ms | 4,827,286 / 150 ms |-| events | `verdict`, heavy-1000 | 44,170,383 / 887 ms | 44,170,383 / 1,151 ms | 23,202,147 / 635 ms | 4,827,286 / 146 ms |-| routes | `verdict`, both | 2,731,360 / 34–40 ms | 2,731,360 / 39–42 ms | 1,520,694 / 29–30 ms | 423,728 / 13–15 ms |-| events | `earlysalary-production`, spread-1000 | 26,793,684 / 481 ms | 26,793,684 / 697 ms | 15,472,396 / 411 ms | 3,471,150 / 100 ms |-| events | `earlysalary-production`, heavy-1000 | 26,793,684 / 510 ms | 26,793,684 / 720 ms | 15,472,396 / 424 ms | 3,471,150 / 101 ms |-| routes | `earlysalary-production`, both | 26,793,684 / 407 ms | 26,793,684 / 514–526 ms | 15,472,396 / 310–312 ms | 3,471,150 / 76–80 ms |-| events | `chatpaper`, both | 19,804,629 / 183–187 ms | 19,804,629 / 246–254 ms | 13,515,386 / 171–176 ms | 2,669,273 / 49–51 ms |-| routes | `chatpaper`, spread-1000 | 19,804,629 / 717 ms | 19,804,629 / 805 ms | 13,515,386 / 563 ms | 2,669,273 / 115 ms |-| routes | `chatpaper`, heavy-1000 | 19,804,629 / 681 ms | 19,804,629 / 778 ms | 13,515,386 / 562 ms | 2,669,273 / 117 ms |--(`verdict` has no `screen_view` events. `earlysalary-production` has none for-these cohorts. Their `routes` rows return 0 rows either way.)--Bytes read, `bayse` spread-1000 events: 1,662 MiB unbounded, 1,948 MiB at the-default, 862 MiB at `30d`, 260 MiB at `7d`.--**Read plainly:**--- **On this copy the default is a cost, not a saving.** The `BETWEEN` adds- `created_at` to the columns read and prunes nothing. That makes the default- **12–48 % slower** at the same row count: `bayse` events is 663 → 978 ms,- +286 MiB read. M31-003 measured the same floor price on `powerUsers`.-- **The saving appears once the window is narrower than the history.**- - At `30d`, `bayse` reads **2.2× fewer rows**.- - At `7d` it reads **7.3× fewer** and runs **4.5× faster** than unbounded.- - `verdict` events at `7d`: 44.2 M → 4.8 M rows, 841 → 150 ms.-- **The guarantee is the point.** After this change, neither statement can read- more than three months of a tenant's events. Before it, they read all of- them, and the cost grew with the tenant's age.--### What a user sees — result sets, on real anchors--**At the default, nothing changes on any anchor.** The window covers all the-data, so the answer must be the same. It is, and this was checked on the full-**un-`LIMIT`ed** `GROUP BY` result:-`count(), sum(cityHash64(key, count))` gave identical row counts and hashes for--- `bayse` spread-1000 events (108 names),-- `verdict` spread-1000 events (36),-- `earlysalary-production` heavy-1000 events (64),-- `chatpaper` spread-1000 routes (5,139 paths),-- `chatpaper` heavy-1000 routes (148,452 paths).--The shipped top-10 was also identical in order and counts on every other-default-window cell in the cost table, with one exception, explained next.--**One apparent difference is a pre-existing tie, not this change.**-`chatpaper` heavy-1000 routes at the default kept 8 of its 10 paths. Its counts-at ranks 8–12 are all `3`, and `ORDER BY count DESC` has no tiebreak.-**Five runs of the unchanged, unbounded statement returned 5 different-orderings.** The full result set is identical (above). `popularRoutes` and-`mostEvents` are therefore already nondeterministic at a tie on the `LIMIT`-boundary, like `powerUsersQuery` (M31-003). Never compare them by ordered rows.-This change touches no `ORDER BY`.--**What a user would see if the window did bite.** This is the `3m` default's-effect on a tenant with more than three months of history, approximated with-narrower windows on this copy. Each cell is how many of the unbounded top-10-entries survive:--| cohort | `30d` | `7d` |-|---|---|---|-| `bayse` spread-1000, events / routes | 7 of 10 / 8 of 10 | 8 / 6 |-| `bayse` heavy-1000, events / routes | 8 / 8 | 7 / 8 |-| `bayse` M33 10,000, events / routes | 7 / 9 | 6 / 8 |-| `verdict` spread-1000 / heavy-1000, events | 9 / 10 (same set, reordered) | 9 / 9 |-| `earlysalary-production` spread-1000 / heavy-1000, events | 10 (reordered) / 8 | 9 / 8 |-| `chatpaper` spread-1000 / heavy-1000, routes | 8 / 7 | 4 / 1 (tie-dominated, see above) |-| `chatpaper` spread-1000, events | 0 of 1: its only non-`screen_view` event is older than 30 d | 0 of 1 |--The top entry was the same in every `30d` cell except that last one. At `7d`,-it also changed for `verdict` events and `chatpaper` heavy-1000 routes.--**What the page shows differently.** The two cards read "Popular events" and-"Most visted pages" (sic), with no time label either before or after. They now-count the member's activity in the last three months, not all time:--- **Any tenant or cohort whose events all fall inside three months:**- identical, as measured above.-- **Older tenants:** the counts are smaller, and the ranking reflects recent- activity. A cohort whose members were active only more than three months ago- shows empty cards. That is the `chatpaper` 0-of-1 case, at a shorter window.-- The "Events per day" chart beside the cards is still 30 days, and was not- changed.--M36-005 did not change the page to name the window. `apps/start` is outside the-task's scope.--### Golden prediction--**Zero golden cases change.** No `verification/golden` case reaches these-statements, for three reasons:--- The 137 cases replay REST routes.-- `cohort.mostEvents` and `cohort.popularRoutes` are tRPC-only. Their only- callers are `cohort.rpc.ts` and the cohort detail route.-- The capture's `dataset.emptyTables` lists `cohort_members`.--The one case whose id contains "cohort", `insights-retention-cohort`, is served-by `chart/retention.service`, which this change does not touch.diff --git a/packages/core/src/modules/cohort/src/cohort-sql.test.ts b/packages/core/src/modules/cohort/src/cohort-sql.test.tsindex c7412ce6e..0d4f78cfd 100644--- a/packages/core/src/modules/cohort/src/cohort-sql.test.ts+++ b/packages/core/src/modules/cohort/src/cohort-sql.test.ts@@ -17,8 +17,7 @@// finished string. The assertions themselves are unchanged in what they// claim, except the one about quotes in a user-controlled property key: a// quote no longer needs escaping because the key is not in the SQL text at-// all, so that test asserts the binding instead. Listed in-// ../cohort.sql.proof.md.+// all, so that test asserts the binding instead.//// V1's `PROFILE_COHORT_QUERY_SETTINGS` test used `vi.resetModules()` +// `vi.stubEnv()` to re-import the module under different env vars — thediff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.tsindex 44c79e6e4..663e25359 100644--- a/packages/core/src/modules/event/event.service.ts+++ b/packages/core/src/modules/event/event.service.ts@@ -1,31 +1,6 @@-// Ported from packages/db/src/services/event.service.ts and the query bodies-// of packages/trpc/src/routers/event.ts (M7-002). The db file is now a-// re-export shim over this one, so @openpanel/db importers (packages/trpc,-// apps/api's export controller and bot hook, the buffers' types,-// notification.service, the mcp/assistant tools) keep working while V1 runs-// (DELEGATE PATTERN).-//-// Every query is a `sql` fragment (src/sql.ts), converted one at a time-// with a result-set proof each, per ADR-013. The two filter compilers-// (`getEventFiltersWhereClause`, `buildFilterWhere`) are NOT converted here —-// they are shared and out of this task's scope; src/filter-clauses.ts is the-// one bridge.-//-// Not ported: V1's `EventService.query` / `EventService.getList` (a clix-// builder over events + profiles + sessions) — nothing in the repo calls-// them; `eventService.getById` is `getEventById` below. `GetEventListOptions.-// custom(sb)` — its only caller (event.conversions) is the typed-// `conversionNames` option instead, since there is no builder to hand out.-//-// M10-005: every function that touches a database takes `ServiceDeps` and-// reaches Postgres as `deps.db`, ClickHouse as `deps.ch` (through-// ch-query.ts) and the event/bot buffers as `deps.buffers.*`. The-// `loadDb` / `loadChClient` / `loadDbBuffers` lazy loaders are gone, and so-// are the two `import('@openpanel/core')` self-barrel hops this file made for-// `resolveDateRange` — imported straight from `shared/`-// (docs/TECH_DEBT.md §2, §4). M15-202 removed the last three lazy loaders-// here: the filter compiler and `getCache` are plain static imports, and the-// session lookup arrives through the composition root's thunk (ADR-022 R3).+// The event read path. Every query is a `sql` fragment (src/sql.ts), per+// ADR-013; the two filter compilers (`getEventFiltersWhereClause`,+// `buildFilterWhere`) are shared, and src/filter-clauses.ts is the bridge.import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';import type { EventMeta, Prisma } from '@openpanel/db/src/prisma-client';diff --git a/packages/core/src/modules/event/src/sql.proof.md b/packages/core/src/modules/event/src/sql.proof.mddeleted file mode 100644index 0bbf9ae3e..000000000--- a/packages/core/src/modules/event/src/sql.proof.md+++ /dev/null@@ -1,686 +0,0 @@-# sql.ts (formerly event.sql.ts) — V1 → V2 result-set proof (M7-002)--Every query builder in `sql.ts` was executed twice against the same data — once as V1 (the `git HEAD` service/router code, `3300f2a0`) and once as V2 (core's service, which renders the builder) — through one patched ClickHouse client that captured each statement, its `query_params`, `clickhouse_settings`, wall time and the raw JSON response. The two responses were compared on `data` (every row, every column, as JSON) and `meta` (column names and types). Statements without an `ORDER BY` were compared as row sets, because ClickHouse's parallel aggregation returns them in a different order run to run — V1 against itself too.--- **Amended by M27-002 (2026-09-15): `eventListQuery`'s ORDER BY is no longer V1's text.** V1 spells it- `ORDER BY created_at DESC, id ASC`. The `events` sort key is- `(project_id, toDate(created_at), created_at, name)`, and ClickHouse will not bridge the monotonic- `toDate` wrapper on its own, so that spelling reads the whole window and sorts it- (`docs/ANALYTICS_PERFORMANCE.md` §6.4). It now reads- `ORDER BY toDate(created_at) DESC, created_at DESC, id ASC`, which is the key's own prefix. `toDate` is- monotonic in `created_at`, so the total order — including the `id` tiebreak — is unchanged. The 31 `-- V2`- renders below carry the amended text; the `-- V1` lines are left as V1 wrote them, so each pair now- differs by exactly that clause. Re-proved against the local prod copy on **2026-09-15**,- `use_query_condition_cache=0`, `max_memory_usage=6 GiB`, numbers off `X-ClickHouse-Summary`:- - **Result sets:** the full default projection (all 30 `EVENT_LIST_COLUMNS`), both spellings run as- `FORMAT TSVRaw` and compared by `sha256sum` — which compares emitted bytes *and* row order — over- 5 projects (`verdict`, `bayse`, `earlysalary-production`, `website-8103`, `chatpaper`) × 3 windows- (1 d / 7 d / 30 d) × 2 page sizes (50, 500): **identical, 30/30**.- - **Cost, 30-day window, `LIMIT 50`, `read_rows` / `elapsed_ns`:** `verdict` 23,001,347 rows / 1,303 ms- -> **2,496,245 rows / 89 ms** · `bayse` 16,858,438 / 762 ms -> 2,162,391 / 64 ms ·- `earlysalary-production` 15,269,819 / 696 ms -> 1,998,830 / 75 ms · `website-8103` 12,232,245 / 540 ms- -> 2,007,353 / 66 ms · `chatpaper` 13,320,063 / 623 ms -> 1,982,384 / 57 ms.- - The per-statement `rows_read V1/V2` and `wall V1/V2` figures below are from the 2026-09-04 run and- therefore describe the pre-amendment V2 text.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static), project `redcollege` unless noted; cases needing rows the prod-copy lacks (`cohort_members`, `events_bots` are empty there) also ran on the isolated `openpanel_test` database with 3,380 events copied from `redcollege` under project `m7-002-proof`, plus seeded cohort/bot rows (deleted afterwards).-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are directional only; production is 2 shards × 2 replicas (`docs/ENVIRONMENT.md`). `rows_read` differences on JOIN statements are ClickHouse's per-run accounting of the right-hand side, not a plan difference: the SQL text is identical up to `{pN:Type}` binding.-- **Verdict**: 26 cases / 51 statements, all IDENTICAL. No conversion changed a result set.--The harness was a throwaway script (it needed verbatim copies of the V1 sources next to V2); each statement below is complete and reproducible with `curl http://127.0.0.1:8123/?database=openpanel`, binding the V2 params as `param_pN=`.--### eventListQuery — date cursor, default columns, no lookups--**statement 1** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 42.7 ms / 10.8 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 0.5 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p5:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":0.5,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":50}-```--**statement 2** — IDENTICAL; rows V1/V2 = 50/50; rows_read V1/V2 = 24575/24575; wall V1/V2 = 27.3 ms / 18.8 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 1 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p5:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":1,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":50}-```--### eventListQuery — numeric cursor page 2, every column, date range--**statement** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 73721/73721; wall V1/V2 = 23.2 ms / 21.1 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, properties, country, city, region, longitude, latitude, os, os_version, browser, browser_version, device, brand, model, path, origin, referrer, referrer_name, referrer_type, imported_at, sdk_name, sdk_version, revenue, groups FROM events e WHERE project_id = 'redcollege' AND toDate(created_at) BETWEEN toDate('2026-08-15 00:00:00') AND toDate('2026-08-20 23:59:59') ORDER BY created_at DESC, id ASC LIMIT 20 OFFSET 40--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, properties, country, city, region, longitude, latitude, os, os_version, browser, browser_version, device, brand, model, path, origin, referrer, referrer_name, referrer_type, imported_at, sdk_name, sdk_version, revenue, groups FROM events e WHERE project_id = {p1:String} AND toDate(created_at) BETWEEN toDate({p2:String}) AND toDate({p3:String}) ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p4:UInt64} OFFSET {p5:UInt64}--- V2 params: {"p1":"redcollege","p2":"2026-08-15 00:00:00","p3":"2026-08-20 23:59:59","p4":20,"p5":40}-```--### eventListQuery — profile (identity stitching) + events + sessionId--**statement 1** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 122874/122874; wall V1/V2 = 31.2 ms / 20.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-26 00:00:00', 3) - INTERVAL 0.5 DAY AND created_at < '2026-08-26 00:00:00' AND project_id = 'redcollege' AND ((device_id IN (SELECT device_id as did FROM events WHERE project_id = 'redcollege' AND device_id != '' AND profile_id = '107145' group by did) AND profile_id = device_id) OR profile_id = '107145') AND session_id = '0kiE1SjOk6U6_WDCbuyLeQ' AND name IN ('screen_view','link_out') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND ((device_id IN (SELECT device_id as did FROM events WHERE project_id = {p5:String} AND device_id != '' AND profile_id = {p6:String} group by did) AND profile_id = device_id) OR profile_id = {p7:String}) AND session_id = {p8:String} AND name IN {p9:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p10:UInt64}--- V2 params: {"p1":"2026-08-26 00:00:00","p2":0.5,"p3":"2026-08-26 00:00:00","p4":"redcollege","p5":"redcollege","p6":"107145","p7":"107145","p8":"0kiE1SjOk6U6_WDCbuyLeQ","p9":["screen_view","link_out"],"p10":50}-```--**statement 2** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 163832/163832; wall V1/V2 = 22.5 ms / 27.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-26 00:00:00', 3) - INTERVAL 1 DAY AND created_at < '2026-08-26 00:00:00' AND project_id = 'redcollege' AND ((device_id IN (SELECT device_id as did FROM events WHERE project_id = 'redcollege' AND device_id != '' AND profile_id = '107145' group by did) AND profile_id = device_id) OR profile_id = '107145') AND session_id = '0kiE1SjOk6U6_WDCbuyLeQ' AND name IN ('screen_view','link_out') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND ((device_id IN (SELECT device_id as did FROM events WHERE project_id = {p5:String} AND device_id != '' AND profile_id = {p6:String} group by did) AND profile_id = device_id) OR profile_id = {p7:String}) AND session_id = {p8:String} AND name IN {p9:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p10:UInt64}--- V2 params: {"p1":"2026-08-26 00:00:00","p2":1,"p3":"2026-08-26 00:00:00","p4":"redcollege","p5":"redcollege","p6":"107145","p7":"107145","p8":"0kiE1SjOk6U6_WDCbuyLeQ","p9":["screen_view","link_out"],"p10":50}-```--**statement 3** — IDENTICAL; rows V1/V2 = 50/50; rows_read V1/V2 = 180215/180215; wall V1/V2 = 32.7 ms / 32.4 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-26 00:00:00', 3) - INTERVAL 2 DAY AND created_at < '2026-08-26 00:00:00' AND project_id = 'redcollege' AND ((device_id IN (SELECT device_id as did FROM events WHERE project_id = 'redcollege' AND device_id != '' AND profile_id = '107145' group by did) AND profile_id = device_id) OR profile_id = '107145') AND session_id = '0kiE1SjOk6U6_WDCbuyLeQ' AND name IN ('screen_view','link_out') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND ((device_id IN (SELECT device_id as did FROM events WHERE project_id = {p5:String} AND device_id != '' AND profile_id = {p6:String} group by did) AND profile_id = device_id) OR profile_id = {p7:String}) AND session_id = {p8:String} AND name IN {p9:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p10:UInt64}--- V2 params: {"p1":"2026-08-26 00:00:00","p2":2,"p3":"2026-08-26 00:00:00","p4":"redcollege","p5":"redcollege","p6":"107145","p7":"107145","p8":"0kiE1SjOk6U6_WDCbuyLeQ","p9":["screen_view","link_out"],"p10":50}-```--### eventListQuery — groupId + profile.* filter (profile join)--**statement 1** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 16.6 ms / 10.9 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'redcollege') as profile on profile.id = profile_id WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 0.5 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND has(groups, '395') AND profile.properties['cargo'] = 'Profesora' ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = {p1:String}) as profile on profile.id = profile_id WHERE created_at >= toDateTime64({p2:String}, 3) - INTERVAL {p3:Float64} DAY AND created_at < {p4:String} AND project_id = {p5:String} AND has(groups, {p6:String}) AND profile.properties['cargo'] = 'Profesora' ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p7:UInt64}--- V2 params: {"p1":"redcollege","p2":"2026-08-24 00:00:00","p3":0.5,"p4":"2026-08-24 00:00:00","p5":"redcollege","p6":"395","p7":50}-```--**statement 2** — IDENTICAL; rows V1/V2 = 50/50; rows_read V1/V2 = 130794/130794; wall V1/V2 = 71.3 ms / 52.1 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'redcollege') as profile on profile.id = profile_id WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 1 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND has(groups, '395') AND profile.properties['cargo'] = 'Profesora' ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = {p1:String}) as profile on profile.id = profile_id WHERE created_at >= toDateTime64({p2:String}, 3) - INTERVAL {p3:Float64} DAY AND created_at < {p4:String} AND project_id = {p5:String} AND has(groups, {p6:String}) AND profile.properties['cargo'] = 'Profesora' ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p7:UInt64}--- V2 params: {"p1":"redcollege","p2":"2026-08-24 00:00:00","p3":1,"p4":"2026-08-24 00:00:00","p5":"redcollege","p6":"395","p7":50}-```--### eventListQuery — groupId + group.* filter (group array join)--**statement 1** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 3359/3359; wall V1/V2 = 10.3 ms / 12.2 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'redcollege') AS _g ON _g.id = _group_id WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 0.5 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND has(groups, '271') AND _g.type = 'establecimiento' ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) AS _g ON _g.id = _group_id WHERE created_at >= toDateTime64({p2:String}, 3) - INTERVAL {p3:Float64} DAY AND created_at < {p4:String} AND project_id = {p5:String} AND has(groups, {p6:String}) AND _g.type = 'establecimiento' ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p7:UInt64}--- V2 params: {"p1":"redcollege","p2":"2026-08-24 00:00:00","p3":0.5,"p4":"2026-08-24 00:00:00","p5":"redcollege","p6":"271","p7":50}-```--**statement 2** — IDENTICAL; rows V1/V2 = 50/50; rows_read V1/V2 = 11551/11551; wall V1/V2 = 14.5 ms / 12.8 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'redcollege') AS _g ON _g.id = _group_id WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 1 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND has(groups, '271') AND _g.type = 'establecimiento' ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) AS _g ON _g.id = _group_id WHERE created_at >= toDateTime64({p2:String}, 3) - INTERVAL {p3:Float64} DAY AND created_at < {p4:String} AND project_id = {p5:String} AND has(groups, {p6:String}) AND _g.type = 'establecimiento' ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p7:UInt64}--- V2 params: {"p1":"redcollege","p2":"2026-08-24 00:00:00","p3":1,"p4":"2026-08-24 00:00:00","p5":"redcollege","p6":"271","p7":50}-```--### eventListQuery — profile.* AND group.* filters together (V1 error parity)--Both sides raise the same ClickHouse error (V1 has always failed this input; V2 must fail identically, not "fix" it):--- **v1**: `JOIN ANY LEFT JOIN ... ON profile.id = profile_id ambiguous identifier 'id'. In scope SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events AS e ANY LEFT JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'redcollege'`-- **v2**: `JOIN ANY LEFT JOIN ... ON profile.id = profile_id ambiguous identifier 'id'. In scope SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events AS e ANY LEFT JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'redcollege'`--### eventListQuery — cohortId + conversions name list (event.conversions)--**statement 1** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 15.6 ms / 10.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 0.5 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":0.5,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 2** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 16.1 ms / 9.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 1 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":1,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 3** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 14.6 ms / 10.1 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 2 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":2,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 4** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 15.3 ms / 11.5 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 4 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":4,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 5** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 16.7 ms / 14.8 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 8 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":8,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 6** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 15.6 ms / 13.2 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 16 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":16,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 7** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 14.0 ms / 15.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 32 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":32,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 8** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 15.1 ms / 14.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 64 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":64,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 9** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 18.3 ms / 14.1 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 128 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":128,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 10** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 12.3 ms / 14.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 256 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":256,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 11** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 13.0 ms / 14.2 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 512 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":512,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 12** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 14.6 ms / 14.0 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 1024 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":1024,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--**statement 13** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 13.3 ms / 14.3 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 1825 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":1825,"p3":"2026-08-24 00:00:00","p4":"redcollege","p5":"cohort-1","p6":"redcollege","p7":["link_out","banner_click"],"p8":50}-```--The prod-copy has no rows for this case (empty `cohort_members` / `events_bots`), so the same case also ran on the seeded `openpanel_test` copy:--### eventListQuery — cohortId + conversions name list (event.conversions)--_Database: `openpanel_test`._--**statement 1** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 3383/3383; wall V1/V2 = 50.5 ms / 8.3 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 0.5 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'm7-002-proof' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'm7-002-proof') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":0.5,"p3":"2026-08-24 00:00:00","p4":"m7-002-proof","p5":"cohort-1","p6":"m7-002-proof","p7":["link_out","banner_click"],"p8":50}-```--**statement 2** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 6763/6763; wall V1/V2 = 9.9 ms / 8.8 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-08-24 00:00:00', 3) - INTERVAL 1 DAY AND created_at < '2026-08-24 00:00:00' AND project_id = 'm7-002-proof' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'm7-002-proof') AND name IN ('link_out','banner_click') ORDER BY created_at DESC, id ASC LIMIT 50--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p5:String} AND project_id = {p6:String}) AND name IN {p7:Array(String)} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p8:UInt64}--- V2 params: {"p1":"2026-08-24 00:00:00","p2":1,"p3":"2026-08-24 00:00:00","p4":"m7-002-proof","p5":"cohort-1","p6":"m7-002-proof","p7":["link_out","banner_click"],"p8":50}-```--### eventListQuery — no cursor, no range (lookback doubling until rows)--**statement 1** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 6.5 ms / 6.9 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-09-04 06:37:07', 3) - INTERVAL 0.5 DAY AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 10--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND project_id = {p3:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p4:UInt64}--- V2 params: {"p1":"2026-09-04 06:37:07","p2":0.5,"p3":"redcollege","p4":10}-```--**statement 2** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 1878/0; wall V1/V2 = 6.8 ms / 6.6 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-09-04 06:37:07', 3) - INTERVAL 1 DAY AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 10--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND project_id = {p3:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p4:UInt64}--- V2 params: {"p1":"2026-09-04 06:37:07","p2":1,"p3":"redcollege","p4":10}-```--**statement 3** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 7284/0; wall V1/V2 = 9.6 ms / 10.6 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-09-04 06:37:07', 3) - INTERVAL 2 DAY AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 10--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND project_id = {p3:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p4:UInt64}--- V2 params: {"p1":"2026-09-04 06:37:07","p2":2,"p3":"redcollege","p4":10}-```--**statement 4** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 7284/0; wall V1/V2 = 8.8 ms / 15.7 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-09-04 06:37:07', 3) - INTERVAL 4 DAY AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 10--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND project_id = {p3:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p4:UInt64}--- V2 params: {"p1":"2026-09-04 06:37:07","p2":4,"p3":"redcollege","p4":10}-```--**statement 5** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 7284/0; wall V1/V2 = 10.0 ms / 9.6 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-09-04 06:37:07', 3) - INTERVAL 8 DAY AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 10--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND project_id = {p3:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p4:UInt64}--- V2 params: {"p1":"2026-09-04 06:37:07","p2":8,"p3":"redcollege","p4":10}-```--**statement 6** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 113773/81914; wall V1/V2 = 17.3 ms / 18.1 ms; clickhouse_settings same.--```sql--- V1-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64('2026-09-04 06:37:07', 3) - INTERVAL 16 DAY AND project_id = 'redcollege' ORDER BY created_at DESC, id ASC LIMIT 10--- V2-SELECT created_at, project_id, id, name, device_id, profile_id, session_id, country, city, os, browser, path FROM events e WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND project_id = {p3:String} ORDER BY toDate(created_at) DESC, created_at DESC, id ASC LIMIT {p4:UInt64}--- V2 params: {"p1":"2026-09-04 06:37:07","p2":16,"p3":"redcollege","p4":10}-```--### eventsCountQuery — plain project--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 65533/65533; wall V1/V2 = 10.8 ms / 9.5 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events e WHERE project_id = 'redcollege'--- V2-SELECT count(*) as count FROM events e WHERE project_id = {p1:String}--- V2 params: {"p1":"redcollege"}-```--Result (first rows, identical on both sides): `[{"count":126190}]`--### eventsCountQuery — profileId + groupId + range + events + profile.* filter--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 155365/155365; wall V1/V2 = 61.1 ms / 40.5 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'redcollege') as profile on profile.id = profile_id WHERE project_id = 'redcollege' AND profile_id = '107145' AND has(groups, '271') AND toDate(created_at) BETWEEN toDate('2026-08-15 00:00:00') AND toDate('2026-08-20 23:59:59') AND name IN ('screen_view') AND profile.properties['cargo'] = 'Profesora'--- V2-SELECT count(*) as count FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = {p1:String}) as profile on profile.id = profile_id WHERE project_id = {p2:String} AND profile_id = {p3:String} AND has(groups, {p4:String}) AND toDate(created_at) BETWEEN toDate({p5:String}) AND toDate({p6:String}) AND name IN {p7:Array(String)} AND profile.properties['cargo'] = 'Profesora'--- V2 params: {"p1":"redcollege","p2":"redcollege","p3":"107145","p4":"271","p5":"2026-08-15 00:00:00","p6":"2026-08-20 23:59:59","p7":["screen_view"]}-```--Result (first rows, identical on both sides): `[{"count":0}]`--### eventsCountQuery — group.* filter (group array join)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 159000/159000; wall V1/V2 = 11.6 ms / 12.0 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'redcollege') AS _g ON _g.id = _group_id WHERE project_id = 'redcollege' AND _g.type = 'establecimiento'--- V2-SELECT count(*) as count FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p1:String}) AS _g ON _g.id = _group_id WHERE project_id = {p2:String} AND _g.type = 'establecimiento'--- V2 params: {"p1":"redcollege","p2":"redcollege"}-```--Result (first rows, identical on both sides): `[{"count":100146}]`--### eventsCountQuery — profile.* AND group.* filters together (V1 error parity)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 281602/281602; wall V1/V2 = 67.1 ms / 56.7 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'redcollege') as profile on profile.id = profile_id ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'redcollege') AS _g ON _g.id = _group_id WHERE project_id = 'redcollege' AND profile.properties['cargo'] = 'Profesora' AND _g.type = 'establecimiento'--- V2-SELECT count(*) as count FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = {p1:String}) as profile on profile.id = profile_id ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {p2:String}) AS _g ON _g.id = _group_id WHERE project_id = {p3:String} AND profile.properties['cargo'] = 'Profesora' AND _g.type = 'establecimiento'--- V2 params: {"p1":"redcollege","p2":"redcollege","p3":"redcollege"}-```--Result (first rows, identical on both sides): `[{"count":6066}]`--### eventsCountQuery — cohortId--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 9.6 ms / 9.8 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events e WHERE project_id = 'redcollege' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'redcollege')--- V2-SELECT count(*) as count FROM events e WHERE project_id = {p1:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String})--- V2 params: {"p1":"redcollege","p2":"cohort-1","p3":"redcollege"}-```--Result (first rows, identical on both sides): `[{"count":0}]`--The prod-copy has no rows for this case (empty `cohort_members` / `events_bots`), so the same case also ran on the seeded `openpanel_test` copy:--### eventsCountQuery — cohortId--_Database: `openpanel_test`._--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3383/3383; wall V1/V2 = 6.4 ms / 7.2 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events e WHERE project_id = 'm7-002-proof' AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = 'cohort-1' AND project_id = 'm7-002-proof')--- V2-SELECT count(*) as count FROM events e WHERE project_id = {p1:String} AND profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id = {p2:String} AND project_id = {p3:String})--- V2 params: {"p1":"m7-002-proof","p2":"cohort-1","p3":"m7-002-proof"}-```--Result (first rows, identical on both sides): `[{"count":2019}]`--### topPagesQuery — page 2 with search--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 179309/179309; wall V1/V2 = 33.4 ms / 36.4 ms; clickhouse_settings same.--```sql--- V1-SELECT path, count(*) as count, project_id, first_value(created_at) as first_seen, last_value(properties['__title']) as title, origin FROM events WHERE name = 'screen_view' AND project_id = 'redcollege' AND created_at > now() - INTERVAL 30 DAY AND path ILIKE '%libro%' GROUP BY path, project_id, origin ORDER BY count desc LIMIT 10 OFFSET 10--- V2-SELECT path, count(*) as count, project_id, first_value(created_at) as first_seen, last_value(properties['__title']) as title, origin FROM events WHERE name = 'screen_view' AND project_id = {p1:String} AND created_at > now() - INTERVAL {p2:UInt64} DAY AND path ILIKE {p3:String} GROUP BY path, project_id, origin ORDER BY count desc LIMIT {p4:UInt64} OFFSET {p5:UInt64}--- V2 params: {"p1":"redcollege","p2":30,"p3":"%libro%","p4":10,"p5":10}-```--Result (first rows, identical on both sides): `[{"path":"/83/2026/libros","count":522,"project_id":"redcollege","first_seen":"2026-08-11 13:33:59.234","title":"RedCollege | Libro de Clases","origin":"https://libro.redcollege.net"},{"path":"/63/202`--### topPagesQuery — first page, no search--**statement** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 179309/179309; wall V1/V2 = 30.6 ms / 32.4 ms; clickhouse_settings same.--```sql--- V1-SELECT path, count(*) as count, project_id, first_value(created_at) as first_seen, last_value(properties['__title']) as title, origin FROM events WHERE name = 'screen_view' AND project_id = 'redcollege' AND created_at > now() - INTERVAL 30 DAY GROUP BY path, project_id, origin ORDER BY count desc LIMIT 20 OFFSET 0--- V2-SELECT path, count(*) as count, project_id, first_value(created_at) as first_seen, last_value(properties['__title']) as title, origin FROM events WHERE name = 'screen_view' AND project_id = {p1:String} AND created_at > now() - INTERVAL {p2:UInt64} DAY GROUP BY path, project_id, origin ORDER BY count desc LIMIT {p3:UInt64} OFFSET {p4:UInt64}--- V2 params: {"p1":"redcollege","p2":30,"p3":20,"p4":0}-```--Result (first rows, identical on both sides): `[{"path":"/","count":5026,"project_id":"redcollege","first_seen":"2026-08-11 11:35:22.248","title":"RedCollege | Dashboard","origin":"https://inicio.redcollege.net"},{"path":"/login","count":4461,"pro`--### eventByIdQuery — with createdAt window--**statement 1** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 106218/106218; wall V1/V2 = 36.4 ms / 32.0 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE id = {p1:String} AND project_id = {p2:String} LIMIT 1--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE id = {p1:String} AND project_id = {p2:String} LIMIT 1--- V2 params: {"p1":"107145","p2":"redcollege"}-```--**statement 2** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 24574/24574; wall V1/V2 = 25.2 ms / 14.1 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events WHERE project_id = 'redcollege' AND created_at BETWEEN '2026-08-24 20:58:43' AND '2026-08-24 20:58:45' AND id = 'db54e0ad-b152-4d6f-9e5d-2aab3e23f9ef' LIMIT 1--- V2-SELECT * FROM events WHERE project_id = {p1:String} AND created_at BETWEEN {p2:String} AND {p3:String} AND id = {p4:String} LIMIT 1--- V2 params: {"p1":"redcollege","p2":"2026-08-24 20:58:43","p3":"2026-08-24 20:58:45","p4":"db54e0ad-b152-4d6f-9e5d-2aab3e23f9ef"}-```--### eventByIdQuery — without createdAt--**statement 1** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 106218/106218; wall V1/V2 = 33.0 ms / 29.4 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE id = {p1:String} AND project_id = {p2:String} LIMIT 1--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE id = {p1:String} AND project_id = {p2:String} LIMIT 1--- V2 params: {"p1":"107145","p2":"redcollege"}-```--**statement 2** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 32766/32766; wall V1/V2 = 14.0 ms / 13.8 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events WHERE project_id = 'redcollege' AND id = 'db54e0ad-b152-4d6f-9e5d-2aab3e23f9ef' LIMIT 1--- V2-SELECT * FROM events WHERE project_id = {p1:String} AND id = {p2:String} LIMIT 1--- V2 params: {"p1":"redcollege","p2":"db54e0ad-b152-4d6f-9e5d-2aab3e23f9ef"}-```--### topEventNamesQuery--**statement** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 40960/40960; wall V1/V2 = 5.9 ms / 6.1 ms; clickhouse_settings same.--```sql--- V1-SELECT name, count() as count FROM distinct_event_names_mv WHERE project_id = 'redcollege' GROUP BY name ORDER BY count DESC LIMIT 50--- V2-SELECT name, count() as count FROM distinct_event_names_mv WHERE project_id = {p1:String} GROUP BY name ORDER BY count DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"redcollege","p2":50}-```--Result (first rows, identical on both sides): `[{"name":"screen_view","count":1235},{"name":"session_start","count":1125},{"name":"session_end","count":1117},{"name":"link_out","count":955},{"name":"tema_cambiado","count":41},{"name":"apariencia_c`--### eventPropertiesQuery — all events--**statement** — IDENTICAL; rows V1/V2 = 144/144; rows_read V1/V2 = 131437/131437; wall V1/V2 = 9.7 ms / 9.7 ms; clickhouse_settings same.--```sql--- V1-SELECT property_key, name as event_name FROM event_property_values_mv WHERE project_id = 'redcollege' GROUP BY property_key, name ORDER BY property_key ASC, name ASC LIMIT 500--- V2-SELECT property_key, name as event_name FROM event_property_values_mv WHERE project_id = {p1:String} GROUP BY property_key, name ORDER BY property_key ASC, name ASC LIMIT {p2:UInt64}--- V2 params: {"p1":"redcollege","p2":500}-```--Result (first rows, identical on both sides): `[{"property_key":"__bot","event_name":"screen_view"},{"property_key":"__bot","event_name":"session_start"},{"property_key":"__bot_reasons","event_name":"apariencia_cambiada"},{"property_key":"__bot_re`--### eventPropertiesQuery — one event--**statement** — IDENTICAL; rows V1/V2 = 64/64; rows_read V1/V2 = 73728/73728; wall V1/V2 = 8.4 ms / 8.4 ms; clickhouse_settings same.--```sql--- V1-SELECT property_key, name as event_name FROM event_property_values_mv WHERE project_id = 'redcollege' AND name = 'screen_view' GROUP BY property_key, name ORDER BY property_key ASC, name ASC LIMIT 500--- V2-SELECT property_key, name as event_name FROM event_property_values_mv WHERE project_id = {p1:String} AND name = {p2:String} GROUP BY property_key, name ORDER BY property_key ASC, name ASC LIMIT {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":"screen_view","p3":500}-```--Result (first rows, identical on both sides): `[{"property_key":"__bot","event_name":"screen_view"},{"property_key":"__bot_reasons","event_name":"screen_view"},{"property_key":"__query.anexos","event_name":"screen_view"},{"property_key":"__query.a`--### eventPropertyValuesQuery--**statement** — IDENTICAL; rows V1/V2 = 200/200; rows_read V1/V2 = 81920/81920; wall V1/V2 = 8.4 ms / 8.6 ms; clickhouse_settings same.--```sql--- V1-SELECT property_value as value FROM event_property_values_mv WHERE project_id = 'redcollege' AND name = 'screen_view' AND property_key = '__query.curso' ORDER BY created_at DESC LIMIT 200--- V2-SELECT property_value as value FROM event_property_values_mv WHERE project_id = {p1:String} AND name = {p2:String} AND property_key = {p3:String} ORDER BY created_at DESC LIMIT {p4:UInt64}--- V2 params: {"p1":"redcollege","p2":"screen_view","p3":"__query.curso","p4":200}-```--Result (first rows, identical on both sides): `[{"value":"12735"},{"value":"12734"},{"value":"12736"},{"value":"13028"},{"value":"12681"},{"value":"12770"},{"value":"12775"},{"value":"12382"},{"value":"12731"},{"value":"12810"},{"value":"12806"},{`--### queryEventsQuery — default 30-day range, every equality column, properties, filters--**statement** — IDENTICAL (as row sets; no ORDER BY); rows V1/V2 = 42/42; rows_read V1/V2 = 270051/270051; wall V1/V2 = 70.4 ms / 73.4 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events WHERE project_id = 'redcollege' AND profile_id IN ('19318', '19315') AND name IN ('screen_view', 'link_out') AND path = '/63/2026/libros' AND referrer = 'https://inicio.redcollege.net' AND referrer_name = 'https://inicio.redcollege.net' AND device = 'desktop' AND country = 'CL' AND city = 'Santiago' AND os = 'Windows' AND browser = 'Chrome' AND properties['__title'] = 'RedCollege | Libro de Clases' AND created_at BETWEEN '2026-08-05 00:00:00' AND '2026-09-04 00:00:00' AND (profile_id IN (SELECT id FROM profiles FINAL WHERE project_id = 'redcollege' AND properties['cargo'] = 'Profesora')) LIMIT 100--- V2-SELECT * FROM events WHERE project_id = {p1:String} AND profile_id IN {p2:Array(String)} AND name IN {p3:Array(String)} AND path = {p4:String} AND referrer = {p5:String} AND referrer_name = {p6:String} AND device = {p7:String} AND country = {p8:String} AND city = {p9:String} AND os = {p10:String} AND browser = {p11:String} AND properties[{p12:String}] = {p13:String} AND created_at BETWEEN {p14:String} AND {p15:String} AND (profile_id IN (SELECT id FROM profiles FINAL WHERE project_id = 'redcollege' AND properties['cargo'] = 'Profesora')) LIMIT {p16:UInt64}--- V2 params: {"p1":"redcollege","p2":["19318","19315"],"p3":["screen_view","link_out"],"p4":"/63/2026/libros","p5":"https://inicio.redcollege.net","p6":"https://inicio.redcollege.net","p7":"desktop","p8":"CL","p9":"Santiago","p10":"Windows","p11":"Chrome","p12":"__title","p13":"RedCollege | Libro de Clases","p14":"2026-08-05 00:00:00","p15":"2026-09-04 00:00:00","p16":100}-```--### queryEventsQuery — sessionId (no date clause), profileId, explicit dates--**statement** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 24575/24575; wall V1/V2 = 22.2 ms / 15.0 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events WHERE project_id = 'redcollege' AND session_id = '0kiE1SjOk6U6_WDCbuyLeQ' AND profile_id = '107145' LIMIT 20--- V2-SELECT * FROM events WHERE project_id = {p1:String} AND session_id = {p2:String} AND profile_id = {p3:String} LIMIT {p4:UInt64}--- V2 params: {"p1":"redcollege","p2":"0kiE1SjOk6U6_WDCbuyLeQ","p3":"107145","p4":20}-```--### queryEventsQuery — sessionId + explicit startDate/endDate--**statement** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 24575/24575; wall V1/V2 = 14.6 ms / 32.5 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events WHERE project_id = 'redcollege' AND session_id = '0kiE1SjOk6U6_WDCbuyLeQ' AND created_at BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 00:00:00' LIMIT 20--- V2-SELECT * FROM events WHERE project_id = {p1:String} AND session_id = {p2:String} AND created_at BETWEEN {p3:String} AND {p4:String} LIMIT {p5:UInt64}--- V2 params: {"p1":"redcollege","p2":"0kiE1SjOk6U6_WDCbuyLeQ","p3":"2026-08-01 00:00:00","p4":"2026-08-31 00:00:00","p5":20}-```--### botEventsQuery + botEventsCountQuery (event.bots)--**statement 1** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 0/0; wall V1/V2 = 9.0 ms / 6.5 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events_bots WHERE project_id = 'redcollege'--- V2-SELECT count(*) as count FROM events_bots WHERE project_id = {p1:String}--- V2 params: {"p1":"redcollege"}-```--Result (first rows, identical on both sides): `[{"count":0}]`--**statement 2** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 0/0; wall V1/V2 = 5.9 ms / 6.4 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events_bots WHERE project_id = 'redcollege' ORDER BY created_at DESC LIMIT 8 OFFSET 8--- V2-SELECT * FROM events_bots WHERE project_id = {p1:String} ORDER BY created_at DESC LIMIT {p2:UInt64} OFFSET {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":8,"p3":8}-```--The prod-copy has no rows for this case (empty `cohort_members` / `events_bots`), so the same case also ran on the seeded `openpanel_test` copy:--### botEventsQuery + botEventsCountQuery (event.bots)--_Database: `openpanel_test`._--**statement 1** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1/1; wall V1/V2 = 50.2 ms / 7.8 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count FROM events_bots WHERE project_id = 'm7-002-proof'--- V2-SELECT count(*) as count FROM events_bots WHERE project_id = {p1:String}--- V2 params: {"p1":"m7-002-proof"}-```--Result (first rows, identical on both sides): `[{"count":23}]`--**statement 2** — IDENTICAL; rows V1/V2 = 8/8; rows_read V1/V2 = 46/46; wall V1/V2 = 51.9 ms / 6.7 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events_bots WHERE project_id = 'm7-002-proof' ORDER BY created_at DESC LIMIT 8 OFFSET 8--- V2-SELECT * FROM events_bots WHERE project_id = {p1:String} ORDER BY created_at DESC LIMIT {p2:UInt64} OFFSET {p3:UInt64}--- V2 params: {"p1":"m7-002-proof","p2":8,"p3":8}-```--### topOriginsQuery (event.origins)--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 179309/179309; wall V1/V2 = 19.0 ms / 14.8 ms; clickhouse_settings same.--```sql--- V1-SELECT DISTINCT origin, count(id) as count FROM events WHERE project_id = 'redcollege' AND origin IS NOT NULL AND origin != '' AND toDate(created_at) > now() - INTERVAL 30 DAY GROUP BY origin ORDER BY count DESC LIMIT 3--- V2-SELECT DISTINCT origin, count(id) as count FROM events WHERE project_id = {p1:String} AND origin IS NOT NULL AND origin != '' AND toDate(created_at) > now() - INTERVAL {p2:UInt64} DAY GROUP BY origin ORDER BY count DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":30,"p3":3}-```--Result (first rows, identical on both sides): `[{"origin":"https://libro.redcollege.net","count":85533},{"origin":"https://inicio.redcollege.net","count":27307},{"origin":"https://evalua.redcollege.net","count":4725}]`-diff --git a/packages/core/src/modules/event/src/sql.test.ts b/packages/core/src/modules/event/src/sql.test.tsindex 46fd71d19..cb22e0419 100644--- a/packages/core/src/modules/event/src/sql.test.ts+++ b/packages/core/src/modules/event/src/sql.test.ts@@ -1,8 +1,8 @@// Shape tests for the event module's fragments: every user value binds as a// `{pN:Type}` parameter (nothing is interpolated), the optional clauses and// joins toggle exactly on V1's conditions, and `sql.id` refuses anything off-// the column whitelists. Result-set equivalence against V1 is not tested here-// (these run offline); it is recorded per query in sql.proof.md.+// the column whitelists. These run offline, so they assert the rendered+// statement and its params, never a result set.import { describe, expect, test } from 'bun:test';import { sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/event/src/sql.ts b/packages/core/src/modules/event/src/sql.tsindex 1e50ad374..f25942713 100644--- a/packages/core/src/modules/event/src/sql.ts+++ b/packages/core/src/modules/event/src/sql.ts@@ -1,15 +1,11 @@// Every ClickHouse query the event module runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/event.service.ts and-// packages/trpc/src/routers/event.ts (M7-002): the SQL text is V1's, with-// every value bound as a `{pN:Type}` parameter instead of an escaped literal.-// Each builder's result set was diffed against V1's on the local prod-copy;-// the statements, params, row counts and timings are in sql.proof.md.+// (ADR-013).//-// Dates bind as V1's own `YYYY-MM-DD HH:mm:ss` strings on purpose: a String-// param in a DateTime64 position is parsed exactly like the literal it-// replaces, so the result sets cannot drift by a millisecond truncation.+// Dates bind as `YYYY-MM-DD HH:mm:ss` strings on purpose: a String param in a+// DateTime64 position is parsed exactly like the literal it replaces, so the+// result sets cannot drift by a millisecond truncation.//-// Cluster note (docs/ENVIRONMENT.md): `events`, `profiles`, `groups` and+// Cluster note: `events`, `profiles`, `groups` and// `cohort_members` are Distributed on Cloud. The identity-stitching and cohort// `IN (SELECT ...)` subqueries, the profile/group LEFT ANY JOINs and any// `IN (SELECT ...)` a filter compiles keep V1's exact shape and run under thediff --git a/packages/core/src/modules/group/group.service.ts b/packages/core/src/modules/group/group.service.tsindex e70f9bbe1..073fd361c 100644--- a/packages/core/src/modules/group/group.service.ts+++ b/packages/core/src/modules/group/group.service.ts@@ -1,16 +1,5 @@-// Ported from packages/db/src/services/group.service.ts plus the query bodies-// of packages/trpc/src/routers/group.ts (M7-002). The db file is now a-// re-export shim over this one, so @openpanel/db importers (the assistant/mcp-// tools, apps/api's insights controller) keep working while V1 runs-// (DELEGATE PATTERN); the trpc router delegates its handler bodies here.-//-// Every query is a `sql` fragment (src/sql.ts), converted one at a time-// with a result-set proof each, per ADR-013.-//-// M10-005: every function takes `ServiceDeps` and reaches ClickHouse as-// `deps.ch` — reads through ch-query.ts, the one write (`writeGroupToCh`)-// through `deps.ch.insert`. The `loadChClient` lazy loader is gone-// (docs/TECH_DEBT.md §2, §4).+// Every query is a `sql` fragment (src/sql.ts), per ADR-013. The one write+// (`writeGroupToCh`) goes through `deps.ch.insert`.import { toDots } from '@openpanel/shared';import { chQuery } from '../../ch-query';diff --git a/packages/core/src/modules/group/src/sql.proof.md b/packages/core/src/modules/group/src/sql.proof.mddeleted file mode 100644index 0931d1d2a..000000000--- a/packages/core/src/modules/group/src/sql.proof.md+++ /dev/null@@ -1,264 +0,0 @@-# sql.ts (formerly group.sql.ts) — V1 → V2 result-set proof (M7-002)--Every query builder in `sql.ts` was executed twice against the same data — once as V1 (the `git HEAD` service/router code, `3300f2a0`) and once as V2 (core's service, which renders the builder) — through one patched ClickHouse client that captured each statement, its `query_params`, `clickhouse_settings`, wall time and the raw JSON response. The two responses were compared on `data` (every row, every column, as JSON) and `meta` (column names and types). Statements without an `ORDER BY` were compared as row sets, because ClickHouse's parallel aggregation returns them in a different order run to run — V1 against itself too.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static), project `redcollege` unless noted; cases needing rows the prod-copy lacks (`cohort_members`, `events_bots` are empty there) also ran on the isolated `openpanel_test` database with 3,380 events copied from `redcollege` under project `m7-002-proof`, plus seeded cohort/bot rows (deleted afterwards).-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are directional only; production is 2 shards × 2 replicas (`docs/ENVIRONMENT.md`). `rows_read` differences on JOIN statements are ClickHouse's per-run accounting of the right-hand side, not a plan difference: the SQL text is identical up to `{pN:Type}` binding.-- **Verdict**: 16 cases / 18 statements, all IDENTICAL. No conversion changed a result set.--The harness was a throwaway script (it needed verbatim copies of the V1 sources next to V2); each statement below is complete and reproducible with `curl http://127.0.0.1:8123/?database=openpanel`, binding the V2 params as `param_pN=`.--### groupByIdQuery--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3359/3359; wall V1/V2 = 5.3 ms / 5.5 ms; clickhouse_settings same.--```sql--- V1-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = 'redcollege' AND id = '271' AND deleted = 0--- V2-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = {p1:String} AND id = {p2:String} AND deleted = 0--- V2 params: {"p1":"redcollege","p2":"271"}-```--### groupListQuery — page 2, type + search--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 3359/3359; wall V1/V2 = 5.5 ms / 5.9 ms; clickhouse_settings same.--```sql--- V1-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = 'redcollege' AND deleted = 0 AND type = 'establecimiento' AND (name ILIKE '%colegio%' OR id ILIKE '%colegio%') ORDER BY created_at DESC LIMIT 10 OFFSET 10--- V2-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0 AND type = {p2:String} AND (name ILIKE {p3:String} OR id ILIKE {p4:String}) ORDER BY created_at DESC LIMIT {p5:UInt64} OFFSET {p6:UInt64}--- V2 params: {"p1":"redcollege","p2":"establecimiento","p3":"%colegio%","p4":"%colegio%","p5":10,"p6":10}-```--### groupListQuery — first page, no filters--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 3359/3359; wall V1/V2 = 9.8 ms / 6.6 ms; clickhouse_settings same.--```sql--- V1-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = 'redcollege' AND deleted = 0 ORDER BY created_at DESC LIMIT 10 OFFSET 0--- V2-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0 ORDER BY created_at DESC LIMIT {p2:UInt64} OFFSET {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":10,"p3":0}-```--### groupListCountQuery — type + search--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3359/3359; wall V1/V2 = 5.3 ms / 5.3 ms; clickhouse_settings same.--```sql--- V1-SELECT count() as count FROM groups FINAL WHERE project_id = 'redcollege' AND deleted = 0 AND type = 'establecimiento' AND (name ILIKE '%colegio%' OR id ILIKE '%colegio%')--- V2-SELECT count() as count FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0 AND type = {p2:String} AND (name ILIKE {p3:String} OR id ILIKE {p4:String})--- V2 params: {"p1":"redcollege","p2":"establecimiento","p3":"%colegio%","p4":"%colegio%"}-```--Result (first rows, identical on both sides): `[{"count":42}]`--### groupListCountQuery — plain--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3359/3359; wall V1/V2 = 5.7 ms / 4.3 ms; clickhouse_settings same.--```sql--- V1-SELECT count() as count FROM groups FINAL WHERE project_id = 'redcollege' AND deleted = 0--- V2-SELECT count() as count FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0--- V2 params: {"p1":"redcollege"}-```--Result (first rows, identical on both sides): `[{"count":124}]`--### groupTypesQuery--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3359/3359; wall V1/V2 = 4.1 ms / 4.0 ms; clickhouse_settings same.--```sql--- V1-SELECT DISTINCT type FROM groups FINAL WHERE project_id = 'redcollege' AND deleted = 0--- V2-SELECT DISTINCT type FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0--- V2 params: {"p1":"redcollege"}-```--Result (first rows, identical on both sides): `[{"type":"establecimiento"}]`--### groupPropertyKeysQuery--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 3359/3359; wall V1/V2 = 6.2 ms / 6.2 ms; clickhouse_settings same.--```sql--- V1-SELECT DISTINCT arrayJoin(mapKeys(properties)) as key FROM groups FINAL WHERE project_id = 'redcollege' AND deleted = 0--- V2-SELECT DISTINCT arrayJoin(mapKeys(properties)) as key FROM groups FINAL WHERE project_id = {p1:String} AND deleted = 0--- V2 params: {"p1":"redcollege"}-```--Result (first rows, identical on both sides): `[{"key":"rbd"}]`--### groupStatsQuery--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 147449/147449; wall V1/V2 = 23.6 ms / 17.1 ms; clickhouse_settings same.--```sql--- V1-SELECT g AS group_id, uniqExact(profile_id) AS member_count, max(created_at) AS last_active_at FROM events ARRAY JOIN groups AS g WHERE project_id = 'redcollege' AND g IN ('271','454','521') AND profile_id != device_id GROUP BY g--- V2-SELECT g AS group_id, uniqExact(profile_id) AS member_count, max(created_at) AS last_active_at FROM events ARRAY JOIN groups AS g WHERE project_id = {p1:String} AND g IN {p2:Array(String)} AND profile_id != device_id GROUP BY g--- V2 params: {"p1":"redcollege","p2":["271","454","521"]}-```--Result (first rows, identical on both sides): `[{"group_id":"271","member_count":76,"last_active_at":"2026-08-25 02:16:23.865"}]`--#### M36-003 — `hasAny(groups, …)` base-row prefilter--The shipped statement tested only the `ARRAY JOIN` alias `g`, which cannot move to PREWHERE, so every identified event of the project had `created_at` and `groups` read before a row was rejected. The builder now also emits `AND hasAny(groups, {p2:Array(String)})` ahead of `g IN {p3:Array(String)}` (the ids bound twice). A row whose `groups` shares nothing with the ids cannot yield a `g` in them, so the result set is the same by construction. It is also measured: on 2026-09-16 at 14:26 UTC both statements ran through `curl` on `:8123` with `use_query_condition_cache=0`, against the prod copy (read-only). Each ran 3× with `FORMAT Null`. The results were compared as sorted `FORMAT TSVRaw` sha256, and also as `cityHash64(arraySort(groupArray(tuple(*))))`. The ids are each project's 50 newest groups. The five busy anchors have no groups, so they were given `stub-web`'s ids: that measures the scan floor any busy project with groups pays.--| project | before | after | rows_read before/after | result rows before/after | result |-|---|---|---|---|---|---|-| `stub-web` | 29–42 ms, 77.5 MiB | 39–49 ms, 14.3 MiB | 786,321 / 786,321 | 6 / 6 | IDENTICAL |-| `secure-privacy` | 40–48 ms, 50.3 MiB | 16–19 ms, 8.1 MiB | 556,965 / 556,965 | 8 / 8 | IDENTICAL |-| `redcollege` | 20–25 ms, 16.5 MiB | 35–41 ms, 10.5 MiB | 216,593 / 216,593 | 48 / 48 | IDENTICAL |-| `strackr` | 20–29 ms, 22.2 MiB | 20–22 ms, 7.9 MiB | 262,122 / 262,122 | 40 / 40 | IDENTICAL |-| `companysize` | 8–9 ms, 7.6 MiB | 5–6 ms, 0.8 MiB | 97,980 / 97,980 | 0 / 0 | IDENTICAL |-| `web-app-7030` | 11–17 ms, 11.6 MiB | 13–15 ms, 9.0 MiB | 122,343 / 122,343 | 45 / 45 | IDENTICAL |-| `verdict` (floor) | **1,274–1,277 ms, 3,164.5 MiB** | **177–180 ms, 337.0 MiB** | 44,164,383 / same | 0 / 0 | IDENTICAL |-| `bayse` (floor) | **1,004–1,009 ms, 3,155.0 MiB** | **153–157 ms, 291.8 MiB** | 38,246,986 / same | 0 / 0 | IDENTICAL |-| `earlysalary-production` (floor) | 844–874 ms, 2,925.7 MiB | 111–114 ms, 204.4 MiB | 26,787,643 / same | 0 / 0 | IDENTICAL |-| `website-8103` (floor) | 64–65 ms, 50.8 MiB | **95–98 ms, 176.4 MiB** | 23,126,247 / same | 0 / 0 | IDENTICAL |-| `chatpaper` (floor) | 580–591 ms, 1,323.1 MiB | 84–85 ms, 151.0 MiB | 19,797,588 / same | 0 / 0 | IDENTICAL |--`EXPLAIN actions=1` shows that `profile_id != device_id` was already a PREWHERE before the change; only the alias test was not. `website-8103` has no identified events, so that PREWHERE already rejected every row after reading `profile_id` and `device_id`. The added `hasAny` now also reads the `groups` offsets (8 bytes per row), which makes it the one project here that got slower. The statement has no `ORDER BY` and the service folds it into a `Map`, so row order is not part of the output. `hasAny` takes a bound array literal, not a subquery, so the `IN` vs `GLOBAL IN` distributed-table trap does not apply. **Not measured:** a busy project where many rows match, because no busy project on this copy has groups.--### groupsByIdsQuery--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 3359/3359; wall V1/V2 = 5.2 ms / 4.9 ms; clickhouse_settings same.--```sql--- V1-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = 'redcollege' AND id IN ('271','454','missing') AND deleted = 0--- V2-SELECT project_id, id, type, name, properties, created_at, version FROM groups FINAL WHERE project_id = {p1:String} AND id IN {p2:Array(String)} AND deleted = 0--- V2 params: {"p1":"redcollege","p2":["271","454","missing"]}-```--### groupMemberProfilesQuery — search (trimmed), page 2--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 122602/122602; wall V1/V2 = 23.1 ms / 22.9 ms; clickhouse_settings same.--```sql--- V1-SELECT id, count() OVER () AS total_count FROM profiles FINAL WHERE project_id = 'redcollege' AND has(groups, '271') AND (email ILIKE '%maria%' OR first_name ILIKE '%maria%' OR last_name ILIKE '%maria%') ORDER BY created_at DESC LIMIT 5 OFFSET 5--- V2-SELECT id, count() OVER () AS total_count FROM profiles FINAL WHERE project_id = {p1:String} AND has(groups, {p2:String}) AND (email ILIKE {p3:String} OR first_name ILIKE {p4:String} OR last_name ILIKE {p5:String}) ORDER BY created_at DESC LIMIT {p6:UInt64} OFFSET {p7:UInt64}--- V2 params: {"p1":"redcollege","p2":"271","p3":"%maria%","p4":"%maria%","p5":"%maria%","p6":5,"p7":5}-```--### groupMemberProfilesQuery — blank search, first page--**statement 1** — IDENTICAL; rows V1/V2 = 5/5; rows_read V1/V2 = 106218/106218; wall V1/V2 = 35.9 ms / 34.9 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} AND id IN {p2:Array(String)}--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} AND id IN {p2:Array(String)}--- V2 params: {"p1":"redcollege","p2":["107142","186276","107079","107111","107918"]}-```--**statement 2** — IDENTICAL; rows V1/V2 = 5/5; rows_read V1/V2 = 122602/122602; wall V1/V2 = 22.9 ms / 19.4 ms; clickhouse_settings same.--```sql--- V1-SELECT id, count() OVER () AS total_count FROM profiles FINAL WHERE project_id = 'redcollege' AND has(groups, '271') ORDER BY created_at DESC LIMIT 5 OFFSET 0--- V2-SELECT id, count() OVER () AS total_count FROM profiles FINAL WHERE project_id = {p1:String} AND has(groups, {p2:String}) ORDER BY created_at DESC LIMIT {p3:UInt64} OFFSET {p4:UInt64}--- V2 params: {"p1":"redcollege","p2":"271","p3":5,"p4":0}-```--### groupEventMetricsQuery + groupUniqueProfilesQuery (group.metrics)--**statement 1** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 147449/147449; wall V1/V2 = 13.0 ms / 14.7 ms; clickhouse_settings same.--```sql--- V1-SELECT count() AS totalEvents, min(created_at) AS firstSeen, max(created_at) AS lastSeen FROM events WHERE project_id = 'redcollege' AND has(groups, '271')--- V2-SELECT count() AS totalEvents, min(created_at) AS firstSeen, max(created_at) AS lastSeen FROM events WHERE project_id = {p1:String} AND has(groups, {p2:String})--- V2 params: {"p1":"redcollege","p2":"271"}-```--Result (first rows, identical on both sides): `[{"totalEvents":20492,"firstSeen":"2026-08-10 20:02:03.875","lastSeen":"2026-08-25 02:16:23.865"}]`--**statement 2** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 122602/122602; wall V1/V2 = 21.8 ms / 21.3 ms; clickhouse_settings same.--```sql--- V1-SELECT count() AS uniqueProfiles FROM profiles FINAL WHERE project_id = 'redcollege' AND has(groups, '271')--- V2-SELECT count() AS uniqueProfiles FROM profiles FINAL WHERE project_id = {p1:String} AND has(groups, {p2:String})--- V2 params: {"p1":"redcollege","p2":"271"}-```--Result (first rows, identical on both sides): `[{"uniqueProfiles":75}]`--### groupActivityQuery (group.activity)--**statement** — IDENTICAL; rows V1/V2 = 16/16; rows_read V1/V2 = 147449/147449; wall V1/V2 = 11.5 ms / 11.2 ms; clickhouse_settings same.--```sql--- V1-SELECT count() AS count, toStartOfDay(created_at) AS date FROM events WHERE project_id = 'redcollege' AND has(groups, '271') GROUP BY date ORDER BY date DESC--- V2-SELECT count() AS count, toStartOfDay(created_at) AS date FROM events WHERE project_id = {p1:String} AND has(groups, {p2:String}) GROUP BY date ORDER BY date DESC--- V2 params: {"p1":"redcollege","p2":"271"}-```--Result (first rows, identical on both sides): `[{"count":2,"date":"2026-08-25 00:00:00"},{"count":1985,"date":"2026-08-24 00:00:00"},{"count":72,"date":"2026-08-23 00:00:00"},{"count":41,"date":"2026-08-22 00:00:00"},{"count":1178,"date":"2026-08-`--### groupMemberGrowthQuery (group.memberGrowth)--**statement** — IDENTICAL; rows V1/V2 = 30/30; rows_read V1/V2 = 73450/73450; wall V1/V2 = 12.8 ms / 13.5 ms; clickhouse_settings same.--```sql--- V1-SELECT toDate(toStartOfDay(created_at)) AS date, count() AS count FROM profiles FINAL WHERE project_id = 'redcollege' AND has(groups, '271') AND created_at >= now() - INTERVAL 30 DAY GROUP BY date ORDER BY date ASC WITH FILL FROM toDate(now() - INTERVAL 29 DAY) TO toDate(now() + INTERVAL 1 DAY) STEP 1--- V2-SELECT toDate(toStartOfDay(created_at)) AS date, count() AS count FROM profiles FINAL WHERE project_id = {p1:String} AND has(groups, {p2:String}) AND created_at >= now() - INTERVAL {p3:UInt64} DAY GROUP BY date ORDER BY date ASC WITH FILL FROM toDate(now() - INTERVAL {p4:UInt64} DAY) TO toDate(now() + INTERVAL 1 DAY) STEP 1--- V2 params: {"p1":"redcollege","p2":"271","p3":30,"p4":29}-```--Result (first rows, identical on both sides): `[{"date":"2026-08-06","count":0},{"date":"2026-08-07","count":0},{"date":"2026-08-08","count":0},{"date":"2026-08-09","count":0},{"date":"2026-08-10","count":22},{"date":"2026-08-11","count":36},{"dat`--### groupMostEventsQuery (group.mostEvents)--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 147449/147449; wall V1/V2 = 11.6 ms / 16.9 ms; clickhouse_settings same.--```sql--- V1-SELECT count() as count, name FROM events WHERE project_id = 'redcollege' AND has(groups, '271') AND name NOT IN ('screen_view', 'session_start', 'session_end') GROUP BY name ORDER BY count DESC LIMIT 10--- V2-SELECT count() as count, name FROM events WHERE project_id = {p1:String} AND has(groups, {p2:String}) AND name NOT IN ('screen_view', 'session_start', 'session_end') GROUP BY name ORDER BY count DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":"271","p3":10}-```--Result (first rows, identical on both sides): `[{"count":854,"name":"link_out"},{"count":1,"name":"banner_click"}]`--### groupPopularRoutesQuery (group.popularRoutes)--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 147449/147449; wall V1/V2 = 21.0 ms / 15.1 ms; clickhouse_settings same.--```sql--- V1-SELECT count() as count, path FROM events WHERE project_id = 'redcollege' AND has(groups, '271') AND name = 'screen_view' GROUP BY path ORDER BY count DESC LIMIT 10--- V2-SELECT count() as count, path FROM events WHERE project_id = {p1:String} AND has(groups, {p2:String}) AND name = 'screen_view' GROUP BY path ORDER BY count DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":"271","p3":10}-```--Result (first rows, identical on both sides): `[{"count":3460,"path":"/271/2026/libros"},{"count":1648,"path":"/271/2026/inicio"},{"count":903,"path":"/271/2026/asistencia-consolidada"},{"count":181,"path":"/271/2026/libros/12530/asistencia"},{"co`-diff --git a/packages/core/src/modules/group/src/sql.ts b/packages/core/src/modules/group/src/sql.tsindex b09086d12..5fa2a1005 100644--- a/packages/core/src/modules/group/src/sql.ts+++ b/packages/core/src/modules/group/src/sql.ts@@ -1,11 +1,7 @@// Every ClickHouse query the group module runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/group.service.ts and-// packages/trpc/src/routers/group.ts (M7-002): the SQL text is V1's, with every-// value bound as a `{pN:Type}` parameter instead of an escaped literal. Each-// builder's result set was diffed against V1's on the local prod-copy; the-// statements, params, row counts and timings are in sql.proof.md.+// (ADR-013).//-// Cluster note (docs/ENVIRONMENT.md): `groups`, `profiles` and `events` are+// Cluster note: `groups`, `profiles` and `events` are// Distributed on Cloud. No query here carries an `IN (subquery)`; the `IN`// lists bind as `Array(String)` params, which is a literal list to the planner.diff --git a/packages/core/src/modules/insight/src/insight-modules.sql.proof.md b/packages/core/src/modules/insight/src/insight-modules.sql.proof.mddeleted file mode 100644index ca8339439..000000000--- a/packages/core/src/modules/insight/src/insight-modules.sql.proof.md+++ /dev/null@@ -1,727 +0,0 @@-# insight-modules — V1 → V2 result-set proof (M12-007)--The five insight detection modules (`devices`, `geo`, `page-trends`,-`referrers`, `entry-pages`) moved off `createCachedClix` onto the ADR-013 `sql`-tag. V1 is the code at `43dedb75` (this task's parent), extracted with-`git show HEAD:<path>` into `/tmp/m12007/v1src/` with only its relative import-specifiers rewritten to absolute paths — the SQL-producing code is byte-identical-to HEAD. Both sides were driven through the **same** `enumerateDimensions(ctx)`-entry point with the same `projectId`, the same `now` and the same three window-kinds; V1's ClickHouse client and V2's `ctx.runQuery` were each replaced by a-recorder, so the two statement lists come from the real code paths rather than-from retyped SQL. Every V1 statement was then executed as `query`, every V2-statement as `query` + `query_params`, against the same local prod-copy-ClickHouse over one HTTP endpoint with `default_format=JSON` and-`session_timezone=UTC` on both sides (clix's own default — `query-builder.ts:696`-sets `timezone ?? 'UTC'` and `:562` sends it as `session_timezone`; the new-wrapper defaults to `'UTC'` identically). `data` and `meta` were compared in-full. None of these statements has a total `ORDER BY` — every one is a bare-`GROUP BY` or a single-row aggregate — so **all 35 cases were compared as sets**-(rows sorted by their JSON encoding on both sides before comparison); `meta` was-compared in column order.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,850,963 events. Project- `openalternative`, driven at `now = 2026-08-26T12:00:00.000Z` (its- `screen_view` events stop on 2026-08-25, and this `now` is what keeps every- page-trends case non-empty). Project timezone is not read by these modules —- clix sent `session_timezone: 'UTC'` unconditionally and so does the- replacement. No fixture is empty here: **every one of the 35 cases returns a- non-zero row count on both sides**.-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). None of these statements contains `IN`, `GLOBAL IN`,- `JOIN` or a subquery of any kind: `grep -nE 'GLOBAL |[^A-Za-z_]IN[ (]|JOIN'`- over the five converted `*.module.ts` files returns nothing, and the same grep- over their V1 form at `43dedb75` also returns nothing. No `IN`/`GLOBAL IN` was- introduced, removed or rewritten in either direction.-- **Verdict**: **35 cases, all IDENTICAL.**--## Coverage--Each module issues 5 distinct statements — 3 on the `yesterday` branch, 2 on the-`rolling_*` branch. Both branches were exercised, and the `rolling_*` branch-twice (`rolling_7d` and `rolling_30d`, different dates through the same text),-giving 7 executed cases per module and 35 in total.--## Cache-key derivation, before and after--| | V1 (`cached-clix.ts`, deleted) | V2 (`cached-query.ts`) |-|---|---|---|-| key | `sha256(query.toSQL() + '\|' + timezone)` (lines 32-36) | `sha256(query + '\|' + JSON.stringify(query_params) + '\|' + timezone)` |-| why it worked / must change | clix inlined every value as a literal, so the text alone identified the query | the `sql` tag renders `{p1:Type}, {p2:Type}, …` from a per-render counter, so two statements differing only in their bound values render to the **same text** |-| timezone | `timezone ?? 'UTC'`, folded into the key | unchanged, including the `'UTC'` default |-| `session_timezone` | `clickhouse_settings.session_timezone` on every `execute()` | `clickhouse_settings.session_timezone` on every `chQuery` |-| cache | caller-supplied `Map`, one per module+window, built in `engine.ts` | unchanged — same `Map`, same place, same lifetime |-| miss path | `clix(...).execute()` | `chQuery(deps, statement, settings)` — same retry/round-robin client, now carrying the request's logger (ADR-018) |--`JSON.stringify(query_params)` is stable because `toStatement()` assigns-`p1, p2, …` in render order from one counter; the keys are deliberately **not**-sorted, so two fragments that differ only in param order stay different keys.--`packages/core/src/modules/insight/src/cached-query.test.ts` pins all of it —-in particular `equal text with different params is a different key`, which first-asserts the two statements' rendered text is byte-equal (the collision a-text-only key would produce) and then that both reach ClickHouse.--## Tests--No existing insight test compared generated SQL text: the three test files in-this module (`insight.service.test.ts`, `insight.jobs.test.ts`,-`insight.rpc.test.ts`) assert delegation and payload shapes only, and none of-them is touched by this task. There was therefore no text-comparing test to-retarget onto `statement + params`; the new `cached-query.test.ts` is the only-test added, and it compares statement text **and** params.--## Cases--### devices--**devices — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 16384/16384; wall V1/V2 = 11 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "device", "type": "LowCardinality(String)"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT device, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device---- V2-SELECT device, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY device---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}-```--**devices — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 99/99; rows_read V1/V2 = 212928/212928; wall V1/V2 = 23 ms / 18 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "device", "type": "LowCardinality(String)"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT toDate(created_at) as date, device, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, device---- V2-SELECT toDate(created_at) as date, device, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY date, device---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}-```--**devices — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 15 ms / 12 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total-FROM sessions-WHERE project_id = {p3:String}- AND sign = {p4:Int8}- AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}---- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}-```--**devices — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 5/5; rows_read V1/V2 = 131025/131025; wall V1/V2 = 11 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "device", "type": "LowCardinality(String)"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT device, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device---- V2-SELECT device, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY device---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**devices — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 9 ms / 7 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**devices — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 6/6; rows_read V1/V2 = 311191/311191; wall V1/V2 = 16 ms / 14 ms; `meta` V1/V2 (identical) = `[{"name": "device", "type": "LowCardinality(String)"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT device, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device---- V2-SELECT device, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY device---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**devices — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 10 ms / 9 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--### geo--**geo — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 154/154; rows_read V1/V2 = 16384/16384; wall V1/V2 = 5 ms / 4 ms; `meta` V1/V2 (identical) = `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT country, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY country---- V2-SELECT country, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY country---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}-```--**geo — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 3876/3876; rows_read V1/V2 = 212928/212928; wall V1/V2 = 14 ms / 13 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT toDate(created_at) as date, country, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, country---- V2-SELECT toDate(created_at) as date, country, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY date, country---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}-```--**geo — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 9 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total-FROM sessions-WHERE project_id = {p3:String}- AND sign = {p4:Int8}- AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}---- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}-```--**geo — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 202/202; rows_read V1/V2 = 131025/131025; wall V1/V2 = 8 ms / 7 ms; `meta` V1/V2 (identical) = `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT country, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY country---- V2-SELECT country, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY country---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**geo — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 7 ms / 12 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**geo — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 213/213; rows_read V1/V2 = 311191/311191; wall V1/V2 = 14 ms / 15 ms; `meta` V1/V2 (identical) = `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT country, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY country---- V2-SELECT country, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY country---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**geo — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 11 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--### page-trends--**page-trends — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 1057/1057; rows_read V1/V2 = 32755/32755; wall V1/V2 = 8 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT origin, path, count(*) as cnt FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY origin, path---- V2-SELECT origin, path, count(*) as cnt-FROM events-WHERE project_id = {p1:String}- AND name = {p2:String}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY origin, path---- V2 params: {"p1": "openalternative", "p2": "screen_view", "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}-```--**page-trends — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 54996/54996; rows_read V1/V2 = 1212377/1212377; wall V1/V2 = 160 ms / 148 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT toDate(created_at) as date, origin, path, count(*) as cnt FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, origin, path---- V2-SELECT toDate(created_at) as date, origin, path, count(*) as cnt-FROM events-WHERE project_id = {p1:String}- AND name = {p2:String}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY date, origin, path---- V2 params: {"p1": "openalternative", "p2": "screen_view", "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}-```--**page-trends — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1245144/1245144; wall V1/V2 = 40 ms / 28 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total-FROM events-WHERE project_id = {p3:String}- AND name = {p4:String}- AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}---- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": "screen_view", "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}-```--**page-trends — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 6608/6608; rows_read V1/V2 = 581593/581593; wall V1/V2 = 42 ms / 50 ms; `meta` V1/V2 (identical) = `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT origin, path, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY origin, path---- V2-SELECT origin, path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM events-WHERE project_id = {p5:String}- AND name = {p6:String}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY origin, path---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**page-trends — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 581593/581593; wall V1/V2 = 32 ms / 21 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM events-WHERE project_id = {p5:String}- AND name = {p6:String}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**page-trends — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 13246/13246; rows_read V1/V2 = 1687334/1687334; wall V1/V2 = 99 ms / 112 ms; `meta` V1/V2 (identical) = `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT origin, path, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY origin, path---- V2-SELECT origin, path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM events-WHERE project_id = {p5:String}- AND name = {p6:String}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY origin, path---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**page-trends — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1687334/1687334; wall V1/V2 = 42 ms / 31 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM events-WHERE project_id = {p5:String}- AND name = {p6:String}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--### referrers--**referrers — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 75/75; rows_read V1/V2 = 16384/16384; wall V1/V2 = 5 ms / 5 ms; `meta` V1/V2 (identical) = `[{"name": "referrer_name", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT referrer_name, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY referrer_name---- V2-SELECT referrer_name, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY referrer_name---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}-```--**referrers — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 2112/2112; rows_read V1/V2 = 212928/212928; wall V1/V2 = 15 ms / 15 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "referrer_name", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT toDate(created_at) as date, referrer_name, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, referrer_name---- V2-SELECT toDate(created_at) as date, referrer_name, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY date, referrer_name---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}-```--**referrers — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 12 ms / 11 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total-FROM sessions-WHERE project_id = {p3:String}- AND sign = {p4:Int8}- AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}---- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}-```--**referrers — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 331/331; rows_read V1/V2 = 131025/131025; wall V1/V2 = 10 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "referrer_name", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT referrer_name, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY referrer_name---- V2-SELECT referrer_name, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY referrer_name---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**referrers — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 8 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**referrers — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 798/798; rows_read V1/V2 = 311191/311191; wall V1/V2 = 16 ms / 13 ms; `meta` V1/V2 (identical) = `[{"name": "referrer_name", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT referrer_name, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY referrer_name---- V2-SELECT referrer_name, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY referrer_name---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**referrers — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 9 ms / 9 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--### entry-pages--**entry-pages — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 1191/1191; rows_read V1/V2 = 16384/16384; wall V1/V2 = 7 ms / 6 ms; `meta` V1/V2 (identical) = `[{"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT entry_origin, entry_path, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY entry_origin, entry_path---- V2-SELECT entry_origin, entry_path, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY entry_origin, entry_path---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}-```--**entry-pages — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 34473/34473; rows_read V1/V2 = 212928/212928; wall V1/V2 = 94 ms / 93 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT toDate(created_at) as date, entry_origin, entry_path, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, entry_origin, entry_path---- V2-SELECT toDate(created_at) as date, entry_origin, entry_path, count(*) as cnt-FROM sessions-WHERE project_id = {p1:String}- AND sign = {p2:Int8}- AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}-GROUP BY date, entry_origin, entry_path---- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}-```--**entry-pages — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 15 ms / 13 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total-FROM sessions-WHERE project_id = {p3:String}- AND sign = {p4:Int8}- AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}---- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}-```--**entry-pages — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 5724/5724; rows_read V1/V2 = 131025/131025; wall V1/V2 = 38 ms / 28 ms; `meta` V1/V2 (identical) = `[{"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT entry_origin, entry_path, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY entry_origin, entry_path---- V2-SELECT entry_origin, entry_path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY entry_origin, entry_path---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**entry-pages — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 10 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**entry-pages — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 11423/11423; rows_read V1/V2 = 311191/311191; wall V1/V2 = 41 ms / 46 ms; `meta` V1/V2 (identical) = `[{"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT entry_origin, entry_path, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY entry_origin, entry_path---- V2-SELECT entry_origin, entry_path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}-GROUP BY entry_origin, entry_path---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--**entry-pages — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 14 ms / 9 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).--```sql--- V1-SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'---- V2-SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total-FROM sessions-WHERE project_id = {p5:String}- AND sign = {p6:Int8}- AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}---- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}-```--## Reproducing any case--V1 is the literal text above; V2 is the text plus `param_pN=` values:--```bash-# V1 (devices / current window, grouped)-curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \- --data-urlencode 'default_format=JSONCompact' \- --data-urlencode "query=SELECT device, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device"--# V2-curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \- --data-urlencode 'default_format=JSONCompact' \- --data-urlencode 'param_p1=openalternative' \- --data-urlencode 'param_p2=1' \- --data-urlencode 'param_p3=2026-08-25 00:00:00' \- --data-urlencode 'param_p4=2026-08-25 23:59:59' \- --data-urlencode 'query=SELECT device, count(*) as cnt FROM sessions WHERE project_id = {p1:String} AND sign = {p2:Int8} AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)} GROUP BY device'-```--Both return the same three rows.--## Conversion notes--- **`DateTime64(3)`, not `String`.** `created_at` is `DateTime64(3)` and V1- compared it against a quoted literal, which ClickHouse converts to that type.- Measured 2026-09-07 on this box: `{p:DateTime}`, `{p:DateTime64(3)}` and- `{p:String}` all return the identical count, but only `DateTime64(3)`- reproduces V1's `rows_read` exactly (163,730 for `{p:String}` vs 212,831 for- the literal on a probe query), i.e. only it keeps the same index analysis.-- **The date strings are unchanged.** clix's `escapeDate` ran- `sqlstring.escape(clix.datetime(d))` = `toISOString().slice(0,19)`, and- `formatClickhouseDate` produces the same string for the same input — including- the truncation of `getEndOfDay`'s `.999` milliseconds to `23:59:59`. The- `countIf(...)` expressions already used `formatClickhouseDate` in V1 (they- went through `clix.exp`, which bypasses `escapeDate`), so both sides of every- window boundary agree byte-for-byte.-- **`sign = 1` and `name = 'screen_view'` are now bound**, as `{pN:Int8}` and- `{pN:String}`. Both were *values* handed to `clix.where(...)` in V1, so they- bind under the mechanical rule; the emitted comparison is unchanged.-- **`escapeDate`'s date-substring rewrite (recipe trap 1) is not reachable- here.** The only strings V1 escaped were the project id and the window- boundaries; no `SELECT` expression or column name in these five modules- contains a date-shaped substring, so nothing relied on the implicit re-quoting- and no V2 text had to add a quote back. The proof's 35 identical texts are the- evidence.-- **Bound through the real driver too, not only over HTTP.** The 35 cases above- were executed over ClickHouse's HTTP interface (`param_pN=`), which is what- makes them reproducible with `curl`. As a separate check on 2026-09-07,- `devicesModule.enumerateDimensions` was run once with `ctx.runQuery` wired to a- real `@clickhouse/client` `query({query, query_params, …})` against local- prod-copy `openpanel`; it returned- `["device:mobile", "device:desktop", "device:tablet", "device:smarttv"]`, so- the `{pN:DateTime64(3)}` / `{pN:Int8}` / `{pN:String}` bindings survive the- driver's own parameter serialization, not just the query string.-- **`session_timezone` is pinned, not dropped** (recipe trap 3): the new wrapper- defaults to `'UTC'` and sends it on every statement, exactly as- `clix(client, undefined)` did.diff --git a/packages/core/src/modules/insight/src/legacy-scan.sql.proof.md b/packages/core/src/modules/insight/src/legacy-scan.sql.proof.mddeleted file mode 100644index 3d4ca808f..000000000--- a/packages/core/src/modules/insight/src/legacy-scan.sql.proof.md+++ /dev/null@@ -1,593 +0,0 @@-# legacy-scan.ts — V1 → V2 result-set proof (M12-008)--Every ClickHouse statement `packages/core/src/modules/insight/src/legacy-scan.ts`-runs, executed V1 against V2 on the local prod-copy `openpanel`. **This proof-also covers `packages/core/src/modules/insight/src/referrer-spikes.ts`**, the-task's second insight file — see *referrer-spikes.ts* at the bottom: it was-already converted off clix by M12-002 and scores 0/0/0 on the grep gate today,-so what is recorded here is a re-execution of its three statements V1 against-V2, not a second conversion.--V1 is the `legacy-scan.ts` at commit `68fea1a7`-(`git show HEAD:packages/core/src/modules/insight/src/legacy-scan.ts`), which-builds all ten statements with `clix`; V2 is the converted file, every runtime-value bound as a `{pN:Type}` param. **Both were imported into one Bun process-and driven through the same public entry point** — `createLegacyInsightsScanner(deps)-.generateInsights('pincali-production')` on each, with `Date.now()` frozen at-`2026-08-25T08:49:53Z` so the ten computed windows are identical on both sides,-behind a `deps.ch.query` stub that captures `{query, query_params,-clickhouse_settings}`. No statement below was retyped by hand. Each captured-statement was then executed through one HTTP call to `127.0.0.1:8123` at-`format: 'JSON'` with the settings its own side asked for; `data` was compared-row-for-row and `meta` column-for-column.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,851,025 events at the time of the- run. Project `pincali-production` (14,047,591 events, 2,160,074 sessions).- Nothing needed here is empty — see the row-bearing twins below for why the- live statements still return no rows.-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either- direction.** `git show HEAD:<file> | grep -c GLOBAL` is `0` and `grep -c- GLOBAL <file>` is `0` for `legacy-scan.ts`; the file emits no `IN` at all, in- either version, so no `IN (subquery)` on a `Distributed` table arises. For- `referrer-spikes.ts` both counts are `0` for `GLOBAL` and `1` for ` IN `- (`referrer_name IN`, a literal value list on both sides — never a subquery).-- **Verdict**: **22 statement pairs, all IDENTICAL** — 13 IDENTICAL and- **9 IDENTICAL ERROR**, the nine V1 defects reproduced byte-for-byte, error- text included. Nothing was fixed. (19 pairs for `legacy-scan.ts` — its ten- statements plus nine row-bearing twins — and 3 for `referrer-spikes.ts`. The- twelve `widget.rpc.ts` pairs are in `widget/widget.sql.proof.md`.)--## The nine defects, and why they are not this task's to fix--`legacy-scan.ts` has **no live callers** — `scanLegacyInsights` is exported from-`insight.service.ts` and reached by nothing but its own unit test, which mocks-the module. Nine of its ten statements have never been able to return a row:--| # | statement | defect | ClickHouse |-|---|---|---|---|-| 1 | `getTrafficSpikes` | `having('visitor_count','>','avg_previous_7_days * 2')` — clix escapes a `having` comparand as a **value**, so the threshold is a quoted string | 53 TYPE_MISMATCH |-| 2 | `getEventSurges` | same | 53 TYPE_MISMATCH |-| 3 | `getNewVisitorTrends` | `sessions.is_new` does not exist (+ the string threshold) | 47 UNKNOWN_IDENTIFIER |-| 4 | `getReferralSourceHighlights` | a window function (`sum(COUNT(*)) OVER ()`) referenced from `HAVING` | 184 ILLEGAL_AGGREGATION |-| 5 | `getSessionDurationChanges` | string threshold | 53 TYPE_MISMATCH |-| 6 | `getTopPerformingContent` | **none — this is the one that works** | 1 row |-| 7 | `getBounceRateImprovements` | string threshold | 53 TYPE_MISMATCH |-| 8 | `getReturningVisitorTrends` | `sessions.is_returning` does not exist (+ string threshold) | 47 UNKNOWN_IDENTIFIER |-| 9 | `getGeographicInterestShifts` | string threshold | 53 TYPE_MISMATCH |-| 10 | `getEventCompletionChanges` | `events.event_name` and `events.status` do not exist (+ string threshold) | 47 UNKNOWN_IDENTIFIER |--A conversion changes how values reach the server and nothing else, so all nine-are reproduced exactly. `IDENTICAL ERROR` is a passing case-(`docs/SQL_MIGRATION_RECIPE.md`, *Side-by-side proof*, step 5) and every one is-listed below with both error strings.--Because a failing statement proves only that two texts are equally invalid,-**each of the nine also has a row-bearing twin**: the same pair with the single-defective token removed — the string comparand replaced by a numeric literal on-both sides, `AND is_new = true` / `AND is_returning = true` / `AND status = …`-dropped from both, `event_name` → `name` on both, the illegal `HAVING` dropped-from both. Nothing else is touched, so the twin still differs between V1 and V2-in exactly the thing being proven: V1 carries inline literals where V2 carries-`{pN:Type}` params. The twins return 1–692 rows each and every one is IDENTICAL.-(A twin's `-- V2 params` line still lists the param the removed token used to-bind; ClickHouse ignores an unreferenced `param_pN`.)--**One twin is not deterministic, and it is V1 that is not deterministic.**-`getGeographicInterestShifts`'s twin selects-`lag(COUNT(*)) OVER (ORDER BY toWeek(created_at))` over a grouping in which many-rows share a week, so `prev_week_count` depends on the order ClickHouse happens-to feed the window — an earlier run of this harness reported the pair-`DIFFERENT`. Measured directly, 2026-09-07, running the **V1 text twice**:-`V1 run1 vs V1 run2` was `ordered: false, set: false`, while the same two runs-compared on `(country, visitor_count)` alone — every column except the window-one — were identical, as were V1-vs-V2 on those columns. So the instability is-V1's own and pre-dates the conversion; the run recorded below happened to agree-column-for-column. It costs nothing to say so: the shipped statement is-`IDENTICAL ERROR` and returns no rows at all.--## What binds and what does not--The rule applied, and the one measurement behind its exception:--- **Runtime values bind.** `projectId` and the ten `Date.now()`-derived windows- are `{pN:String}`. clix escaped a `Date` to `'YYYY-MM-DD HH:mm:ss'`- (`query-builder.ts:286`); `since()` uses core's `formatClickhouseDate`, which- the parity test pins against `@openpanel/db`'s, and binds the same text.-- **Module constants that clix escaped as values also bind** — the eight string- thresholds as `{pN:String}`, `0.5` as `{pN:Float64}`, `LIMIT 1` as- `{pN:UInt64}`. This is `referrer-spikes.ts`'s precedent (`MIN_SESSIONS_FLOOR`- and `MAX_REFERRERS` bind there).-- **The two boolean keywords stay SQL text.** `is_new = true` /- `is_returning = true` are written into the template rather than bound.- Measured 2026-09-07: ClickHouse substitutes a `Bool` parameter as a cast, so- `is_new = {p3:Bool}` is analysed as `is_new = _CAST('true', 'Bool')` and the- UNKNOWN_IDENTIFIER message — which echoes the whole normalised query — would- no longer match V1's byte-for-byte. A `String` parameter substitutes as a- plain quoted literal and matches, which is why `status = {p3:String}` binds- and prints as `status = 'completed'` inside V1's own error text. Both facts- are visible in the two error blocks below.-- **`session_timezone`** was `'UTC'` on every statement on both sides: clix- defaults its constructor timezone to `'UTC'` (`query-builder.ts:696-697`) and- sends it on every `execute()` (`:562`), and `CLIX_SESSION_TIMEZONE` keeps- sending it.--## Tests--There is no test in the tree that compares a statement built by this file.-`insight.service.test.ts` `mock.module`s `./src/legacy-scan` wholesale and-asserts only that `scanLegacyInsights` delegates to it; that test is unchanged-and passes. The factory's parameter widened from `Pick<ServiceDeps,'ch'>` to-`ChScope` (`Pick<ServiceDeps,'ch'|'logger'>`) because core's `chQuery` logs the-`query info` line with the request's id — `insight.service.ts` already passes a-full `ServiceDeps`.--## Grep gate--```-$ bash tooling/gates/p12-grep-gates.sh --report-```--| | sqlstring | clix | sql-builder |-|---|---|---|---|-| `insight/src/legacy-scan.ts` before | 0 | 11 | 0 |-| `insight/src/legacy-scan.ts` after | **absent from the report (0/0/0)** | | |-| `insight/src/referrer-spikes.ts` | **absent already (0/0/0)** — M12-002 | | |-| `widget/widget.rpc.ts` after | **absent from the report (0/0/0)** | | |-| TOTAL before | 16 | 21 | 1 |-| TOTAL after | **16** | **1** | **1** |--The one remaining `clix` line and the one remaining `sql-builder` line are both-`packages/db/index.ts`'s re-exports of the two definer files — the last line to-go, in M12-009.--## still non-zero--Files under `packages/core` that the report still lists after this task, and why-each is not this task's:--| file | column | count | why not this task's |-|---|---|---|---|-| `packages/core/package.json` | sqlstring | 2 | the `sqlstring` / `@types/sqlstring` dependency entries. They come out with the last `sqlstring` call site, which is in the buffers below — a manifest edit ahead of that would break the build. |-| `packages/core/src/buffers/group-buffer.ts` | sqlstring | 3 | ClickHouse **write**-path buffer, not a read query; not one of this task's three files and not in the P12 wave's read-path conversion list. |-| `packages/core/src/buffers/profile-backfill-buffer.ts` | sqlstring | 3 | same |-| `packages/core/src/buffers/profile-buffer.ts` | sqlstring | 2 | same |--`packages/core/src/v1-compat.ts` **was** on this list (clix 2) and is not any-more: its `compatChHelpers()` seam exposed `clix` for consumers that no longer-exist, and `legacy-scan.ts` and `widget.rpc.ts` were the last two files in core-reaching the builder. The dead member is removed in this task's diff — that is-what makes "nothing in core imports the builders" true, which is M12-009's-precondition. `TABLE_NAMES` / `chQuery` / the date helpers stay on that seam for-`misc.service.ts`.--Every other column for every other `packages/core` file is 0, and both the-`clix` and `sql-builder` TOTALs are now made up entirely of `packages/db`.--## Reading the case blocks, and reproducing them--`rows V1:` / `rows V2:` are the **first 300 characters** of each side's JSON-`data`, as an eyeball check. The comparison itself was made on the full arrays:-`JSON.stringify(v1.data) === JSON.stringify(v2.data)` and the same on `meta`,-which is what the `IDENTICAL` verdict on each block reports.--Either side of any block is reproducible with one `curl`. V1 goes as the body;-V2 goes as the body with its params as `param_pN`:--```bash-curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=<tz>&default_format=JSON' \- --data-binary '<the -- V1 statement>'--curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=<tz>' \- --data-urlencode 'default_format=JSON' \- --data-urlencode 'param_p1=<value>' [--data-urlencode 'param_p2=<value>' ...] \- --data-urlencode 'query=<the -- V2 statement>'-```--An `Array(String)` param is written in ClickHouse's own form, not JSON —-`param_p4=['Google','Bing']` — which is how the harness encoded it.--## Cases--### legacy/traffic_spike--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 6 ms / 5 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT referrer_name, toDate(created_at) as date, COUNT(*) as visitor_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= '2026-07-26 08:49:53' AND project_id = 'pincali-production' GROUP BY referrer_name, date HAVING visitor_count > 'avg_previous_7_days * 2' ORDER BY visitor_count DESC--- V2-SELECT referrer_name, toDate(created_at) as date, COUNT(*) as visitor_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY referrer_name, date HAVING visitor_count > {p3:String} ORDER BY visitor_count DESC--- V2 params: {"p1":"2026-07-26 08:49:53","p2":"pincali-production","p3":"avg_previous_7_days * 2"}-```--```-V1: Code: 53. DB::Exception: Cannot convert string 'avg_previous_7_days * 2' to type UInt64: while executing function greater on arguments count() UInt64 UInt64(size = 0), 'avg_previous_7_days * 2'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-V2: Code: 53. DB::Exception: Cannot convert string 'avg_previous_7_days * 2' to type UInt64: while executing function greater on arguments count() UInt64 UInt64(size = 0), 'avg_previous_7_days * 2'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-```--### legacy/traffic_spike (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 603/603; rows_read V1/V2 = 14187522/14187522; wall V1/V2 = 307 ms / 288 ms; `meta` V1/V2 = identical `[{"name":"referrer_name","type":"String"},{"name":"date","type":"Date"},{"name":"visitor_count","type":"UInt64"},{"name":"avg_previous_7_days","type":"Float64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT referrer_name, toDate(created_at) as date, COUNT(*) as visitor_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= '2026-07-26 08:49:53' AND project_id = 'pincali-production' GROUP BY referrer_name, date HAVING visitor_count > 100 ORDER BY visitor_count DESC--- V2-SELECT referrer_name, toDate(created_at) as date, COUNT(*) as visitor_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY referrer_name, date HAVING visitor_count > 100 ORDER BY visitor_count DESC--- V2 params: {"p1":"2026-07-26 08:49:53","p2":"pincali-production","p3":"avg_previous_7_days * 2"}-```--rows V1: `[{"referrer_name":"","date":"2026-07-28","visitor_count":421997,"avg_previous_7_days":6199.142857142857},{"referrer_name":"","date":"2026-08-03","visitor_count":370152,"avg_previous_7_days":26041.714285714286},{"referrer_name":"","date":"2026-07-29","visitor_count":363868,"avg_previous_7_days":8478}`-rows V2: `[{"referrer_name":"","date":"2026-07-28","visitor_count":421997,"avg_previous_7_days":6199.142857142857},{"referrer_name":"","date":"2026-08-03","visitor_count":370152,"avg_previous_7_days":26041.714285714286},{"referrer_name":"","date":"2026-07-29","visitor_count":363868,"avg_previous_7_days":8478}`--### legacy/event_surge--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 3 ms / 2 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toDate(created_at) as date, COUNT(*) as event_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= '2026-07-26 08:49:53' AND project_id = 'pincali-production' GROUP BY date HAVING event_count > 'avg_previous_7_days * 1.3' ORDER BY event_count DESC--- V2-SELECT toDate(created_at) as date, COUNT(*) as event_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY date HAVING event_count > {p3:String} ORDER BY event_count DESC--- V2 params: {"p1":"2026-07-26 08:49:53","p2":"pincali-production","p3":"avg_previous_7_days * 1.3"}-```--```-V1: Code: 53. DB::Exception: Cannot convert string 'avg_previous_7_days * 1.3' to type UInt64: while executing function greater on arguments count() UInt64 UInt64(size = 0), 'avg_previous_7_days * 1.3'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-V2: Code: 53. DB::Exception: Cannot convert string 'avg_previous_7_days * 1.3' to type UInt64: while executing function greater on arguments count() UInt64 UInt64(size = 0), 'avg_previous_7_days * 1.3'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-```--### legacy/event_surge (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 30/30; rows_read V1/V2 = 14187522/14187522; wall V1/V2 = 127 ms / 130 ms; `meta` V1/V2 = identical `[{"name":"date","type":"Date"},{"name":"event_count","type":"UInt64"},{"name":"avg_previous_7_days","type":"Float64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toDate(created_at) as date, COUNT(*) as event_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= '2026-07-26 08:49:53' AND project_id = 'pincali-production' GROUP BY date HAVING event_count > 100 ORDER BY event_count DESC--- V2-SELECT toDate(created_at) as date, COUNT(*) as event_count, avg(COUNT(*)) OVER (ORDER BY date ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING) as avg_previous_7_days FROM events WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY date HAVING event_count > 100 ORDER BY event_count DESC--- V2 params: {"p1":"2026-07-26 08:49:53","p2":"pincali-production","p3":"avg_previous_7_days * 1.3"}-```--rows V1: `[{"date":"2026-07-28","event_count":649909,"avg_previous_7_days":73284},{"date":"2026-07-29","event_count":596082,"avg_previous_7_days":361596.5},{"date":"2026-08-19","event_count":591628,"avg_previous_7_days":483219.28571428574},{"date":"2026-08-03","event_count":578025,"avg_previous_7_days":455115`-rows V2: `[{"date":"2026-07-28","event_count":649909,"avg_previous_7_days":73284},{"date":"2026-07-29","event_count":596082,"avg_previous_7_days":361596.5},{"date":"2026-08-19","event_count":591628,"avg_previous_7_days":483219.28571428574},{"date":"2026-08-03","event_count":578025,"avg_previous_7_days":455115`--### legacy/new_visitor_trend--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 2 ms / 2 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toMonth(created_at) as month, COUNT(DISTINCT device_id) as new_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY month) as prev_month_visitors FROM sessions WHERE created_at >= '2026-06-26 08:49:53' AND project_id = 'pincali-production' AND is_new = true GROUP BY month HAVING new_visitors > 'prev_month_visitors * 1.2' ORDER BY month DESC--- V2-SELECT toMonth(created_at) as month, COUNT(DISTINCT device_id) as new_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY month) as prev_month_visitors FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} AND is_new = true GROUP BY month HAVING new_visitors > {p3:String} ORDER BY month DESC--- V2 params: {"p1":"2026-06-26 08:49:53","p2":"pincali-production","p3":"prev_month_visitors * 1.2"}-```--```-V1: Code: 47. DB::Exception: Unknown expression or function identifier `is_new` in scope SELECT toMonth(created_at) AS month, COUNTDistinct(device_id) AS new_visitors, lag(COUNTDistinct(device_id)) OVER (ORDER BY month ASC) AS prev_month_visitors FROM sessions WHERE (created_at >= '2026-06-26 08:49:53') AND (project_id = 'pincali-production') AND (is_new = true) GROUP BY month HAVING new_visitors > 'prev_month_visitors * 1.2' ORDER BY month DESC. (UNKNOWN_IDENTIFIER) (version 26.1.3.52 (official build))-V2: Code: 47. DB::Exception: Unknown expression or function identifier `is_new` in scope SELECT toMonth(created_at) AS month, COUNTDistinct(device_id) AS new_visitors, lag(COUNTDistinct(device_id)) OVER (ORDER BY month ASC) AS prev_month_visitors FROM sessions WHERE (created_at >= '2026-06-26 08:49:53') AND (project_id = 'pincali-production') AND (is_new = true) GROUP BY month HAVING new_visitors > 'prev_month_visitors * 1.2' ORDER BY month DESC. (UNKNOWN_IDENTIFIER) (version 26.1.3.52 (official build))-```--### legacy/new_visitor_trend (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 2243553/2243553; wall V1/V2 = 303 ms / 260 ms; `meta` V1/V2 = identical `[{"name":"month","type":"UInt8"},{"name":"new_visitors","type":"UInt64"},{"name":"prev_month_visitors","type":"UInt64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toMonth(created_at) as month, COUNT(DISTINCT device_id) as new_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY month) as prev_month_visitors FROM sessions WHERE created_at >= '2026-06-26 08:49:53' AND project_id = 'pincali-production' GROUP BY month HAVING new_visitors > 100 ORDER BY month DESC--- V2-SELECT toMonth(created_at) as month, COUNT(DISTINCT device_id) as new_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY month) as prev_month_visitors FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY month HAVING new_visitors > 100 ORDER BY month DESC--- V2 params: {"p1":"2026-06-26 08:49:53","p2":"pincali-production","p3":"prev_month_visitors * 1.2"}-```--rows V1: `[{"month":8,"new_visitors":1640718,"prev_month_visitors":316069},{"month":7,"new_visitors":316069,"prev_month_visitors":0}]`-rows V2: `[{"month":8,"new_visitors":1640718,"prev_month_visitors":316069},{"month":7,"new_visitors":316069,"prev_month_visitors":0}]`--### legacy/referral_source--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 2 ms / 1 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT referrer_name, COUNT(*) as count, COUNT(*) / sum(COUNT(*)) OVER () as percentage FROM sessions WHERE created_at >= '2026-08-18 08:49:53' AND project_id = 'pincali-production' GROUP BY referrer_name HAVING percentage >= 0.5 ORDER BY count DESC--- V2-SELECT referrer_name, COUNT(*) as count, COUNT(*) / sum(COUNT(*)) OVER () as percentage FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY referrer_name HAVING percentage >= {p3:Float64} ORDER BY count DESC--- V2 params: {"p1":"2026-08-18 08:49:53","p2":"pincali-production","p3":0.5}-```--```-V1: Code: 184. DB::Exception: Window function sum(COUNT(*)) OVER () is found in HAVING in query. (ILLEGAL_AGGREGATION) (version 26.1.3.52 (official build))-V2: Code: 184. DB::Exception: Window function sum(COUNT(*)) OVER () is found in HAVING in query. (ILLEGAL_AGGREGATION) (version 26.1.3.52 (official build))-```--### legacy/referral_source (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 692/692; rows_read V1/V2 = 761519/761519; wall V1/V2 = 18 ms / 18 ms; `meta` V1/V2 = identical `[{"name":"referrer_name","type":"String"},{"name":"count","type":"UInt64"},{"name":"percentage","type":"Float64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT referrer_name, COUNT(*) as count, COUNT(*) / sum(COUNT(*)) OVER () as percentage FROM sessions WHERE created_at >= '2026-08-18 08:49:53' AND project_id = 'pincali-production' GROUP BY referrer_name ORDER BY count DESC--- V2-SELECT referrer_name, COUNT(*) as count, COUNT(*) / sum(COUNT(*)) OVER () as percentage FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY referrer_name ORDER BY count DESC--- V2 params: {"p1":"2026-08-18 08:49:53","p2":"pincali-production","p3":0.5}-```--rows V1: `[{"referrer_name":"","count":488272,"percentage":0.7115530904713745},{"referrer_name":"Google","count":90187,"percentage":0.13142846317286647},{"referrer_name":"easybroker.com","count":71608,"percentage":0.10435350317543128},{"referrer_name":"ChatGPT","count":13048,"percentage":0.019014698210158467}`-rows V2: `[{"referrer_name":"","count":488272,"percentage":0.7115530904713745},{"referrer_name":"Google","count":90187,"percentage":0.13142846317286647},{"referrer_name":"easybroker.com","count":71608,"percentage":0.10435350317543128},{"referrer_name":"ChatGPT","count":13048,"percentage":0.019014698210158467}`--### legacy/session_duration--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 2 ms / 2 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toWeek(created_at) as week, avg(duration) as avg_duration, lag(avg(duration)) OVER (ORDER BY week) as prev_week_duration FROM sessions WHERE created_at >= '2026-08-11 08:49:53' AND project_id = 'pincali-production' GROUP BY week HAVING avg_duration > 'prev_week_duration * 1.25' ORDER BY week DESC--- V2-SELECT toWeek(created_at) as week, avg(duration) as avg_duration, lag(avg(duration)) OVER (ORDER BY week) as prev_week_duration FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY week HAVING avg_duration > {p3:String} ORDER BY week DESC--- V2 params: {"p1":"2026-08-11 08:49:53","p2":"pincali-production","p3":"prev_week_duration * 1.25"}-```--```-V1: Code: 53. DB::Exception: Cannot convert string 'prev_week_duration * 1.25' to type Float64: while executing function greater on arguments avg(__table1.duration) Float64 Float64(size = 0), 'prev_week_duration * 1.25'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-V2: Code: 53. DB::Exception: Cannot convert string 'prev_week_duration * 1.25' to type Float64: while executing function greater on arguments avg(__table1.duration) Float64 Float64(size = 0), 'prev_week_duration * 1.25'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-```--### legacy/session_duration (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 4/4; rows_read V1/V2 = 1162483/1162483; wall V1/V2 = 23 ms / 28 ms; `meta` V1/V2 = identical `[{"name":"week","type":"UInt8"},{"name":"avg_duration","type":"Float64"},{"name":"prev_week_duration","type":"Float64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toWeek(created_at) as week, avg(duration) as avg_duration, lag(avg(duration)) OVER (ORDER BY week) as prev_week_duration FROM sessions WHERE created_at >= '2026-08-11 08:49:53' AND project_id = 'pincali-production' GROUP BY week HAVING avg_duration > 10 ORDER BY week DESC--- V2-SELECT toWeek(created_at) as week, avg(duration) as avg_duration, lag(avg(duration)) OVER (ORDER BY week) as prev_week_duration FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY week HAVING avg_duration > 10 ORDER BY week DESC--- V2 params: {"p1":"2026-08-11 08:49:53","p2":"pincali-production","p3":"prev_week_duration * 1.25"}-```--rows V1: `[{"week":35,"avg_duration":63509.807911080155,"prev_week_duration":127541.13198440011},{"week":34,"avg_duration":127541.13198440011,"prev_week_duration":165461.89794130405},{"week":33,"avg_duration":165461.89794130405,"prev_week_duration":151476.37365892096},{"week":32,"avg_duration":151476.37365892`-rows V2: `[{"week":35,"avg_duration":63509.807911080155,"prev_week_duration":127541.13198440011},{"week":34,"avg_duration":127541.13198440011,"prev_week_duration":165461.89794130405},{"week":33,"avg_duration":165461.89794130405,"prev_week_duration":151476.37365892096},{"week":32,"avg_duration":151476.37365892`--### legacy/top_content--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 14187522/14187522; wall V1/V2 = 1205 ms / 1167 ms; `meta` V1/V2 = identical `[{"name":"path","type":"String"},{"name":"view_count","type":"UInt64"},{"name":"unique_viewers","type":"UInt64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT path, COUNT(*) as view_count, COUNT(DISTINCT device_id) as unique_viewers FROM events WHERE created_at >= '2026-07-26 08:49:53' AND project_id = 'pincali-production' GROUP BY path ORDER BY view_count DESC LIMIT 1--- V2-SELECT path, COUNT(*) as view_count, COUNT(DISTINCT device_id) as unique_viewers FROM events WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY path ORDER BY view_count DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"2026-07-26 08:49:53","p2":"pincali-production","p3":1}-```--rows V1: `[{"path":"/","view_count":474556,"unique_viewers":82587}]`-rows V2: `[{"path":"/","view_count":474556,"unique_viewers":82587}]`--### legacy/bounce_rate--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 3 ms / 2 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toMonth(created_at) as month, sum(is_bounce) / COUNT(*) as bounce_rate, lag(sum(is_bounce) / COUNT(*)) OVER (ORDER BY month) as prev_month_bounce_rate FROM sessions WHERE created_at >= '2026-06-26 08:49:53' AND project_id = 'pincali-production' GROUP BY month HAVING bounce_rate < 'prev_month_bounce_rate * 0.85' ORDER BY month DESC--- V2-SELECT toMonth(created_at) as month, sum(is_bounce) / COUNT(*) as bounce_rate, lag(sum(is_bounce) / COUNT(*)) OVER (ORDER BY month) as prev_month_bounce_rate FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY month HAVING bounce_rate < {p3:String} ORDER BY month DESC--- V2 params: {"p1":"2026-06-26 08:49:53","p2":"pincali-production","p3":"prev_month_bounce_rate * 0.85"}-```--```-V1: Code: 53. DB::Exception: Cannot convert string 'prev_month_bounce_rate * 0.85' to type Float64: while executing function less on arguments divide(sum(__table1.is_bounce), count()) Float64 Float64(size = 0), 'prev_month_bounce_rate * 0.85'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-V2: Code: 53. DB::Exception: Cannot convert string 'prev_month_bounce_rate * 0.85' to type Float64: while executing function less on arguments divide(sum(__table1.is_bounce), count()) Float64 Float64(size = 0), 'prev_month_bounce_rate * 0.85'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-```--### legacy/bounce_rate (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 2243553/2243553; wall V1/V2 = 31 ms / 38 ms; `meta` V1/V2 = identical `[{"name":"month","type":"UInt8"},{"name":"bounce_rate","type":"Float64"},{"name":"prev_month_bounce_rate","type":"Float64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toMonth(created_at) as month, sum(is_bounce) / COUNT(*) as bounce_rate, lag(sum(is_bounce) / COUNT(*)) OVER (ORDER BY month) as prev_month_bounce_rate FROM sessions WHERE created_at >= '2026-06-26 08:49:53' AND project_id = 'pincali-production' GROUP BY month HAVING bounce_rate < 0.85 ORDER BY month DESC--- V2-SELECT toMonth(created_at) as month, sum(is_bounce) / COUNT(*) as bounce_rate, lag(sum(is_bounce) / COUNT(*)) OVER (ORDER BY month) as prev_month_bounce_rate FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY month HAVING bounce_rate < 0.85 ORDER BY month DESC--- V2 params: {"p1":"2026-06-26 08:49:53","p2":"pincali-production","p3":"prev_month_bounce_rate * 0.85"}-```--rows V1: `[{"month":8,"bounce_rate":0.7916161871668908,"prev_month_bounce_rate":0.8395492525786178},{"month":7,"bounce_rate":0.8395492525786178,"prev_month_bounce_rate":0}]`-rows V2: `[{"month":8,"bounce_rate":0.7916161871668908,"prev_month_bounce_rate":0.8395492525786178},{"month":7,"bounce_rate":0.8395492525786178,"prev_month_bounce_rate":0}]`--### legacy/returning_visitors--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 2 ms / 2 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toQuarter(created_at) as quarter, COUNT(DISTINCT device_id) as returning_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY quarter) as prev_quarter_visitors FROM sessions WHERE created_at >= '2026-02-26 08:49:53' AND project_id = 'pincali-production' AND is_returning = true GROUP BY quarter HAVING returning_visitors > 'prev_quarter_visitors * 1.1' ORDER BY quarter DESC--- V2-SELECT toQuarter(created_at) as quarter, COUNT(DISTINCT device_id) as returning_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY quarter) as prev_quarter_visitors FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} AND is_returning = true GROUP BY quarter HAVING returning_visitors > {p3:String} ORDER BY quarter DESC--- V2 params: {"p1":"2026-02-26 08:49:53","p2":"pincali-production","p3":"prev_quarter_visitors * 1.1"}-```--```-V1: Code: 47. DB::Exception: Unknown expression or function identifier `is_returning` in scope SELECT toQuarter(created_at) AS quarter, COUNTDistinct(device_id) AS returning_visitors, lag(COUNTDistinct(device_id)) OVER (ORDER BY quarter ASC) AS prev_quarter_visitors FROM sessions WHERE (created_at >= '2026-02-26 08:49:53') AND (project_id = 'pincali-production') AND (is_returning = true) GROUP BY quarter HAVING returning_visitors > 'prev_quarter_visitors * 1.1' ORDER BY quarter DESC. (UNKNOWN_IDENTIFIER) (version 26.1.3.52 (official build))-V2: Code: 47. DB::Exception: Unknown expression or function identifier `is_returning` in scope SELECT toQuarter(created_at) AS quarter, COUNTDistinct(device_id) AS returning_visitors, lag(COUNTDistinct(device_id)) OVER (ORDER BY quarter ASC) AS prev_quarter_visitors FROM sessions WHERE (created_at >= '2026-02-26 08:49:53') AND (project_id = 'pincali-production') AND (is_returning = true) GROUP BY quarter HAVING returning_visitors > 'prev_quarter_visitors * 1.1' ORDER BY quarter DESC. (UNKNOWN_IDENTIFIER) (version 26.1.3.52 (official build))-```--### legacy/returning_visitors (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 2243553/2243553; wall V1/V2 = 247 ms / 277 ms; `meta` V1/V2 = identical `[{"name":"quarter","type":"UInt8"},{"name":"returning_visitors","type":"UInt64"},{"name":"prev_quarter_visitors","type":"UInt64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toQuarter(created_at) as quarter, COUNT(DISTINCT device_id) as returning_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY quarter) as prev_quarter_visitors FROM sessions WHERE created_at >= '2026-02-26 08:49:53' AND project_id = 'pincali-production' GROUP BY quarter HAVING returning_visitors > 100 ORDER BY quarter DESC--- V2-SELECT toQuarter(created_at) as quarter, COUNT(DISTINCT device_id) as returning_visitors, lag(COUNT(DISTINCT device_id)) OVER (ORDER BY quarter) as prev_quarter_visitors FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY quarter HAVING returning_visitors > 100 ORDER BY quarter DESC--- V2 params: {"p1":"2026-02-26 08:49:53","p2":"pincali-production","p3":"prev_quarter_visitors * 1.1"}-```--rows V1: `[{"quarter":3,"returning_visitors":1956782,"prev_quarter_visitors":0}]`-rows V2: `[{"quarter":3,"returning_visitors":1956782,"prev_quarter_visitors":0}]`--### legacy/geographic_shift--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 3 ms / 2 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT country, COUNT(*) as visitor_count, lag(COUNT(*)) OVER (ORDER BY toWeek(created_at)) as prev_week_count FROM sessions WHERE created_at >= '2026-08-11 08:49:53' AND project_id = 'pincali-production' GROUP BY country, toWeek(created_at) HAVING visitor_count > 'prev_week_count * 1.5' ORDER BY visitor_count DESC--- V2-SELECT country, COUNT(*) as visitor_count, lag(COUNT(*)) OVER (ORDER BY toWeek(created_at)) as prev_week_count FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY country, toWeek(created_at) HAVING visitor_count > {p3:String} ORDER BY visitor_count DESC--- V2 params: {"p1":"2026-08-11 08:49:53","p2":"pincali-production","p3":"prev_week_count * 1.5"}-```--```-V1: Code: 53. DB::Exception: Cannot convert string 'prev_week_count * 1.5' to type UInt64: while executing function greater on arguments count() UInt64 UInt64(size = 0), 'prev_week_count * 1.5'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-V2: Code: 53. DB::Exception: Cannot convert string 'prev_week_count * 1.5' to type UInt64: while executing function greater on arguments count() UInt64 UInt64(size = 0), 'prev_week_count * 1.5'_String String Const(size = 0, String(size = 1)). (TYPE_MISMATCH) (version 26.1.3.52 (official build))-```--### legacy/geographic_shift (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 220/220; rows_read V1/V2 = 1162483/1162483; wall V1/V2 = 29 ms / 27 ms; `meta` V1/V2 = identical `[{"name":"country","type":"LowCardinality(FixedString(2))"},{"name":"visitor_count","type":"UInt64"},{"name":"prev_week_count","type":"UInt64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT country, COUNT(*) as visitor_count, lag(COUNT(*)) OVER (ORDER BY toWeek(created_at)) as prev_week_count FROM sessions WHERE created_at >= '2026-08-11 08:49:53' AND project_id = 'pincali-production' GROUP BY country, toWeek(created_at) HAVING visitor_count > 100 ORDER BY visitor_count DESC--- V2-SELECT country, COUNT(*) as visitor_count, lag(COUNT(*)) OVER (ORDER BY toWeek(created_at)) as prev_week_count FROM sessions WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY country, toWeek(created_at) HAVING visitor_count > 100 ORDER BY visitor_count DESC--- V2 params: {"p1":"2026-08-11 08:49:53","p2":"pincali-production","p3":"prev_week_count * 1.5"}-```--rows V1: `[{"country":"MX","visitor_count":208577,"prev_week_count":140},{"country":"MX","visitor_count":202338,"prev_week_count":234},{"country":"MX","visitor_count":146394,"prev_week_count":1904},{"country":"US","visitor_count":109085,"prev_week_count":128},{"country":"US","visitor_count":37021,"prev_week_c`-rows V2: `[{"country":"MX","visitor_count":208577,"prev_week_count":140},{"country":"MX","visitor_count":202338,"prev_week_count":234},{"country":"MX","visitor_count":146394,"prev_week_count":1904},{"country":"US","visitor_count":109085,"prev_week_count":128},{"country":"US","visitor_count":37021,"prev_week_c`--### legacy/event_completion--**statement** — IDENTICAL ERROR; both sides fail; wall V1/V2 = 2 ms / 1 ms; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT event_name, toMonth(created_at) as month, COUNT(*) as completion_count, lag(COUNT(*)) OVER (ORDER BY month) as prev_month_count FROM events WHERE created_at >= '2026-06-26 08:49:53' AND project_id = 'pincali-production' AND status = 'completed' GROUP BY event_name, month HAVING completion_count > 'prev_month_count * 1.05' ORDER BY month DESC--- V2-SELECT event_name, toMonth(created_at) as month, COUNT(*) as completion_count, lag(COUNT(*)) OVER (ORDER BY month) as prev_month_count FROM events WHERE created_at >= {p1:String} AND project_id = {p2:String} AND status = {p3:String} GROUP BY event_name, month HAVING completion_count > {p4:String} ORDER BY month DESC--- V2 params: {"p1":"2026-06-26 08:49:53","p2":"pincali-production","p3":"completed","p4":"prev_month_count * 1.05"}-```--```-V1: Code: 47. DB::Exception: Unknown expression identifier `event_name` in scope SELECT event_name, toMonth(created_at) AS month, COUNT(*) AS completion_count, lag(COUNT(*)) OVER (ORDER BY month ASC) AS prev_month_count FROM events WHERE (created_at >= '2026-06-26 08:49:53') AND (project_id = 'pincali-production') AND (status = 'completed') GROUP BY event_name, month HAVING completion_count > 'prev_month_count * 1.05' ORDER BY month DESC. (UNKNOWN_IDENTIFIER) (version 26.1.3.52 (official build))-V2: Code: 47. DB::Exception: Unknown expression identifier `event_name` in scope SELECT event_name, toMonth(created_at) AS month, COUNT(*) AS completion_count, lag(COUNT(*)) OVER (ORDER BY month ASC) AS prev_month_count FROM events WHERE (created_at >= '2026-06-26 08:49:53') AND (project_id = 'pincali-production') AND (status = 'completed') GROUP BY event_name, month HAVING completion_count > 'prev_month_count * 1.05' ORDER BY month DESC. (UNKNOWN_IDENTIFIER) (version 26.1.3.52 (official build))-```--### legacy/event_completion (row-bearing twin)--_defective token removed identically on both sides_--**statement** — IDENTICAL; rows V1/V2 = 99/99; rows_read V1/V2 = 14187522/14187522; wall V1/V2 = 266 ms / 267 ms; `meta` V1/V2 = identical `[{"name":"name","type":"LowCardinality(String)"},{"name":"month","type":"UInt8"},{"name":"completion_count","type":"UInt64"},{"name":"prev_month_count","type":"UInt64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT name, toMonth(created_at) as month, COUNT(*) as completion_count, lag(COUNT(*)) OVER (ORDER BY month) as prev_month_count FROM events WHERE created_at >= '2026-06-26 08:49:53' AND project_id = 'pincali-production' GROUP BY name, month HAVING completion_count > 100 ORDER BY month DESC--- V2-SELECT name, toMonth(created_at) as month, COUNT(*) as completion_count, lag(COUNT(*)) OVER (ORDER BY month) as prev_month_count FROM events WHERE created_at >= {p1:String} AND project_id = {p2:String} GROUP BY name, month HAVING completion_count > 100 ORDER BY month DESC--- V2 params: {"p1":"2026-06-26 08:49:53","p2":"pincali-production","p3":"completed","p4":"prev_month_count * 1.05"}-```--rows V1: `[{"name":"viewed_properties_search_list","month":8,"completion_count":1007534,"prev_month_count":7070},{"name":"copied_location_link","month":8,"completion_count":3733,"prev_month_count":4142},{"name":"view_board","month":8,"completion_count":7070,"prev_month_count":2976968},{"name":"screen_view","m`-rows V2: `[{"name":"viewed_properties_search_list","month":8,"completion_count":1007534,"prev_month_count":7070},{"name":"copied_location_link","month":8,"completion_count":3733,"prev_month_count":4142},{"name":"view_board","month":8,"completion_count":7070,"prev_month_count":2976968},{"name":"screen_view","m`---## referrer-spikes.ts--`packages/core/src/modules/insight/src/referrer-spikes.ts` is the task's second-insight file. It was already converted off clix by **M12-002** (commit-`4cd0d76b`) — `getRawWhereClause` started returning a `SqlFragment` carrying-params and clix's `execute()` (`query-builder.ts:552`) has no `query_params`-slot to carry them — and it scores **0/0/0** on the grep gate today. There was-nothing left in it for this task to convert.--What is recorded below is a re-execution, today, of its three statements V1-against V2 on the same data and the same inputs. **Provenance, stated plainly:**-the V2 side was captured from the real `getReferrerSpikes(deps, input)` in this-process, behind a recording client that *also executes*, so the second and third-statements receive the real referrer list the first one returns. The V1 side is-the clix text recorded by M12-002's own side-by-side proof-(`packages/core/src/modules/chart/src/filter-where.sql.proof.md`, §*Consumer-conversion: referrer-spikes.ts*) — the clix builder is gone from this module, so-V1 could not be re-derived by calling it, and re-deriving it would only-reproduce that record. Both texts were executed here, today, against local-prod-copy `openpanel`.--Inputs: project `secure-privacy`, filters-`[{name:'country',operator:'is',value:['US']}]`, window-`2026-07-01 00:00:00` … `2026-07-08 00:00:00`, interval `day`,-`session_timezone=UTC` on both sides. The eight referrer names the second-statement binds are the ones the first statement returned in this run, and they-match M12-002's recorded list exactly.--`referrer_name IN (…)` (V1) → `referrer_name IN {p4:Array(String)}` (V2) is a-**literal value list on both sides, never a subquery**, so the distributed-`IN`-trap does not arise and no `GLOBAL` was added or removed.--### referrer-spikes/topReferrers--**statement** — IDENTICAL; rows V1/V2 = 8/8; rows_read V1/V2 = 65436/65436; wall V1/V2 = 7 ms / 11 ms; `meta` V1/V2 = identical `[{"name":"referrer_name","type":"String"},{"name":"total","type":"Int64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT referrer_name, sum(sign) AS total FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND referrer_name != '' AND referrer_name IS NOT NULL AND country = 'US' GROUP BY referrer_name HAVING sum(sign) >= 10 ORDER BY total DESC LIMIT 50--- V2-SELECT referrer_name, sum(sign) AS total FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND referrer_name != '' AND referrer_name IS NOT NULL AND country = {p4:String} GROUP BY referrer_name HAVING sum(sign) >= {p5:UInt64} ORDER BY total DESC LIMIT {p6:UInt64}--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"US","p5":10,"p6":50}-```--rows V1: `[{"referrer_name":"Google","total":12327},{"referrer_name":"https://www.bwtrailerhitches.com","total":54},{"referrer_name":"https://www.kingandprince.com","total":48},{"referrer_name":"https://www.propper.com","total":31},{"referrer_name":"Bing","total":20},{"referrer_name":"DuckDuckGo","total":13},`-rows V2: `[{"referrer_name":"Google","total":12327},{"referrer_name":"https://www.bwtrailerhitches.com","total":54},{"referrer_name":"https://www.kingandprince.com","total":48},{"referrer_name":"https://www.propper.com","total":31},{"referrer_name":"Bing","total":20},{"referrer_name":"DuckDuckGo","total":13},`--### referrer-spikes/perBucketSessions--**statement** — IDENTICAL; rows V1/V2 = 47/47; rows_read V1/V2 = 65436/65436; wall V1/V2 = 8 ms / 7 ms; `meta` V1/V2 = identical `[{"name":"date","type":"DateTime"},{"name":"referrer_name","type":"String"},{"name":"sessions","type":"Int64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toStartOfDay(created_at) AS date, referrer_name, sum(sign) AS sessions FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND referrer_name IN ('Google', 'https://www.bwtrailerhitches.com', 'https://www.kingandprince.com', 'https://www.propper.com', 'Bing', 'DuckDuckGo', 'Twitter', 'https://www.packetsofhope.com') AND country = 'US' GROUP BY date, referrer_name HAVING sum(sign) > 0 ORDER BY date ASC--- V2-SELECT toStartOfDay(created_at) AS date, referrer_name, sum(sign) AS sessions FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND referrer_name IN {p4:Array(String)} AND country = {p5:String} GROUP BY date, referrer_name HAVING sum(sign) > 0 ORDER BY date ASC--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":["Google","https://www.bwtrailerhitches.com","https://www.kingandprince.com","https://www.propper.com","Bing","DuckDuckGo","Twitter","https://www.packetsofhope.com"],"p5":"US"}-```--rows V1: `[{"date":"2026-07-01 00:00:00","referrer_name":"https://www.bwtrailerhitches.com","sessions":4},{"date":"2026-07-01 00:00:00","referrer_name":"https://www.kingandprince.com","sessions":9},{"date":"2026-07-01 00:00:00","referrer_name":"https://www.propper.com","sessions":8},{"date":"2026-07-01 00:00:`-rows V2: `[{"date":"2026-07-01 00:00:00","referrer_name":"https://www.bwtrailerhitches.com","sessions":4},{"date":"2026-07-01 00:00:00","referrer_name":"https://www.kingandprince.com","sessions":9},{"date":"2026-07-01 00:00:00","referrer_name":"https://www.propper.com","sessions":8},{"date":"2026-07-01 00:00:`--### referrer-spikes/bucketTotals--**statement** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 65436/65436; wall V1/V2 = 7 ms / 8 ms; `meta` V1/V2 = identical `[{"name":"date","type":"DateTime"},{"name":"total","type":"Int64"}]`; clickhouse_settings: session_timezone=UTC/UTC.--```sql--- V1-SELECT toStartOfDay(created_at) AS date, sum(sign) AS total FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND country = 'US' GROUP BY date HAVING sum(sign) > 0--- V2-SELECT toStartOfDay(created_at) AS date, sum(sign) AS total FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND country = {p4:String} GROUP BY date HAVING sum(sign) > 0--- V2 params: {"p1":"secure-privacy","p2":"2026-07-01 00:00:00","p3":"2026-07-08 00:00:00","p4":"US"}-```--rows V1: `[{"date":"2026-07-07 00:00:00","total":2384},{"date":"2026-07-01 00:00:00","total":1045},{"date":"2026-07-02 00:00:00","total":678},{"date":"2026-07-04 00:00:00","total":2099},{"date":"2026-07-05 00:00:00","total":2152},{"date":"2026-07-03 00:00:00","total":3065},{"date":"2026-07-06 00:00:00","total`-rows V2: `[{"date":"2026-07-07 00:00:00","total":2384},{"date":"2026-07-01 00:00:00","total":1045},{"date":"2026-07-02 00:00:00","total":678},{"date":"2026-07-04 00:00:00","total":2099},{"date":"2026-07-05 00:00:00","total":2152},{"date":"2026-07-03 00:00:00","total":3065},{"date":"2026-07-06 00:00:00","total`-diff --git a/packages/core/src/modules/insight/src/legacy-scan.ts b/packages/core/src/modules/insight/src/legacy-scan.tsindex 2a2dd5ffe..3b218bb0c 100644--- a/packages/core/src/modules/insight/src/legacy-scan.ts+++ b/packages/core/src/modules/insight/src/legacy-scan.ts@@ -7,8 +7,8 @@// clix always sent `session_timezone` (query-builder.ts:562) and defaulted it// to `'UTC'` (`:696`), so `chQuery` sends the same value.//-// Nine of the ten statements are BROKEN AND WERE ALWAYS BROKEN — see-// `legacy-scan.sql.proof.md`. clix's `having(column, operator, value)` escapes+// Nine of the ten statements are BROKEN AND WERE ALWAYS BROKEN. clix's+// `having(column, operator, value)` escaped// its comparand as a VALUE, so every `'<column> * <n>'` threshold below reaches// ClickHouse as a quoted string and the comparison fails with TYPE_MISMATCH;// three more read columns (`is_new`, `is_returning`, `event_name`, `status`)diff --git a/packages/core/src/modules/mcp/src/tools/analytics/property-values.sql.proof.md b/packages/core/src/modules/mcp/src/tools/analytics/property-values.sql.proof.mddeleted file mode 100644index 454b8dd8d..000000000--- a/packages/core/src/modules/mcp/src/tools/analytics/property-values.sql.proof.md+++ /dev/null@@ -1,218 +0,0 @@-# property-values.ts — V1 → V2 result-set proof (M12-006)--Both ClickHouse statements-`packages/core/src/modules/mcp/src/tools/analytics/property-values.ts` runs-(three cases, because `list_event_properties` has an optional `eventName`-branch), executed V1 against V2 on the local prod-copy `openpanel`. V1 is the-file at commit `78098bdc`-(`git show HEAD:packages/core/src/modules/mcp/src/tools/analytics/property-values.ts`),-which builds both statements with `clix`; V2 is the converted file, every value-bound as a `{pN:Type}` param. **Both files were imported into one Bun process-and their tools registered against the same stub MCP server**, then invoked with-the same inputs — the SQL below was produced by calling the real registered tool-handlers with a `deps.ch.query` stub that captures-`{query, query_params, clickhouse_settings}`, never by retyping V1 by hand. Each-captured statement was then executed through the local HTTP interface at-`format: 'JSON'` with the settings its own side asked for; V1 went as `query`,-V2 as `query` + `param_pN`. `data` was compared row-for-row and `meta`-column-for-column.--No case needed set comparison: both statements carry a total `ORDER BY`-(`property_key ASC, name ASC` on the first, `created_at DESC` on the second) and-both sides returned byte-identical row order.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,850,903 events. Project fixture- `pincali-production`, whose `event_property_values_mv` rows cover 500+- `(property_key, name)` pairs, 299 of them under `screen_view`, and 1,288,989+- rows under `(viewed_property, property_id)`. Nothing is empty here — every- case below returns its full `LIMIT` window or close to it.-- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either- direction.** `grep -c 'GLOBAL'` is `0` on the V1 file and `0` on the V2 file,- and `grep -c ' IN '` is `0` on both — neither statement contains an `IN` of- any kind, so the distributed-`IN` trap does not arise here at all.-- **Verdict**: **3 cases, all IDENTICAL.**--## `session_timezone`--`clix(client)` with no timezone argument defaults to `'UTC'`-(`query-builder.ts:696-697`) and sends it as-`clickhouse_settings.session_timezone` on every `execute()` (`:562`). Both-statements came off `clix`, so both sent it; V2 sends it through-`CLIX_SESSION_TIMEZONE` and the capture confirms `session_timezone=UTC` on both-sides of all three cases. Dropping it would have changed the meaning of-`created_at DESC` ordering under a non-UTC server default, which is why it is-pinned rather than inherited.--## `list_event_properties` — no `eventName`--**statement** — IDENTICAL; rows V1/V2 = **500/500** (the `LIMIT` window, full);-`meta` V1/V2 =-`[{"name":"property_key","type":"String"},{"name":"event_name","type":"LowCardinality(String)"}]`;-rows_read V1/V2 = 131456/131456; wall V1/V2 = 16 ms / 13 ms;-clickhouse_settings: `session_timezone=UTC` (both). First rows on both sides:-`{"property_key":"__bot","event_name":"applied_filters"}`,-`{"property_key":"__bot","event_name":"authentication_modal_opened"}`, …--```sql--- V1-SELECT property_key, name as event_name FROM event_property_values_mv-WHERE project_id = 'pincali-production'-GROUP BY property_key, name-ORDER BY property_key ASC, name ASC-LIMIT 500--- V2-SELECT property_key, name as event_name FROM event_property_values_mv-WHERE project_id = {p1:String}-GROUP BY property_key, name-ORDER BY property_key ASC, name ASC-LIMIT {p2:UInt64}--- V2 params: {"p1":"pincali-production","p2":500}-```--`LIMIT {p2:UInt64}` is a bound parameter, not inlined text: `UInt64` is the-right type because the scan limit is a compile-time constant that cannot be-negative (recipe, *Numbers*). V1's `500` and V2's bound `500` produce the same-window, which the equal 500-row results and equal `rows_read` show.--## `list_event_properties` — `eventName = 'screen_view'`--**statement** — IDENTICAL; rows V1/V2 = **299/299**; `meta` V1/V2 as above;-rows_read V1/V2 = 98688/98688; wall V1/V2 = 14 ms / 11 ms; clickhouse_settings:-`session_timezone=UTC` (both).--This is the conditional-fragment case: V1 appended a second `.where('name','=',…)`-to the builder after `orderBy`/`limit` and clix folded it into the WHERE in call-order; V2 splices `sql\` AND name = ${sql.string(eventName)}\`` (or `sql.empty`)-into the same position. The two texts below differ only in the binding.--```sql--- V1-SELECT property_key, name as event_name FROM event_property_values_mv-WHERE project_id = 'pincali-production' AND name = 'screen_view'-GROUP BY property_key, name-ORDER BY property_key ASC, name ASC-LIMIT 500--- V2-SELECT property_key, name as event_name FROM event_property_values_mv-WHERE project_id = {p1:String} AND name = {p2:String}-GROUP BY property_key, name-ORDER BY property_key ASC, name ASC-LIMIT {p3:UInt64}--- V2 params: {"p1":"pincali-production","p2":"screen_view","p3":500}-```--The no-`eventName` case above is the other half of that branch: `sql.empty`-renders to nothing, and the resulting text is byte-for-byte V1's minus the-`AND name = …` clause.--## `get_event_property_values`--**statement** — IDENTICAL; rows V1/V2 = **2000/2000** (the `LIMIT` window,-full); `meta` V1/V2 = `[{"name":"value","type":"String"}]`; rows_read V1/V2 =-1082520/1081344; wall V1/V2 = 39 ms / 42 ms; clickhouse_settings:-`session_timezone=UTC` (both). First rows on both sides: `EB-RG9481`,-`EB-SS0279`, `EB-WN5258`, `EB-WH9815`, …--```sql--- V1-SELECT property_value as value FROM event_property_values_mv-WHERE project_id = 'pincali-production'- AND name = 'viewed_property'- AND property_key = 'property_id'-ORDER BY created_at DESC-LIMIT 2000--- V2-SELECT property_value as value FROM event_property_values_mv-WHERE project_id = {p1:String}- AND name = {p2:String}- AND property_key = {p3:String}-ORDER BY created_at DESC-LIMIT {p4:UInt64}--- V2 params: {"p1":"pincali-production","p2":"viewed_property","p3":"property_id","p4":2000}-```--**Known instability of this table, not of this conversion.** The-`event_property_values_mv` is an AggregatingMergeTree read without `FINAL` whose-`created_at` is outside the sort key, so the top-2000 window reshuffles when a-background merge lands (`docs/TECH_DEBT.md`, *Golden coverage hole:-`insights-event-property-values`*). Both sides of this case were executed back to-back through the same client against the same parts and returned identical rows;-a re-run days later may return a different — but still identical-between-sides —-2000. V1 runs the same query, so the conversion neither introduces nor fixes it.--## The lazy loaders--V1 opened each handler with-`const [ch, { clix, TABLE_NAMES }] = await Promise.all([loadCompatCh(), loadCompatChHelpers()])`-— two awaited dynamic `import('../../../../v1-compat')` hops per tool call, one-of them only to fetch `clix` and `TABLE_NAMES`. V2 imports `sql`, `chQuery` and-core's own `TABLE_NAMES` statically and takes the ClickHouse scope from-`loadCompatChScope()` (ADR-007: no lazy loaders; MCP handlers have a fixed-`@modelcontextprotocol/sdk` signature with no `Ctx` slot, so the v1-compat seam-stays — it is the *dynamic import* that goes). `tools/shared.ts` lost its-dynamic form too: its surviving `loadCompat*` helpers all read a static import-of `v1-compat` (which that file already value-imported for-`resolveClientProjectId`, so the dynamic form deferred nothing), and-`organization.service.ts` lost the last one in its own module. Consequences visible in the capture: the statement-now carries `deps.logger`, so the `query info` line carries the request's scope,-and `tools/shared.ts` no longer exports `loadCompatChHelpers` (property-values-was its only caller) nor `loadCompatCh` (same) — with them the comment saying-property-values "still builds its query with `clix`" is gone.--**The `await`-dynamic-import gate is 0 across the three module trees' source-files**, which is what the acceptance criterion asks for:--```-$ grep -rn "await imp"'ort' --include='*.ts' --exclude='*.test.ts' \- packages/core/src/modules/mcp packages/core/src/modules/project \- packages/core/src/modules/organization-$ echo $?-1-```--Measured 2026-09-07 on this tree. The `--exclude=*.test.ts` is not a loophole-around this task, it is the ADR: the modules' 10 test files hold 55 awaited-dynamic imports that are the mandated `bun:test` idiom, not lazy loaders.-ADR-010's acceptance note and `packages/core/AGENTS.md` require top-level-`mock.module` followed by an awaited dynamic import of the subject inside-`beforeAll`, and state that "a static `import` of the subject at the top of the-file defeats it". They are unchanged by this task.--| scope | occurrences |-|---|---:|-| `*.ts` source in the three module trees | **0** |-| `*.test.ts` in the three module trees (the ADR-010 idiom) | 55 |-| the three `*.sql.proof.md` files this task adds (deliberately phrased so they add none) | 0 |--## Tests--No test compares this tool's generated SQL text, so none had to be retargeted to-compare statement + params. `src/integration/tools.test.ts` invokes both tools-against the isolated `openpanel_test` databases and asserts on the returned-shape (`res.columns`, `res.properties`, `res.event`, `res.property`,-`res.values`); its assertions are unchanged and the file is untouched.-(`src/tools/analytics/profiles.test.ts` is the module's one statement+params-comparison, and it belongs to the profile service, not to this file.)--## Reproduce--```bash-# get_event_property_values, V1-curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC&default_format=JSONCompact' \- --data-binary "SELECT property_value as value FROM event_property_values_mv WHERE project_id = 'pincali-production' AND name = 'viewed_property' AND property_key = 'property_id' ORDER BY created_at DESC LIMIT 2000"--# get_event_property_values, V2-curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \- --data-urlencode 'default_format=JSONCompact' \- --data-urlencode 'param_p1=pincali-production' \- --data-urlencode 'param_p2=viewed_property' \- --data-urlencode 'param_p3=property_id' \- --data-urlencode 'param_p4=2000' \- --data-urlencode 'query=SELECT property_value as value FROM event_property_values_mv WHERE project_id = {p1:String} AND name = {p2:String} AND property_key = {p3:String} ORDER BY created_at DESC LIMIT {p4:UInt64}'-```--Both return 2,000 rows.diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex d199d87c0..143c9015f 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -1,39 +1,10 @@-// Moved from packages/db/src/services/organization.service.ts +-// packages/db/src/services/delete.service.ts (M6-001, folded together per the-// module map: "delete.service in organization"). The mutation bodies inline-// in packages/trpc/src/routers/organization.ts (update/delete/cancelDeletion/-// inviteUser/revokeInvite/removeMember/updateMemberAccess) moved here too, so-// V1's router and core's own organization.rpc.ts shared one implementation-// (DELEGATE PATTERN) until packages/trpc was retired. packages/db carries no-// re-export shim for this file — its services/ directory holds only-// access.service.ts today. `getSettingsForProject` is instead value-imported-// directly by ten sibling packages/core modules; that's the tree-wide R3-// sibling-access gap the composition-root fix wave tracks, not something-// local to this file. packages/db lost delete.service.ts entirely — nothing-// outside the `delete` cron job (now here) reached it through-// @openpanel/db's barrel.+// Organizations, their projects, the invite/member mutations, and the+// deletion cron that reaps organizations left without an admin.//-// M10-009: every exported function takes `ServiceDeps` and reaches Postgres-// as `deps.db` and ClickHouse as `deps.ch` (through core's own `chQuery`), so-// the requestId minted at the edge reaches the query (ADR-018,-// docs/TECH_DEBT.md §4). The two `cacheable` wrappers are `cacheablePerDeps`-// (M15-004): `cacheable` keys on the call's ARGUMENTS-// (packages/redis/cachable.ts), so the caller's deps travel beside the key-// rather than inside it and the Redis key stays byte-identical.-//-// M12-006 also made `shared/access-lookups.ts` a static import: that file-// value-imports only zod-free leaves (`@openpanel/redis`, a Prisma TYPE) and-// reaches Postgres through `context.ts`'s `unscopedDb()` (its bare signature-// is pinned by a protected wire contract), so it has no static edge back here.-//-// M12-006 converted all five ClickHouse statements here onto the ADR-013 `sql`-// tag: the four billing counters and `deleteFromClickhouse`'s project filter-// bind every value as a `{pN:Type}` param, and the statements are written out-// in full instead of assembled by `createSqlBuilder`'s record-of-strings.-// `sqlstring` and `createSqlBuilder` are both gone from this module. The-// `sql` tag is a value import of `@openpanel/db` and stays one: it is a-// compile-time template tag holding no client (see ch-query.ts). The-// V1-vs-V2 result-set proof is `organization.sql.proof.md` beside this file.+// The two `cacheable` wrappers are `cacheablePerDeps`: `cacheable` keys on the+// call's ARGUMENTS (packages/redis/cachable.ts), so the caller's deps have to+// travel beside the key rather than inside it, or the Redis key would change+// per request.import { sql } from '@openpanel/db/src/clickhouse/sql';import type {diff --git a/packages/core/src/modules/organization/organization.sql.proof.md b/packages/core/src/modules/organization/organization.sql.proof.mddeleted file mode 100644index 094d4f0e3..000000000--- a/packages/core/src/modules/organization/organization.sql.proof.md+++ /dev/null@@ -1,238 +0,0 @@-# organization.service.ts — V1 → V2 result-set proof (M12-006)--Every ClickHouse statement `packages/core/src/modules/organization/organization.service.ts`-runs, executed V1 against V2. V1 is the file at commit `78098bdc`-(`git show HEAD:packages/core/src/modules/organization/organization.service.ts`),-which builds four counters with `createSqlBuilder` + `sqlstring.escape` and-`deleteFromClickhouse`'s filter with `sqlstring.escape`; V2 is the converted-file, every value bound as a `{pN:Type}` param. **Both files were imported into-one Bun process and called with the same inputs** — the SQL below was produced-by calling the real exported functions with a `deps.ch.query` / `deps.ch.command`-stub that captures `{query, query_params, clickhouse_settings}`, never by-retyping V1 by hand. Each captured statement was then executed through the local-HTTP interface at `format: 'JSON'` with the settings its own side asked for; V1-went as `query`, V2 as `query` + `param_pN`. `data` was compared row-for-row and-`meta` column-for-column.--No case needed set comparison: the four counters return one row or a fully-ordered `WITH FILL` series.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,850,903 events. Organization- fixture: two projects, `verdict` (real: 41,921,451 non-session events) and- `o'brien-prod` (**does not exist** — it is the quote-carrying value, present- so the escaping case is covered; its contribution to every count is 0 on both- sides). Billing window `2026-08-01 00:00:00` … `2026-08-20 00:00:00`, inside- the copy's `2026-07-01` … `2026-08-25` range. Every SELECT case below returns- a non-zero count.-- **Deletes run elsewhere, deliberately.** `deleteFromClickhouse` issues 14- `DELETE` / `ALTER TABLE … DELETE` statements. Running those against the- prod-copy would mutate the golden harness's data, so both sides were executed- against a scratch database `m12_006_proof` holding 14 tables that carry only- the column the statements filter on, seeded identically per side and dropped- at the end of the run. §*deleteFromClickhouse* records the row counts.-- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either- direction.** `grep -c GLOBAL` is `0` on the V1 file and `0` on the V2 file.- Every `IN` operand on both sides is a literal value list (V1 an inline tuple,- V2 an `Array(String)` param) — there is no `IN (subquery)` anywhere in this- module, so the distributed-`IN` trap does not arise.-- **Verdict**: **32 statement pairs, all IDENTICAL** — 18 IDENTICAL (4 counters- + 14 scratch-database deletes) and 14 IDENTICAL ERROR (the clustered- rendering, which cannot run on a single node; §*deleteFromClickhouse,- clustered rendering*).--## `session_timezone`--None of the five statements came off `clix`, so none of them ever sent a-`session_timezone`. V1 sent no `clickhouse_settings` on the four counters and-`{lightweight_deletes_sync: '0'}` on the deletes; V2 sends exactly the same,-captured and compared per statement.--## `getOrganizationBillingEventsCount`--**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **15080373/15080373**;-`meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 =-16008988/16008988; wall V1/V2 = 232 ms / 204 ms; clickhouse_settings: *(none)*-on both.--```sql--- V1-SELECT COUNT(*) AS count FROM events e-WHERE project_id IN ('verdict','o\'brien-prod')- AND created_at BETWEEN '2026-08-01 00:00:00' AND '2026-08-20 00:00:00'- AND name NOT IN ('session_start', 'session_end')--- V2-SELECT COUNT(*) AS count FROM events e-WHERE project_id IN {p1:Array(String)}- AND created_at BETWEEN {p2:String} AND {p3:String}- AND name NOT IN {p4:Array(String)}--- V2 params: {"p1":["verdict","o'brien-prod"],"p2":"2026-08-01 00:00:00","p3":"2026-08-20 00:00:00","p4":["session_start","session_end"]}-```--## `getOrganizationEventsCount`--**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **41921451/41921451**;-`meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 =-44371055/44371055; wall V1/V2 = 358 ms / 340 ms; clickhouse_settings: *(none)*-on both.--```sql--- V1-SELECT COUNT(*) AS count FROM events e-WHERE project_id IN ('verdict','o\'brien-prod')- AND name NOT IN ('session_start', 'session_end')--- V2-SELECT COUNT(*) AS count FROM events e-WHERE project_id IN {p1:Array(String)}- AND name NOT IN {p2:Array(String)}--- V2 params: {"p1":["verdict","o'brien-prod"],"p2":["session_start","session_end"]}-```--## `getOrganizationEventsCountSince`--**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **18487546/18487546**;-`meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 =-19697131/19697131; wall V1/V2 = 248 ms / 259 ms; clickhouse_settings: *(none)*-on both.--`since = 2026-08-01T00:00:00Z`, and `formatClickhouseDate(since, true)` narrows-it to the calendar day `'2026-08-01'` on both sides — kept as a bound `String`-compared against a `DateTime64`, exactly the comparison V1 wrote, not promoted-to `sql.date`.--```sql--- V1-SELECT COUNT(*) AS count FROM events e-WHERE project_id IN ('verdict','o\'brien-prod')- AND name NOT IN ('session_start', 'session_end')- AND created_at >= '2026-08-01'--- V2-SELECT COUNT(*) AS count FROM events e-WHERE project_id IN {p1:Array(String)}- AND name NOT IN {p2:Array(String)}- AND created_at >= {p3:String}--- V2 params: {"p1":["verdict","o'brien-prod"],"p2":["session_start","session_end"],"p3":"2026-08-01"}-```--## `getOrganizationBillingEventsCountSerie`--**statement** — IDENTICAL; rows V1/V2 = **20/20**; `data` byte-identical-row-for-row (`2026-08-01` → 2852707, `2026-08-02` → 456447, `2026-08-03` → 360613,-`2026-08-04` → 298741, … through `2026-08-20`);-`meta` V1/V2 = `[{"name":"count","type":"UInt64"},{"name":"day","type":"Date"}]`;-rows_read V1/V2 = 16352596/16352596; wall V1/V2 = 269 ms / 455 ms;-clickhouse_settings: *(none)* on both.--This is the case that proves `WITH FILL FROM toDate({pN:String})` is accepted:-`WITH FILL` needs a constant bound, parameters are substituted at parse time, and-the filled series comes back with the same 20 days on both sides.--```sql--- V1-SELECT COUNT(*) AS count, toDate(toStartOfDay(created_at)) AS day-FROM events e-WHERE project_id IN ('verdict','o\'brien-prod')- AND day BETWEEN '2026-08-01' AND '2026-08-20'- AND name NOT IN ('session_start', 'session_end')-GROUP BY day-ORDER BY day WITH FILL FROM toDate('2026-08-01') TO toDate('2026-08-20') STEP INTERVAL 1 DAY--- V2-SELECT COUNT(*) AS count, toDate(toStartOfDay(created_at)) AS day-FROM events e-WHERE project_id IN {p1:Array(String)}- AND day BETWEEN {p2:String} AND {p3:String}- AND name NOT IN {p4:Array(String)}-GROUP BY day-ORDER BY day WITH FILL FROM toDate({p5:String}) TO toDate({p6:String}) STEP INTERVAL 1 DAY--- V2 params: {"p1":["verdict","o'brien-prod"],"p2":"2026-08-01","p3":"2026-08-20","p4":["session_start","session_end"],"p5":"2026-08-01","p6":"2026-08-20"}-```--V1's `const interval = 'day'` was never anything but `'day'`; V2 writes the-bucket, the alias, the GROUP BY and the `STEP INTERVAL 1 DAY` out instead of-deriving four spellings of it. The emitted text is identical apart from the-bindings, as the two blocks above show.--## `deleteFromClickhouse`, non-clustered rendering (executed)--14 statements per side — 6 `DELETE FROM <t>` and 8 `ALTER TABLE <t> DELETE`,-in `TABLE_NAMES` order — each ending `WHERE project_id IN …;` and each sent with-`clickhouse_settings: {lightweight_deletes_sync: '0'}` on **both** sides.--Executed against scratch database `m12_006_proof`: 14 tables-`(project_id String, n UInt32) ENGINE = MergeTree ORDER BY project_id`, each-seeded with 5 rows — `('verdict',1), ('verdict',2), ('o''brien-prod',3),-('keepme',4), ('keepme',5)`. Each side got a freshly dropped + recreated +-reseeded database; after issuing all 14 statements the run waited for-`system.mutations` to drain and read every table back-`ORDER BY project_id, n`. The scratch database is dropped at the end-(`SELECT count() FROM system.databases WHERE name='m12_006_proof'` → 0).--**statement set** — IDENTICAL; rows before = **70/70**; rows deleted V1/V2 =-**42/42**; rows remaining V1/V2 = **28/28**; the post-delete contents of all 14-tables are byte-identical between the two sides (`[["keepme",4],["keepme",5]]`-in every table). The `o'brien-prod` row is deleted by both sides, which is the-quote-escaping case reaching a row rather than a count.--```sql--- V1 (first and fifth of the fourteen)-DELETE FROM events WHERE project_id IN ('verdict','o\'brien-prod');-ALTER TABLE cohort_events_mv DELETE WHERE project_id IN ('verdict','o\'brien-prod');--- V2-DELETE FROM events WHERE project_id IN {p1:Array(String)};-ALTER TABLE cohort_events_mv DELETE WHERE project_id IN {p1:Array(String)};--- V2 params (every one of the 14): {"p1":["verdict","o'brien-prod"]}-```--## `deleteFromClickhouse`, clustered rendering (IDENTICAL ERROR)--`isClickhouseClustered()` is true unless `SELF_HOSTED` is set, and-`getReplicatedTableName` then appends `ON CLUSTER '{cluster}'` — a clause, not-an identifier, which is why V2 renders it as `sql.id(`${table}_replicated`)`-followed by literal template text rather than through a single identifier.--Both sides' 14 clustered statements were executed as rendered against-`openpanel`. This box has no `*_replicated` table-(`SELECT name FROM system.tables WHERE database='openpanel' AND name LIKE-'%_replicated'` → 0 rows) and no cluster, so all 28 fail — **and they fail-identically, statement for statement**:--| rendering | V1 error | V2 error |-|---|---|---|-| `DELETE FROM <t>_replicated ON CLUSTER '{cluster}' …` (6) | `Code: 60 … UNKNOWN_TABLE` | same |-| `ALTER TABLE <t>_replicated ON CLUSTER '{cluster}' DELETE …` (8) | `Code: 701 … Requested cluster 'openpanel_cluster' not found. (CLUSTER_DOESNT_EXIST)` | same |--The `CLUSTER_DOESNT_EXIST` rows are the load-bearing evidence: the `{cluster}`-macro expanded to `openpanel_cluster` on the V2 side **with `param_p1` supplied**,-so ClickHouse's `{name:Type}` substitution does not disturb the `ON CLUSTER-'{cluster}'` macro. 14 pairs, all IDENTICAL ERROR — V1 defects (well, V1-*environment* limits) reproduced byte-for-byte, not fixed here.--## Tests--No test in this module compares generated SQL text, so none had to be retargeted-to compare statement + params. `organization.service.test.ts` stubs-`deps.ch.command` and asserts only that it was called-(`expect(chCommand).toHaveBeenCalled()`); its assertions are unchanged. The one-edit to that file is its header comment, which described the per-function lazy-dynamic imports this task removed.--## Reproduce--```bash-# getOrganizationBillingEventsCount, V1-curl -s 'http://127.0.0.1:8123/?database=openpanel&default_format=JSONCompact' \- --data-binary "SELECT COUNT(*) AS count FROM events e WHERE project_id IN ('verdict','o\\'brien-prod') AND created_at BETWEEN '2026-08-01 00:00:00' AND '2026-08-20 00:00:00' AND name NOT IN ('session_start', 'session_end')"--# getOrganizationBillingEventsCount, V2-curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'default_format=JSONCompact' \- --data-urlencode "param_p1=['verdict','o\\'brien-prod']" \- --data-urlencode 'param_p2=2026-08-01 00:00:00' \- --data-urlencode 'param_p3=2026-08-20 00:00:00' \- --data-urlencode "param_p4=['session_start','session_end']" \- --data-urlencode 'query=SELECT COUNT(*) AS count FROM events e WHERE project_id IN {p1:Array(String)} AND created_at BETWEEN {p2:String} AND {p3:String} AND name NOT IN {p4:Array(String)}'-```--Both return `[[15080373]]`.diff --git a/packages/core/src/modules/overview/src/overview.sql.proof.md b/packages/core/src/modules/overview/src/overview.sql.proof.mddeleted file mode 100644index 55704e3c1..000000000--- a/packages/core/src/modules/overview/src/overview.sql.proof.md+++ /dev/null@@ -1,312 +0,0 @@-# overview.sql.ts — V1 -> V2 result-set proof (M7-005)--**Methodology.** Two levels of evidence, per decision 21:--1. **Whole-method comparison.** `OverviewService`'s public methods were called twice with- identical input against the same local ClickHouse — once through V1's unmodified- `clix`-built queries (`git show HEAD:packages/db/src/services/overview.service.ts`, the- state before this task) and once through this module's `sql`-fragment builders — and the- JSON results diffed byte-for-byte. This exercises every query plus all of V1's JS-side- post-processing (revenue merge, fill defaults, the user-journey graph builder) in one pass,- which a query-by-query SQL diff alone would not catch.-2. **Per-query SQL + execution proof.** Every builder in this file was rendered via- `toStatement()` and executed against the same data with `EXPLAIN`-equivalent real- execution (no query is committed unexecuted). Row counts and timings below are from that- run.--- **Amended by M27-001 (2026-09-15): the user-journey dedup expression is no longer V1's.** V1's- `arrayFilter((x, i) -> i = 1 OR x != paths_raw[i - 1], groupArray(path) as paths_raw, arrayEnumerate(paths_raw))`- is Theta(n^2) in the longest single session's pageview count, so `overview.userJourney` — which the- dashboard calls on every load — could not answer at all for a tenant with one very long session- (`docs/ANALYTICS_PERFORMANCE.md` section 6.1). It now reads `arrayCompact(groupArray(path))`, which is the- ClickHouse built-in for the same operation and is linear. The render below is the amended text.- Re-proved against the local prod copy on **2026-09-15**, `use_query_condition_cache=0`,- `max_memory_usage=6 GiB`, `memory_usage` and `elapsed_ns` read off `X-ClickHouse-Summary`:- - **Result sets:** `cityHash64(arraySort(groupArray(tuple(*))))` old vs new on every (project, window)- pair where the old spelling survives — `verdict`/`bayse`/`earlysalary-production`/`chatpaper` at 30 d- and `bayse` at 7 d, both statements: **identical, 10/10**.- - **Cost, both statements, 5 steps, 30-day window:** `verdict` 100 ms -> 71 ms · `bayse` 1,583 ms ->- 980 ms / 182 MiB · `earlysalary-production` 1,341 ms -> 1,283 ms · `website-8103` FAIL- (`would use 917.36 TiB`) -> 2,304 ms / 909 MiB · `chatpaper` 7,125 ms -> 6,434 ms / 1,392 MiB.- `website-8103` at 1 day: FAIL (`852.36 GiB`) -> 119 ms / 27 MiB.- - **Row order is not part of the contract for `transitionsQuery`**, exactly as `sankey.sql.proof.md`- already records: it ends `ORDER BY step ASC, value DESC` and most rows share a `(step, value)` pair,- so ClickHouse returns them in whatever order the parallel merge produced. Measured 2026-09-15 on- `bayse` 30 d: 5,192 of 5,301 result rows sit in a tied group, and **the unchanged shipped statement,- run 10 times, returned 10 different row orders and 1 identical row set**. Set-level hashes are the- comparison above for that reason.--- **Amended by M28-001 (2026-09-15): `metricsWithPageFilterQuery` reads each source table once.**- The shipped shape referenced `overall_unique_visitors` twice and `session_agg` twice, and- **a ClickHouse CTE is re-executed once per reference** — so the statement performed **four- `events` scans and two `sessions FINAL` scans**, not the three `docs/ANALYTICS_PERFORMANCE.md`- section 6.10 counted. Measured on the local prod copy, `chatpaper` 30 d filtered on its busiest- path: the whole statement read **60,569,110 rows = 4 x 13,393,722 + 2 x 3,497,111**, and removing- each scalar reference in turn dropped exactly one scan's worth (47,175,388 -> 33,781,666 ->- 30,284,555). Section 6.10's *"ClickHouse may already share those scans"* is therefore **measured- false**, and its 1,453 ms / 30,350,044-row baseline is the cost of the statement with those two- extra references removed, i.e. roughly half the real one.- The query now reads `events` once into `filtered_screen_views`, aggregates it once with- `GROUP BY date WITH ROLLUP`, and broadcasts the window-wide totals off that rollup row with- `max(if(date = <rollup>, x, NULL)) OVER ()` instead of re-scanning. Same for `sessions`. Both- aggregates keep their rollup row through the `LEFT JOIN` so the two totals rows pair up — that is- what carries `overall_bounce_rate` onto days the sessions aggregate has no row for — and the- rollup row is dropped afterwards. `src/metrics-page-filter.test.ts` pins both that case and the- NULL-when-nothing-matches nullability the old scalar subqueries had.- Re-proved against the local prod copy on **2026-09-15**, `use_query_condition_cache=0`,- `max_memory_usage=6 GiB`, `elapsed_ns`/`read_rows`/`memory_usage` read off `X-ClickHouse-Summary`:- - **Result sets: `FORMAT JSONCompact` `meta` + `data`, compared byte-for-byte, old vs new —- identical on 38 of 38 cases.** All five anchors; windows 1 d / 7 d / 30 d / 56 d; intervals- minute / hour / day / week / month; and the edge cases that decide the rewrite: a page filter- matching nothing (all five projects), `verdict` — which has no `screen_view` events at all — a- path that is never any session's `entry_path`, and a `bayse` path whose event days and session- days **do not overlap at all**, which is the case the naive fold gets wrong.- - **Cost, 30-day window, busiest path, median of 3:**--| project | old ms | old rows_read | new ms | new rows_read |-|---|---:|---:|---:|---:|-| `bayse` | 1,554 | 68,873,974 | **495** | **17,496,956** |-| `earlysalary-production` | 1,863 | 62,275,058 | **706** | **15,875,922** |-| `website-8103` | 1,551 | 49,471,404 | **520** | **12,384,061** |-| `chatpaper` | 2,901 | 60,569,110 | **1,118** | **16,890,833** |-| `verdict` (no `screen_view` at all) | 182 | 1,673,650 | **66** | **828,633** |-- Peak memory is slightly higher (`chatpaper` 98 MiB -> 186 MiB), because one pass now holds the- per-row `lead()` window and the daily aggregate together instead of building them in separate- scans. At 56 days on `bayse` the statement goes 3,317 ms / 154,168,912 rows -> 1,031 ms /- 38,968,107 rows.- - **The M7-005 render case below** (`skills-directory`, `2026-08-01`..`2026-08-08`, no filter)- re-run on 2026-09-15: same 7 rows, byte-identical, **65 ms / 475,054 rows -> 30 ms /- 131,039 rows**. Its row in the per-query table further down is M7-005's original measurement- and is left as the historical record.--- **Amended by M39-002 (2026-09-16): `FINAL` dropped from the sign-weighted `sessions` aggregates**- `topEntryExitQuery`, `topGenericQuery` and `topGenericSeriesTimeSeriesQuery` (plus the three- `insight/src/referrer-spikes.ts` statements). Every output column is a grouping key or a sum that is- linear in `sign`. A collapsible pair is `(+1, V)` and `(-1, V)` with identical columns- (`session-buffer.ts` builds the `-1` as `{ ...existing, sign: -1 }`), so it sums to 0 in the same- group, under the same filter, and `HAVING sum(sign) > 0` sees the same sums. **`bounceRate`- (`countIf(sign = 1)`) and `pages.sql.ts` are not linear and keep `FINAL`.**- Proof, run 2026-09-16 21:48–21:52 UTC on the local prod copy, read-only, `wait_end_of_query=1`,- `use_query_cache=0`, `use_query_condition_cache=0`. Statements were rendered by the real builders- (the referrer-spike ones were captured from `getReferrerSpikes` through a recording `deps.ch`), and- the old form is the same text with ` FINAL` put back. Result-set hash `count(), sum(sipHash64(formatRow('TSV', *)))`:- **312 of 312 statements identical.** The anchors were `chatpaper`, `verdict`, `bayse`,- `earlysalary-production` and `website-8103` over 2026-08-01..08-30, plus `e2e-sessions` over- 2026-09-01..09-15, which holds the box's 21 unmerged `-1` rows. The cases covered entry/exit,- six `topGeneric` columns (with and without a prefix), four series intervals, no filter, a- `country` filter and a page filter (the `distinct_sessions` CTE), and spikes at- hour/day/week, UTC and `Europe/Stockholm`. The spike cases include a forced step 1, because every- `e2e-sessions` referrer is `''`. A non-linear control (`count()` without `FINAL`) **did** differ on- `e2e-sessions`, which shows the probe can detect the unmerged rows. Row *order* differs only- within ties: the sort-key column sequence (`sessions` / `date` / `total`) was identical in every- ordered case.- Cost, warm, 3 runs, shipped → no `FINAL`: `chatpaper` `topGenericQuery` 169–182 → 53–57 ms,- `topEntryExitQuery` 610–635 → 376–381 ms, series (day) 191–195 → 76–80 ms, spikes steps 1/2/3- 139–141 / 139–140 / 128–136 → 41–43 / 43–45 / 41–43 ms (3,571,254 → 3,448,379 rows read);- `verdict` `topGenericQuery` 47–51 → 18 ms, `topEntryExitQuery` 61–86 → 26–30 ms, series- 52–56 → 24 ms.--- **Amended by M39-003 (2026-09-16): the `metricsWithPageFilterQuery` bounce rate drops `FINAL` and- is now sign-weighted.** `countIf(is_bounce = 1 AND sign = 1) * 100. / countIf(sign = 1) FROM sessions- FINAL WHERE sign = 1` became `sumIf(sign, is_bounce = 1) * 100. / sum(sign) FROM sessions` with no- `sign` filter, plus `HAVING sum(sign) > 0` after `WITH ROLLUP`. The old form is not linear in- `sign`, so dropping `FINAL` alone counts the stale `+1` of every uncollapsed pair. That is the- "naive drop" control below.- **The two checks M38-002 left open.** Both were run on a scratch `openpanel_m39003` database- (`sessions`/`events` created `AS openpanel.*`, merges stopped, seeded in separate parts), with a- bucket and a whole window whose sessions all cancel:- 1. *Division by zero.* A bucket with `sum(sign) = 0` evaluates to `0 * 100. / 0` = **`nan`**, not an- error. Without `HAVING`, a net-zero day came out as a `bounce_rate = nan` row. A net-zero window- came out as `overall_bounce_rate = nan` on every row, and `getMetricsWithPageFilter`'s- `?? 0` would have passed that `nan` through. `FINAL` had produced no such rows.- 2. *`WITH ROLLUP` on net zero.* ClickHouse emits no rollup row for an empty input, but it does- emit one (`nan`) for rows that sum to zero. `HAVING sum(sign) > 0` is applied to the rollup row- as well (verified), so both cases return to `FINAL`'s shape: the bucket is absent, and with no- rollup row `overall_bounce_rate` is `NULL`, which is the "no data" signal- `metrics-page-filter.test.ts` pins. `sum(sign)` equals `FINAL`'s surviving `+1` count whenever- every `-1` has its `+1`, which is the `session-buffer.ts` invariant.- **Proof**, run 2026-09-16 21:57–22:05 UTC, read-only on `openpanel`, `wait_end_of_query=1`,- `use_query_cache=0`, `use_query_condition_cache=0`, `session_timezone=UTC`. The statements were- rendered by the real builder, and the old form is the same text with the previous `sessionAgg`- put back. `count(), sum(sipHash64(formatRow('TSV', *)))` was compared for the whole statement- **and** for `session_stats` alone (the join hides session-only buckets): **158 of 158 hashes- identical over 79 cases.** Cases: `chatpaper`, `verdict`, `bayse`, `earlysalary-production` and- `website-8103`, each at 30 d/day, with no filter and with `path=/`; 7 d/hour; 8 w/week with- `country=US`; 2 mo/month; 1 d/minute. `e2e-sessions` (the box's 21 unmerged `-1` rows) at- day/week/hour, a 1 h minute window, the 1 s window holding the `-1` rows, and `country=SE`. The- scratch net-zero-day project (pending pairs, a pair whose replacement moved day and path, a- cancelled-only day) and net-zero-window project, at day/hour/week/month × no filter /- matching / non-matching / other path, plus minute and single-day windows.- **Control:** the naive drop (`FINAL` removed, `countIf`/`WHERE sign = 1` kept) **differed** on 5 of- 6 unmerged cases (e2e-sessions day and both minute windows; the scratch project day, with 3 → 4- rows, and minute, with 5 → 7 rows). The probe therefore does detect the wrong answer.- **Cost**, warm, 3 runs each, 2026-09-16 22:05–22:06 UTC, load 1.4–2.4, 30 d/day, shipped → new.- `session_agg` alone: `chatpaper` 139–159 → 45–49 ms (3,571,254 → 3,448,379 rows, 103 → 73 MiB);- `chatpaper` with `path=/` 203–228 → 87–89 ms; `verdict` 40–44 → 14–19; `bayse` 28–33 → 11–12;- `earlysalary-production` 33–34 → 14–15. Whole statement: `chatpaper` 2,737–2,829 → 2,616–2,623 ms,- `path=/` 734–741 → 611–623; `verdict` 63–66 → 40–43; `bayse` 416–421 → 397–404;- `earlysalary-production` 507–513 → 493–509. The `events` side dominates the whole statement.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static).- Project: `skills-directory` (293,597 events, 75,727 sessions, 2026-07-01..2026-08-25).- Window used throughout: `2026-08-01 00:00:00`..`2026-08-08 00:00:00`, UTC.-- **Machine**: single-node ClickHouse — self-host topology (`docs/ENVIRONMENT.md`). No- statement here touches a `Distributed` table or a cross-shard `IN`; `events`/`sessions` are- local tables both locally and on Cloud, so no `GLOBAL IN` question arises for this module.--## Whole-method comparison — verdict--13 of 15 cases came back **byte-identical**; the 2 that didn't are `pages.getTopPages`'s-`title` column, explained below (a V1 characteristic, not a V2 regression).--| Case | Verdict | Rows |-|---|---|---|-| `getMetrics` (no filter) | IDENTICAL | 7 series + summary |-| `getMetrics` (page filter) | IDENTICAL | 7 series + summary |-| `getTopPages` | IDENTICAL | 20 |-| `getTopEntryExit` (entry) | IDENTICAL | 20 |-| `getTopEntryExit` (exit, page filter) | IDENTICAL | 20 |-| `getTopGeneric` (country) | IDENTICAL | 143 |-| `getTopGenericSeries` (referrer, day) | IDENTICAL | 1 item + series |-| `getUserJourney` (4 steps) | IDENTICAL | nodes + links |-| `getTopEvents` | IDENTICAL | 12 |-| `getTopLinkOut` | IDENTICAL | 78 |-| `getMapData` | IDENTICAL | 1000 |-| `pages.getTopPages` | see below | 20 |-| `pages.getTopPages` (search) | see below | 20 |-| `pages.getPageTimeseries` | IDENTICAL | 3103 |-| `getPageConversionsCore` | IDENTICAL | 20 |--### The one V1 characteristic that survives unchanged: `anyLast(properties['__title'])`--`pages.getTopPages`'s title lookup (`page_titles` CTE) uses `anyLast()` with no explicit-ordering. ClickHouse does not guarantee a deterministic pick for `any`/`anyLast` across-repeated executions of the *same* query when the underlying merge is order-sensitive at the-row level. Proven independently of this task's code: running V1's own reconstructed SQL text-(byte-identical, params inlined as V1's clix would) directly via `curl` five times in a row-against the unchanged data flips the same page's title between `''` and its real value:--```-curl ... "WITH page_titles AS (... anyLast(properties['__title']) ...) SELECT ... WHERE e.path = '/skills/jezweb-fastapi' ..."-run 1: title = ''-run 2: title = 'Fastapi (Grade A) - Claude Skill | Skills Directory'-run 3: title = 'Fastapi (Grade A) - Claude Skill | Skills Directory'-run 4: title = ''-run 5: title = 'Fastapi (Grade A) - Claude Skill | Skills Directory'-```--This is V1's behaviour, ported verbatim (same `anyLast`, same lack of an explicit tiebreak) —-fixing it (e.g. `argMax` with a deterministic key) is a behaviour change outside this task's-scope. Every other column in both `pages.getTopPages` cases — `sessions`, `pageviews`,-`avg_duration`, `bounce_rate`, and (for the search case) the row set once title-dependent-matches are excluded — is identical between V1 and V2.--## Two real bugs found during conversion (not V1 bugs — introduced and fixed in this task)--1. **`GROUP BY ... WITH ROLLUP ... HAVING`, not `HAVING ... WITH ROLLUP`.** `sessionMetricsQuery`- initially emitted `GROUP BY date HAVING sum(sign) > 0 WITH ROLLUP`, which ClickHouse- rejects (`Syntax error ... Expected ... end of query`, right after `ORDER BY date ASC`).- Fixed by reordering to `GROUP BY date WITH ROLLUP HAVING sum(sign) > 0`, ClickHouse's- required clause order. Caught by `bun test` (`get_analytics_overview` mcp tool test),- confirmed by re-running the corrected query and diffing against V1.-2. **`WITH FILL FROM/TO` needs the exact column type, not a `String`.** The first cut bound- the fill boundary as `sql.string(...)` (or, once fixed once, `sql.dateTime64(...)`).- ClickHouse's `WITH FILL` requires the boundary's type to match the sorted column's type- exactly: `toStartOfDay(created_at)` is `DateTime`, and a `String` or `DateTime64` boundary- is rejected (`Sort FILL FROM expression must be constant with numeric type` / `Incompatible- types of WITH FILL expression values with column type DateTime`). Fixed by wrapping the- boundary in `toStartOfX(...)` exactly as V1's `clix.toStartOf`/`clix.datetime` expression- text did (never a bare literal) and typing the raw param `DateTime` (day/hour/minute- buckets) or `Date` (week/month buckets, matching V1's `toDate` wrapper).--## Per-query render + execution proof--Every builder below was rendered via `toStatement()` and executed once against-`skills-directory`, `2026-08-01`..`2026-08-08` UTC (`transitionsQuery` used placeholder entry-pages that don't exist in the data, to prove the array-function shape parses and runs; 0 rows-is expected and correct for that input). All 22 statements below executed with no error.--| Query | Rows | Rows read | Wall |-|---|---|---|---|-| `revenueQuery` | 0 (no revenue events for this project) | 0 | 29 ms |-| `sessionMetricsQuery` | 8 (7 days + rollup total) | 16,369 | 23 ms |-| `metricsWithPageFilterQuery` | 7 | 73,678 | 76 ms |-| `topPagesQuery` (overview) | 20 | 49,152 | 23 ms |-| `topEntryExitQuery` (no page filter) | 20 | 24,551 | 12 ms |-| `distinctSessionsQuery` | 6,981 | 65,536 | 14 ms |-| `topGenericQuery` (no prefix, country) | 143 | 24,551 | 14 ms |-| `topGenericQuery` (with prefix, region) | 725 | 24,551 | 13 ms |-| `topGenericSeriesTimeSeriesQuery` | 219 | 24,551 | 8 ms |-| `topEntriesQuery` | 3 | 49,152 | 55 ms |-| `transitionsQuery` (placeholder entries) | 0 | 49,152 | 54 ms |-| `topEventsQuery` | 12 | 65,536 | 14 ms |-| `topLinkOutQuery` | 78 | 49,152 | 18 ms |-| `mapDataQuery` | 1000 | 49,152 | 24 ms |-| `liveTotalSessionsQuery` | 1 | 0 (empty 30-min window) | 8 ms |-| `liveMinuteCountsQuery` | 30 | 0 | 6 ms |-| `liveMinuteReferrersQuery` | 0 | 0 | 9 ms |-| `liveReferrersQuery` | 0 | 0 | 10 ms |--`liveTotalSessionsQuery`/`liveMinuteCountsQuery`/`liveMinuteReferrersQuery`/`liveReferrersQuery`-read 0 rows against local prod-copy data because their `now() - INTERVAL 30 MINUTE` window-never overlaps the fixture's frozen historical range; `liveMinuteCountsQuery`'s 30 rows are-the `WITH FILL`-materialized empty minute buckets, proving the fill clause itself (`FROM-toStartOfMinute(now() - INTERVAL 30 MINUTE) TO toStartOfMinute(now()) STEP INTERVAL 1-MINUTE`) parses and runs. These four were moved here from packages/trpc's inline-`overview.liveData` procedure (M7-005) and had no prior SQL-discipline proof; this is their-first execution against real ClickHouse.--### Representative statements (rendered, params bound)--```sql--- sessionMetricsQuery-SELECT- toStartOfDay(created_at) AS date,- round(sum(sign * is_bounce) * 100.0 / sum(sign), 2) as bounce_rate,- uniqIf(profile_id, sign > 0) AS unique_visitors,- sum(sign) AS total_sessions,- round(avgIf(duration, duration > 0 AND sign > 0), 2) / 1000 AS _avg_session_duration,- if(isNaN(_avg_session_duration), 0, _avg_session_duration) AS avg_session_duration,- sum(sign * screen_view_count) AS total_screen_views,- round(sum(sign * screen_view_count) * 1.0 / sum(sign), 2) AS views_per_session-FROM sessions-WHERE created_at BETWEEN toDateTime({p1:String}) AND toDateTime({p2:String})- AND project_id = {p3:String}-GROUP BY date-WITH ROLLUP-HAVING sum(sign) > 0-ORDER BY date ASC-WITH FILL FROM toStartOfDay({p4:DateTime}) TO {p5:DateTime} STEP toIntervalDay(1)--- params: {"p1":"2026-08-01 00:00:00","p2":"2026-08-08 00:00:00","p3":"skills-directory","p4":"2026-08-01 00:00:00","p5":"2026-08-08 00:00:00"}-```--```sql--- topEntriesQuery (user-journey step 1) — same array-function shape sankey.sql.ts established (M7-004),--- with M27-001's arrayCompact amendment (see the note above the render)-WITH session_paths AS (- WITH paths_deduped_cte AS (- WITH ordered_events AS (- SELECT session_id, concat(origin, path) as path, created_at- FROM events- WHERE project_id = {p1:String} AND name = 'screen_view' AND path != '' AND path IS NOT NULL- AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String})- ORDER BY session_id ASC, created_at ASC- )- SELECT session_id,- arraySlice(arrayCompact(groupArray(path)), 1, {p4:UInt64}) as paths_deduped- FROM ordered_events GROUP BY session_id- )- SELECT session_id,- if(arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) = 0, paths_deduped,- arraySlice(paths_deduped, 1, arrayFirstIndex(x -> x > 1, arrayEnumerateUniq(paths_deduped)) - 1)) as paths,- paths[1] as entry_page- FROM paths_deduped_cte HAVING length(paths) >= 2-)-SELECT entry_page, count() as count FROM session_paths GROUP BY entry_page ORDER BY count DESC LIMIT {p5:UInt64}--- params: {"p1":"skills-directory","p2":"2026-08-01 00:00:00","p3":"2026-08-08 00:00:00","p4":4,"p5":3}-```--Full renders for all 18 `overview.sql.ts` builders (including the CTE-heavy-`metricsWithPageFilterQuery` and `transitionsQuery`) are exercised by-`overview.sql.test.ts`'s `EXPLAIN`-based parse gate, which runs on every `bun test`.diff --git a/packages/core/src/modules/overview/src/overview.sql.test.ts b/packages/core/src/modules/overview/src/overview.sql.test.tsindex d9835d8e7..c4a8e6cb1 100644--- a/packages/core/src/modules/overview/src/overview.sql.test.ts+++ b/packages/core/src/modules/overview/src/overview.sql.test.ts@@ -1,11 +1,10 @@/*** SQL-shape tests for every `overview.sql.ts` builder. Same strategy as- * chart/funnel/retention/sankey's own `*.sql.test.ts` (M7-003/004): render- * the statement, then run `EXPLAIN <sql>` with its bound params against the- * isolated `openpanel_test` ClickHouse (pinned by test/preload.ts). EXPLAIN- * parses and resolves columns without executing, catching the two bugs this- * module actually shipped during conversion — see overview.sql.proof.md —- * without needing seeded rows.+ * chart/funnel/retention/sankey's own `*.sql.test.ts`: render the statement,+ * then run `EXPLAIN <sql>` with its bound params against the isolated+ * `openpanel_test` ClickHouse (pinned by test/preload.ts). EXPLAIN parses and+ * resolves columns without executing, so a column typo is caught with no+ * seeded rows.*/import { beforeAll, describe, expect, it } from 'bun:test';diff --git a/packages/core/src/modules/overview/src/overview.sql.ts b/packages/core/src/modules/overview/src/overview.sql.tsindex 199e07de9..ac1eadcc3 100644--- a/packages/core/src/modules/overview/src/overview.sql.ts+++ b/packages/core/src/modules/overview/src/overview.sql.ts@@ -1,13 +1,8 @@// Every ClickHouse query OverviewService runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/overview.service.ts-// (clix): the SQL text is V1's, with every value — project id, dates,-// timezone, event/column names, limits — bound as a `{pN:Type}` parameter-// instead of an escaped literal or clix's inline string interpolation. Each-// builder's result set was diffed against V1's on the local prod-copy; the-// statements, params, row counts and timings are in overview.sql.proof.md.+// (ADR-013).//-// Both filter compilers and the field resolver return fragments now (M12-002,-// M12-003) and are interpolated directly. `compiledText` is left with one job+// Both filter compilers and the field resolver return fragments and are+// interpolated directly. `compiledText` is left with one job// here: the `INTERVAL <n> <unit>` step keyword in a WITH FILL clause, which is// SQL syntax, not a value.//diff --git a/packages/core/src/modules/overview/src/pages.sql.proof.md b/packages/core/src/modules/overview/src/pages.sql.proof.mddeleted file mode 100644index 790fc997b..000000000--- a/packages/core/src/modules/overview/src/pages.sql.proof.md+++ /dev/null@@ -1,203 +0,0 @@-# pages.sql.ts — V1 -> V2 result-set proof (M7-005)--Same methodology and data as `overview.sql.proof.md` (whole-method comparison against-unmodified V1, plus a per-query render + execution pass) — see that file for the full-writeup. This file covers `PagesService` and `getPageConversionsCore`.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel`. Project: `skills-directory`,- window `2026-08-01 00:00:00`..`2026-08-08 00:00:00` UTC.--## Whole-method comparison — verdict--| Case | Verdict |-|---|---|-| `PagesService.getTopPages` | title column non-deterministic in **V1 itself** — see `overview.sql.proof.md`'s `anyLast` section. `sessions`/`pageviews`/`avg_duration`/`bounce_rate` IDENTICAL for all 20 rows. |-| `PagesService.getTopPages` (search: `'a'`) | same title-driven flicker (the search clause itself matches on `pt.title LIKE '%a%'`, so a flickering title changes which rows the search *keeps* — a downstream, not independent, effect); numeric columns IDENTICAL where titles agree. |-| `PagesService.getPageTimeseries` | **IDENTICAL** — 3103 rows |-| `getPageConversionsCore` | **IDENTICAL** — 20 rows |--`getPageConversionsCore` was already parameter-safe-ish (V1 used `sqlstring.escape` inline-rather than clix) but not through the `sql` tag; converted the same way as every other query-here — literals to `{pN:Type}` params, identical row order and values proven against the same-data.--## Per-query render + execution proof--| Query | Rows | Rows read | Wall |-|---|---|---|---|-| `topPagesQuery` | 20 | 229,342 | 62 ms |-| `topPagesQuery` (search: `'a'`) | 20 | 229,342 | 50 ms |-| `pageTimeseriesQuery` | 3103 | 49,152 | 18 ms |-| `pageConversionsQuery` | 20 | 147,456 | 68 ms |--```sql--- pageConversionsQuery-WITH- conversion_events AS (- SELECT profile_id, created_at AS conv_time FROM events- WHERE project_id = {p1:String} AND name = {p2:String}- AND created_at BETWEEN toDateTime({p3:String}) AND toDateTime({p4:String})- ),- views_before_conversions AS (- SELECT DISTINCT e.profile_id, e.path, e.origin FROM events AS e- INNER JOIN conversion_events AS c ON e.profile_id = c.profile_id- WHERE e.project_id = {p5:String} AND e.name = 'screen_view' AND e.path != ''- AND e.created_at BETWEEN toDateTime({p6:String}) AND toDateTime({p7:String})- AND e.created_at < c.conv_time AND e.created_at >= c.conv_time - INTERVAL {p8:UInt64} HOUR- ),- total_visitors AS (- SELECT path, origin, uniq(session_id) AS visitors FROM events- WHERE project_id = {p9:String} AND name = 'screen_view' AND path != ''- AND created_at BETWEEN toDateTime({p10:String}) AND toDateTime({p11:String})- GROUP BY path, origin- )-SELECT vbc.path, vbc.origin, count() AS unique_converters, any(tv.visitors) AS total_visitors,- round(100.0 * count() / any(tv.visitors), 2) AS conversion_rate-FROM views_before_conversions AS vbc-LEFT JOIN total_visitors AS tv ON vbc.path = tv.path AND vbc.origin = tv.origin-GROUP BY vbc.path, vbc.origin ORDER BY unique_converters DESC LIMIT {p12:UInt64}--- params: {"p1":"skills-directory","p2":"screen_view","p3":"2026-08-01 00:00:00","p4":"2026-08-08 00:00:00","p5":"skills-directory","p6":"2026-08-01 00:00:00","p7":"2026-08-08 00:00:00","p8":24,"p9":"skills-directory","p10":"2026-08-01 00:00:00","p11":"2026-08-08 00:00:00","p12":20}-```--Full renders exercised by `pages.sql.test.ts`'s `EXPLAIN`-based parse gate.--## M31-002 — `topPagesPerBucket`, the optional bound on `pageTimeseriesQuery`--- **Date**: 2026-09-16. **Data**: local prod-copy `openpanel` (read-only `SELECT`/`EXPLAIN`).- Window `2026-07-26 00:00:00`..`2026-08-25 00:00:00` UTC, `interval: 'day'`,- `use_query_condition_cache=0`, `max_memory_usage=6 GB`, statements rendered by the builder- itself (`toStatement()`) and executed with their bound `param_pN`.--Unbounded, the query is one row per `(origin, path, bucket)`, so its size is the project's page-cardinality rather than its traffic. `topPagesPerBucket` keeps the `n` busiest pages per bucket.--**Result sets — bounded vs unbounded, `sum(cityHash64(...))` over the whole set:**--| project | unbounded rows | `n = 50` rows | verdict |-|---|---:|---:|---|-| `chatpaper` | 5,050,763 | 1,500 | truncated (2.68 M distinct pages) |-| `website-8103` | 200,687 | 1,500 | truncated |-| `bayse` | 14,604 | 1,500 | truncated |-| `earlysalary-production` | 33 | 33 | **IDENTICAL hash** — 2 pages, always under the bound |-| `verdict` | 30 | 30 | **IDENTICAL hash** — no `screen_view`; all 30 are `WITH FILL` rows |--`verdict` is the proof that the bound does not eat the fill: `EXPLAIN PLAN` shows-`Filling > LimitBy`, i.e. ClickHouse fills **after** `LIMIT BY`, so an empty bucket still gets-its filled row and never spends the bucket's quota.--The truncated set is exactly the top `n`: an independent `row_number() OVER (PARTITION BY date-ORDER BY pageviews DESC, origin ASC, path ASC) <= 50` produced the identical hash on all three-truncated projects (`bayse` 13709211731794099286, `website-8103` 6888520080080211176,-`chatpaper` 566149299824503912).--**Why `origin ASC, path ASC` is part of the ranking, not decoration.** On `chatpaper` the 50th-place is 4–5 pageviews with **17–30 pages tied at that value** in every bucket. Without the-tiebreak the endpoint returned a different top-50 on every single call (3 runs, 3 different-hashes); with it, 3 runs, 1 hash. It costs nothing on four of five anchors and ~0.9–1.1 s on-`chatpaper`, whose 2.68 M-row sort is the only one large enough to notice.--**Timing and response size** (median of 3, `FORMAT Null`):--| project | unbounded | `n = 50` | response unbounded -> bounded |-|---|---|---|---|-| `chatpaper` | 1,603 ms / 1,556 MiB peak | 2,539 ms / 1,556 MiB peak | **485.7 MiB -> 0.67 MiB** |-| `website-8103` | 512 ms | 545 ms | 23.5 MiB -> 0.29 MiB |-| `bayse` | 336 ms | 344 ms | 2.06 MiB -> 0.20 MiB |-| `earlysalary-production` | 378 ms | 385 ms | unchanged |-| `verdict` | 39 ms | 34 ms | unchanged |--ClickHouse server time is **not** the win here and was not expected to be: the scan is-unchanged (13,401,914 rows read either way on `chatpaper`) and the added sort columns cost-~1 s there. What disappears is the response — and with it the ~5 s of serialisation M25-001-measured between this query's ClickHouse time and `event.pagesTimeseries`' procedure time.--Omitting `topPagesPerBucket` renders the query exactly as before: token-identical and-parameter-identical to the version at `4b7afb8e`, differing only by trailing whitespace where-the two conditional fragments render empty. `event.pageTimeseries` (the `origin`+`path`-filtered-variant) never passes it and is unchanged.--## M34-002 — `page_titles` bounded to the query's own range (Group C fix 8, remainder)--- **Date**: 2026-09-16, 09:02–09:06 UTC. **Data**: local prod-copy `openpanel`, read-only `SELECT`- (`events` read 321,191,847 before the run). `use_query_condition_cache=0`,- `session_timezone=UTC`, `max_memory_usage=6 GB`. Both statements rendered by the builders- themselves — "before" is `pages.sql.ts` at `26a56aa0`, "after" is this change — and bound through- `param_pN=`. Timings interleave old/new, median of 3, `FORMAT Null`, from `X-ClickHouse-Summary`.-- Windows: `1d` = 2026-08-24, `7d` = 2026-08-18 -> 08-24, `30d` = 2026-07-26 -> 08-24 (all- `23:59:59`-closed).--The `page_titles` CTE read `created_at >= now() - INTERVAL 30 DAY`, whatever the caller asked for.-It now reads `created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String})` — the-spelling the other two CTEs and M31-003 already use. Only the title column can change: the pages-and their numbers come from `screen_view_durations` and `sessions`, which were already bounded.--**The approved change:** a page whose title shows up **only outside the requested range** now gets-an empty title. The reverse also happens: a page viewed in the range whose only titles are more than-30 days before *now* used to have an empty title and now gets one.--### Result sets — before vs after, joined on `(origin, path)`, no `LIMIT`--| project | window | pages (both) | numeric columns differ | title differs |-|---|---|---:|---:|---:|-| `verdict` | 1d / 7d / 30d | 0 / 0 / 0 (no `screen_view`) | 0 | 0 |-| `earlysalary-production` | 1d / 7d / 30d | 1 / 2 / 2 | 0 | 0 |-| `website-8103` | 1d / 7d / 30d | 3,918 / 13,995 / 104,824 | 0 | 0 |-| `bayse` | 1d / 7d / 30d | 440 / 2,036 / 7,653 | 0 | 67 / 124 / 4,638 |-| `chatpaper` | 1d / 7d | 62,198 / 594,845 | 0 | 192 / 12,915 |--(`chatpaper` 30d was not joined: each side is 2.68 M pages.) **The pages and every numeric column-are identical everywhere.** Only titles differ, and part of that difference is not caused by this-change: `anyLast` already flickered **before** it (see the M7-005 section above). The old statement-compared with itself gave 14 differing titles on `bayse` 7d and 888 on `chatpaper` 1d. The new-statement compared with itself gave 75 on `bayse` 7d.--To measure only the approved effect, I counted **whether any non-empty title exists** for each-page in each window. That count does not flicker:--| project | window | loses its only title (titled only outside range, inside old window) | gains a title (titled only in range, outside old window) |-|---|---|---:|---:|-| `bayse` | 1d / 7d / 30d | 7 / 3 / 1 | 0 / 0 / **4,950** |-| `chatpaper` | 1d / 7d | 70 / **3,311** | 0 / 0 |-| `website-8103` | 1d / 7d / 30d | 0 / 0 / 0 | 0 / 0 / 0 |--On this copy, the old window was 2026-08-17 -> "now" (2026-09-16), so it held only the last eight-days of data. That is why a 30-day report on `bayse` *gained* 4,950 titles: those pages were titled-only before 08-17.--### Timing (median of 3, `LIMIT 50`)--| project / window | before (`now() - 30 DAY`) | after (range) |-|---|---|---|-| `verdict` 1d | 50 ms / 596,328 rows / 7 MiB read | 39 ms / 186,788 / 5 MiB |-| `verdict` 30d | 159 ms / 2,752,863 / 49 MiB | 164 ms / 3,784,293 / 52 MiB |-| `bayse` 1d | 452 ms / 6,691,332 / 1,743 MiB | **103 ms / 1,809,700 / 241 MiB** |-| `bayse` 7d | 563 ms / 10,991,899 / 1,944 MiB | 533 ms / 10,394,455 / 1,765 MiB |-| `bayse` 30d | 1,047 ms / 23,230,204 / 2,502 MiB | 1,937 ms / 34,436,987 / 6,122 MiB |-| `earlysalary-production` 1d | 860 ms / 4,549,922 / 9,208 MiB | **232 ms / 1,482,682 / 1,314 MiB** |-| `earlysalary-production` 7d | 968 ms / 7,146,746 / 9,457 MiB | 930 ms / 6,651,762 / 8,265 MiB |-| `earlysalary-production` 30d | 1,583 ms / 19,631,267 / 10,618 MiB | 4,120 ms / 31,137,529 / 39,818 MiB |-| `website-8103` 1d | 986 ms / 3,025,109 / 4,542 MiB | **326 ms / 879,433 / 459 MiB** |-| `website-8103` 7d | 1,196 ms / 4,822,514 / 4,708 MiB | 1,083 ms / 4,474,243 / 4,069 MiB |-| `website-8103` 30d | 2,285 ms / 14,965,439 / 5,661 MiB | 5,702 ms / 24,735,702 / 23,842 MiB |-| `chatpaper` 1d | 452 ms / 3,456,236 / 537 MiB | **143 ms / 950,030 / 67 MiB** |-| `chatpaper` 7d | 1,168 ms / 6,208,658 / 759 MiB | 1,079 ms / 5,865,077 / 695 MiB |-| `chatpaper` 30d | 6,706 ms / 19,798,407 / 1,848 MiB | 8,671 ms / 30,300,939 / 3,957 MiB |--(`verdict` 7d: 51 ms either way.) **Short windows get rid of the 30-day floor: 3–4x faster at 1d.**-The 30d rows get slower, and **this copy exaggerates that**. With the copy's last event on-2026-08-25, the old CTE read only eight days of data here. In production, "now" is current, so the-old CTE always read a full 30 days, and a 30d report reads about the same amount either way. The-real cost is for windows **longer than 30 days**: they now read the `properties` Map over the whole-range (§6.5 flagged this as the price of fix 8). Removing that Map read altogether is the separate-`__title` materialisation option in §6.5, and it was not proposed.--### Golden coverage--Only `getPagePerformanceCore` (`/insights/:projectId/pages/performance`) reaches this builder from-the REST surface. That covers the three `insights-pages-performance-*` cases, all on-`secure-privacy`, 2026-08-20. I ran each case's statement (`limit: 1000`, with the case's-`search`) and compared the results. The new statement matches both the old one as of today and the-old one with `now()` pinned to the capture instant (`2026-09-07 02:43:03`): same pages, numbers and-titles. It also matches every page in the captured response: 28/28, 28/28 and 6/6 titles equal.-These cases are `clock-anchored` (`require-same-utc-day`), so the gate reports them as stale. The-reason given for that rule is this CTE's `now()`, which no longer exists.diff --git a/packages/core/src/modules/overview/src/pages.sql.ts b/packages/core/src/modules/overview/src/pages.sql.tsindex 9cb10ff63..3b8304d4c 100644--- a/packages/core/src/modules/overview/src/pages.sql.ts+++ b/packages/core/src/modules/overview/src/pages.sql.ts@@ -1,9 +1,5 @@// Every ClickHouse query PagesService/getPageConversionsCore runs, as pure-// `sql` fragments (ADR-013). Converted 1:1 from-// packages/db/src/services/pages.service.ts: the SQL text is V1's, with every-// value bound as a `{pN:Type}` parameter instead of clix's inline-// interpolation or (for `getPageConversionsCore`) `sqlstring.escape`. Result-// sets diffed against V1's on the local prod-copy — see pages.sql.proof.md.+// `sql` fragments (ADR-013).import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { toRangeBoundaryLiteral } from '../../../shared/ch-dates';@@ -112,7 +108,7 @@ export interface PageTimeseriesQueryInput {/*** Keep only the `n` busiest pages in each date bucket. Omitted means* unbounded, which is one row per (origin, path, bucket) and on a project- * with per-user URL segments is millions of rows — see pages.sql.proof.md.+ * with per-user URL segments is millions of rows.* `origin`/`path` break the ranking's ties so the truncated set is stable* between calls; without them ClickHouse returns a different top-n on every* run (measured, M31-002).diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.tsindex 970606304..d80c10b8e 100644--- a/packages/core/src/modules/profile/profile.service.ts+++ b/packages/core/src/modules/profile/profile.service.ts@@ -1,20 +1,6 @@-// Ported from packages/db/src/services/profile.service.ts, the query bodies of-// packages/trpc/src/routers/profile.ts and apps/api/src/controllers/-// profile.controller.ts (M7-002). The db file is now a re-export shim over-// this one, so @openpanel/db importers (packages/trpc, the assistant/mcp-// tools, apps/api's controllers, notification.service, the buffers' types)-// keep working while V1 runs (DELEGATE PATTERN).-//-// Every query is a `sql` fragment (src/sql.ts), converted one at a-// time with a result-set proof each, per ADR-013. `buildFilterWhere` is NOT-// converted here: it is the shared filter compiler, out of this task's scope;-// src/filter-clauses.ts is the one bridge.-//-// M10-005: every function that touches ClickHouse or the profile buffer takes-// `ServiceDeps` and reaches them as `deps.ch` (through ch-query.ts) and-// `deps.buffers.profile`. The `loadChClient` / `loadProfileBuffer` lazy-// loaders are gone (docs/TECH_DEBT.md §2, §4), and M15-202 made the last one-// — the shared filter compiler — a plain static sibling import (ADR-022 R6).+// Every query is a `sql` fragment (src/sql.ts), per ADR-013. The exception is+// `buildFilterWhere`, the shared filter compiler; src/filter-clauses.ts is the+// bridge to it.import { strip, toObject } from '@openpanel/shared';import { assocPath, flatten, map, pathOr, pipe, prop, sort, uniq } from 'ramda';diff --git a/packages/core/src/modules/profile/src/profile-metrics-sql.test.ts b/packages/core/src/modules/profile/src/profile-metrics-sql.test.tsindex d23ff383b..d0b19ebd5 100644--- a/packages/core/src/modules/profile/src/profile-metrics-sql.test.ts+++ b/packages/core/src/modules/profile/src/profile-metrics-sql.test.ts@@ -1,12 +1,9 @@-// SQL-shape tests for the profile metrics query. Ported from-// packages/db/src/services/profile-metrics-sql.test.ts (M7-002) — minus its-// itCH ClickHouse-reachability EXPLAIN check, for the reason-// cohort-sql.test.ts's header gives (a sibling file's client mock applies-// process-wide). The rendered statement was EXPLAINed and result-diffed-// against V1 on the local prod-copy by hand instead — see the EXPLAIN section-// and the profileMetricsQuery case in profile.sql.proof.md. V1's-// "escapes the identifiers" test becomes "binds the identifiers": the `sql`-// tag never interpolates, so the hostile value can only appear in the params.+// SQL-shape tests for the profile metrics query. No ClickHouse-reachability+// EXPLAIN check here, for the reason cohort-sql.test.ts's header gives: a+// sibling file's client mock applies process-wide.+//+// "binds the identifiers" rather than "escapes" them — the `sql` tag never+// interpolates, so a hostile value can only ever appear in the params.import { describe, expect, test } from 'bun:test';import { profileMetricsQuery } from './sql';diff --git a/packages/core/src/modules/profile/src/profile.sql.proof.md b/packages/core/src/modules/profile/src/profile.sql.proof.mddeleted file mode 100644index a2f854803..000000000--- a/packages/core/src/modules/profile/src/profile.sql.proof.md+++ /dev/null@@ -1,574 +0,0 @@-# profile.sql.ts (now src/sql.ts) — V1 → V2 result-set proof (M7-002)--> **Amended 2026-09-23 (port of main `1f21214a`).** `profileListCountQuery` now-> reads `uniqExact(id)` where the two `profileListCountQuery` cases below show-> `count(id)`. The WHERE, the GROUP BY and the absence of FINAL are unchanged,-> and on a fully merged table both return the same number — which is why the-> proof's `5604` still holds. They diverge only while the table has unmerged-> ReplacingMergeTree versions, where `count(id)` counted every version and ran-> ahead of the page, which reads FINAL. Demonstrated on a scratch-> ReplacingMergeTree with one id written twice: `count(id)` 3, `uniqExact(id)`-> 2, `FINAL` 2.--Every query builder in `src/sql.ts` (`profile.sql.ts` at proof time; renamed under R1, M15-121) was executed twice against the same data — once as V1 (the `git HEAD` service/router code, `3300f2a0`) and once as V2 (core's service, which renders the builder) — through one patched ClickHouse client that captured each statement, its `query_params`, `clickhouse_settings`, wall time and the raw JSON response. The two responses were compared on `data` (every row, every column, as JSON) and `meta` (column names and types). Statements without an `ORDER BY` were compared as row sets, because ClickHouse's parallel aggregation returns them in a different order run to run — V1 against itself too.--- **Amended by M27-002 (2026-09-15): `profileRecentEventsQuery`'s ORDER BY is no longer V1's text.**- Same re-spelling as `event/src/sql.proof.md` records for `eventListQuery`, for the same reason: the- `events` sort key is `(project_id, toDate(created_at), created_at, name)` and `ORDER BY created_at DESC`- alone cannot use it (`docs/ANALYTICS_PERFORMANCE.md` §6.4). It now reads- `ORDER BY toDate(created_at) DESC, created_at DESC`; `toDate` is monotonic in `created_at`, so the order- is unchanged. Only the `-- V2` render of `profileRecentEventsQuery` (case- `profileRowQuery + profileRecentEventsQuery`, statement 2) carries it; the `-- V1` line is left as V1- wrote it. Re-proved against the local prod copy on **2026-09-15**, `use_query_condition_cache=0`,- numbers off `X-ClickHouse-Summary`, on each project's busiest identified profile of 2026-08:- - **Result sets:** both spellings as `FORMAT TSVRaw` compared by `sha256sum` (bytes and row order) on- `verdict`, `bayse`, `earlysalary-production`, `chatpaper`: **identical, 4/4**.- - **Cost, `LIMIT 20`, `read_rows` / warm `elapsed_ns`:** `verdict` 17,280,491 rows / 295 ms ->- **139,246 rows / 21 ms** · `bayse` 10,195,851 / 183 ms -> 204,800 / 24 ms ·- `earlysalary-production` 245,751 / 26-43 ms -> 180,217 / 31-47 ms · `chatpaper` 663,537 / 33-44 ms ->- 245,762 / 26-34 ms. On the two projects where `idx_profile_id` already pruned the read the two- spellings are within run-to-run noise over 5 warm iterations each; the win is on the two where it- did not.- - The per-statement `rows_read V1/V2` and `wall V1/V2` figures below are from the 2026-09-04 run and- therefore describe the pre-amendment V2 text.--- **Amended by M31-003 (2026-09-16): `profileListQuery`, `profileListCountQuery` and `powerUsersQuery`- are bounded to an explicit window.** M25 Group C fix 8, approved by Carl on 2026-09-15: all three- had no date filter at all, so their cost grew with the tenant's lifetime rather than with anything- the caller chose (`docs/ANALYTICS_PERFORMANCE.md` §6.8). Each now carries- `created_at BETWEEN toDateTime({pN:String}) AND toDateTime({pN:String})`, spelled as- `overview/src/pages.sql.ts` spells it. **This is the approved semantic change** — "power users of- all time" is now "power users of the range" — so these three cases are no longer V1-identical by- construction, and the V1 lines below stand as the record of what they used to be. `created_at` is- the column both tables can prune on (`profiles` is `PARTITION BY toYYYYMM(created_at)`; `events`- has it in the sort key) and the column the list already orders by; `profiles.last_seen_at` is in- neither and would prune nothing. See the M31-003 section at the end for the measurements.--- **Date**: 2026-09-04. **Data**: local prod-copy `openpanel` (319,499,000 events, static), project `redcollege` unless noted; cases needing rows the prod-copy lacks (`cohort_members`, `events_bots` are empty there) also ran on the isolated `openpanel_test` database with 3,380 events copied from `redcollege` under project `m7-002-proof`, plus seeded cohort/bot rows (deleted afterwards).-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are directional only; production is 2 shards × 2 replicas (`docs/ENVIRONMENT.md`). `rows_read` differences on JOIN statements are ClickHouse's per-run accounting of the right-hand side, not a plan difference: the SQL text is identical up to `{pN:Type}` binding.-- **Verdict**: 20 cases / 23 statements, all IDENTICAL. No conversion changed a result set.--The harness was a throwaway script (it needed verbatim copies of the V1 sources next to V2); each statement below is complete and reproducible with `curl http://127.0.0.1:8123/?database=openpanel`, binding the V2 params as `param_pN=`.--### profileMetricsQuery--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 335310/335310; wall V1/V2 = 52.5 ms / 49.1 ms; clickhouse_settings same.--```sql--- V1-WITH profileSeen AS ( SELECT created_at as firstSeen, last_seen_at as lastSeen FROM profiles FINAL WHERE id = '107145' AND project_id = 'redcollege' LIMIT 1 ), eventStats AS ( SELECT countIf(name = 'screen_view') as screenViews, countIf(name = 'session_start') as sessions, round(avgIf(duration, name = 'session_end' AND duration != 0) / 1000 / 60, 2) as durationAvg, round(quantilesExactInclusiveIf(0.9)(duration, name = 'session_end' AND duration != 0)[1] / 1000 / 60, 2) as durationP90, count(*) as totalEvents, count(DISTINCT toDate(created_at)) as uniqueDaysActive, round(avgIf(properties['__bounce'] = '1', name = 'session_end') * 100, 4) as bounceRate, countIf(name NOT IN ('screen_view', 'session_start', 'session_end')) as conversionEvents, sumIf(revenue, name = 'revenue') as revenue FROM events WHERE profile_id = '107145' AND project_id = 'redcollege' ) SELECT (SELECT lastSeen FROM profileSeen) as lastSeen, (SELECT firstSeen FROM profileSeen) as firstSeen, screenViews, sessions, durationAvg, durationP90, totalEvents, uniqueDaysActive, bounceRate, round(totalEvents / nullIf(sessions, 0), 2) as avgEventsPerSession, conversionEvents, CASE WHEN sessions <= 1 THEN 0 ELSE round(dateDiff('second', (SELECT firstSeen FROM profileSeen), (SELECT lastSeen FROM profileSeen)) / nullIf(sessions - 1, 0), 1) END as avgTimeBetweenSessions, revenue FROM eventStats--- V2-WITH profileSeen AS ( SELECT created_at as firstSeen, last_seen_at as lastSeen FROM profiles FINAL WHERE id = {p1:String} AND project_id = {p2:String} LIMIT 1 ), eventStats AS ( SELECT countIf(name = 'screen_view') as screenViews, countIf(name = 'session_start') as sessions, round(avgIf(duration, name = 'session_end' AND duration != 0) / 1000 / 60, 2) as durationAvg, round(quantilesExactInclusiveIf(0.9)(duration, name = 'session_end' AND duration != 0)[1] / 1000 / 60, 2) as durationP90, count(*) as totalEvents, count(DISTINCT toDate(created_at)) as uniqueDaysActive, round(avgIf(properties['__bounce'] = '1', name = 'session_end') * 100, 4) as bounceRate, countIf(name NOT IN ('screen_view', 'session_start', 'session_end')) as conversionEvents, sumIf(revenue, name = 'revenue') as revenue FROM events WHERE profile_id = {p3:String} AND project_id = {p4:String} ) SELECT (SELECT lastSeen FROM profileSeen) as lastSeen, (SELECT firstSeen FROM profileSeen) as firstSeen, screenViews, sessions, durationAvg, durationP90, totalEvents, uniqueDaysActive, bounceRate, round(totalEvents / nullIf(sessions, 0), 2) as avgEventsPerSession, conversionEvents, CASE WHEN sessions <= 1 THEN 0 ELSE round(dateDiff('second', (SELECT firstSeen FROM profileSeen), (SELECT lastSeen FROM profileSeen)) / nullIf(sessions - 1, 0), 1) END as avgTimeBetweenSessions, revenue FROM eventStats--- V2 params: {"p1":"107145","p2":"redcollege","p3":"107145","p4":"redcollege"}-```--Result (first rows, identical on both sides): `[{"lastSeen":"2026-08-28 19:45:27.000","firstSeen":"2026-08-10 20:01:50.000","screenViews":1447,"sessions":2,"durationAvg":5.48,"durationP90":9.65,"totalEvents":1482,"uniqueDaysActive":11,"bounceRate"`--### profileByIdQuery--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 106218/106218; wall V1/V2 = 29.0 ms / 29.8 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE id = '107145' AND project_id = 'redcollege' LIMIT 1--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE id = {p1:String} AND project_id = {p2:String} LIMIT 1--- V2 params: {"p1":"107145","p2":"redcollege"}-```--### profilesByIdsQuery--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 122602/122602; wall V1/V2 = 38.2 ms / 38.1 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = 'redcollege' AND id IN ('107145','107075','107098','missing')--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} AND id IN {p2:Array(String)}--- V2 params: {"p1":"redcollege","p2":["107145","107075","107098","missing"]}-```--### profileListQuery — page 1, no search--**statement** — IDENTICAL; rows V1/V2 = 25/25; rows_read V1/V2 = 122602/122602; wall V1/V2 = 36.8 ms / 36.7 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM profiles FINAL WHERE project_id = 'redcollege' ORDER BY created_at DESC LIMIT 25--- V2-SELECT * FROM profiles FINAL WHERE project_id = {p1:String} ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"redcollege","p2":25}-```--### profileListQuery — page 3, multi-token search, isExternal, filters--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 122602/122602; wall V1/V2 = 37.9 ms / 40.7 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM profiles FINAL WHERE project_id = 'redcollege' AND ((id ILIKE '%maria%' OR email ILIKE '%maria%' OR first_name ILIKE '%maria%' OR last_name ILIKE '%maria%' OR concat(first_name, ' ', last_name) ILIKE '%maria%') AND (id ILIKE '%colegio%' OR email ILIKE '%colegio%' OR first_name ILIKE '%colegio%' OR last_name ILIKE '%colegio%' OR concat(first_name, ' ', last_name) ILIKE '%colegio%')) AND is_external = true ORDER BY created_at DESC LIMIT 2 OFFSET 2--- V2-SELECT * FROM profiles FINAL WHERE project_id = {p1:String} AND ((id ILIKE {p2:String} OR email ILIKE {p3:String} OR first_name ILIKE {p4:String} OR last_name ILIKE {p5:String} OR concat(first_name, ' ', last_name) ILIKE {p6:String}) AND (id ILIKE {p7:String} OR email ILIKE {p8:String} OR first_name ILIKE {p9:String} OR last_name ILIKE {p10:String} OR concat(first_name, ' ', last_name) ILIKE {p11:String})) AND is_external = {p12:Bool} ORDER BY created_at DESC LIMIT {p13:UInt64} OFFSET {p14:UInt64}--- V2 params: {"p1":"redcollege","p2":"%maria%","p3":"%maria%","p4":"%maria%","p5":"%maria%","p6":"%maria%","p7":"%colegio%","p8":"%colegio%","p9":"%colegio%","p10":"%colegio%","p11":"%colegio%","p12":true,"p13":2,"p14":2}-```--### profileListCountQuery — no search--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 57344/57344; wall V1/V2 = 6.9 ms / 7.3 ms; clickhouse_settings same.--```sql--- V1-SELECT count(id) as count FROM profiles WHERE project_id = 'redcollege' GROUP BY project_id--- V2-SELECT count(id) as count FROM profiles WHERE project_id = {p1:String} GROUP BY project_id--- V2 params: {"p1":"redcollege"}-```--Result (first rows, identical on both sides): `[{"count":5604}]`--### profileListCountQuery — search, isExternal=false, filters--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 24576/24576; wall V1/V2 = 11.9 ms / 10.2 ms; clickhouse_settings same.--```sql--- V1-SELECT count(id) as count FROM profiles WHERE project_id = 'redcollege' AND ((id ILIKE '%maria%' OR email ILIKE '%maria%' OR first_name ILIKE '%maria%' OR last_name ILIKE '%maria%' OR concat(first_name, ' ', last_name) ILIKE '%maria%')) AND is_external = true GROUP BY project_id--- V2-SELECT count(id) as count FROM profiles WHERE project_id = {p1:String} AND ((id ILIKE {p2:String} OR email ILIKE {p3:String} OR first_name ILIKE {p4:String} OR last_name ILIKE {p5:String} OR concat(first_name, ' ', last_name) ILIKE {p6:String})) AND is_external = {p7:Bool} GROUP BY project_id--- V2 params: {"p1":"redcollege","p2":"%maria%","p3":"%maria%","p4":"%maria%","p5":"%maria%","p6":"%maria%","p7":true}-```--Result (first rows, identical on both sides): `[{"count":23}]`--### findProfilesQuery — every condition, asc, capped limit--**statement** — IDENTICAL; rows V1/V2 = 4/4; rows_read V1/V2 = 351028/351028; wall V1/V2 = 70.5 ms / 61.5 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = 'redcollege' AND email ILIKE '%colegio%' AND ((id ILIKE '%maria%' OR email ILIKE '%maria%' OR first_name ILIKE '%maria%' OR last_name ILIKE '%maria%' OR concat(first_name, ' ', last_name) ILIKE '%maria%')) AND properties['country'] = 'CL' AND properties['city'] = 'Santiago' AND properties['device'] = 'desktop' AND properties['browser'] = 'Chrome' AND id NOT IN ( SELECT DISTINCT profile_id FROM events WHERE project_id = 'redcollege' AND profile_id != '' AND created_at >= now() - INTERVAL 3 DAY ) AND id IN ( SELECT profile_id FROM sessions WHERE project_id = 'redcollege' AND sign = 1 AND profile_id != '' GROUP BY profile_id HAVING count() >= 1 ) AND id IN ( SELECT DISTINCT profile_id FROM events WHERE project_id = 'redcollege' AND name = 'screen_view' ) ORDER BY created_at ASC LIMIT 100--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} AND email ILIKE {p2:String} AND ((id ILIKE {p3:String} OR email ILIKE {p4:String} OR first_name ILIKE {p5:String} OR last_name ILIKE {p6:String} OR concat(first_name, ' ', last_name) ILIKE {p7:String})) AND properties[{p8:String}] = {p9:String} AND properties[{p10:String}] = {p11:String} AND properties[{p12:String}] = {p13:String} AND properties[{p14:String}] = {p15:String} AND id NOT IN ( SELECT DISTINCT profile_id FROM events WHERE project_id = {p16:String} AND profile_id != '' AND created_at >= now() - INTERVAL {p17:UInt64} DAY ) AND id IN ( SELECT profile_id FROM sessions WHERE project_id = {p18:String} AND sign = 1 AND profile_id != '' GROUP BY profile_id HAVING count() >= {p19:UInt64} ) AND id IN ( SELECT DISTINCT profile_id FROM events WHERE project_id = {p20:String} AND name = {p21:String} ) ORDER BY created_at ASC LIMIT {p22:UInt64}--- V2 params: {"p1":"redcollege","p2":"%colegio%","p3":"%maria%","p4":"%maria%","p5":"%maria%","p6":"%maria%","p7":"%maria%","p8":"country","p9":"CL","p10":"city","p11":"Santiago","p12":"device","p13":"desktop","p14":"browser","p15":"Chrome","p16":"redcollege","p17":3,"p18":"redcollege","p19":1,"p20":"redcollege","p21":"screen_view","p22":100}-```--### findProfilesQuery — defaults (project only)--**statement** — IDENTICAL; rows V1/V2 = 20/20; rows_read V1/V2 = 122602/122602; wall V1/V2 = 41.2 ms / 36.3 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = 'redcollege' ORDER BY created_at DESC LIMIT 20--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} ORDER BY created_at DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"redcollege","p2":20}-```--### profileRowQuery + profileRecentEventsQuery (getProfileWithEvents)--**statement 1** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 106218/106218; wall V1/V2 = 35.7 ms / 35.9 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = 'redcollege' AND id = '107145' LIMIT 1--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} AND id = {p2:String} LIMIT 1--- V2 params: {"p1":"redcollege","p2":"107145"}-```--**statement 2** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 131065/131065; wall V1/V2 = 26.5 ms / 34.4 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM events WHERE project_id = 'redcollege' AND profile_id = '107145' ORDER BY created_at DESC LIMIT 7--- V2-SELECT * FROM events WHERE project_id = {p1:String} AND profile_id = {p2:String} ORDER BY toDate(created_at) DESC, created_at DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":"107145","p3":7}-```--### profileSessionsQuery--**statement** — IDENTICAL; rows V1/V2 = 2/2; rows_read V1/V2 = 16378/16378; wall V1/V2 = 15.4 ms / 14.8 ms; clickhouse_settings same.--```sql--- V1-SELECT * FROM sessions WHERE project_id = 'redcollege' AND profile_id = '107145' AND sign = 1 ORDER BY created_at DESC LIMIT 5--- V2-SELECT * FROM sessions WHERE project_id = {p1:String} AND profile_id = {p2:String} AND sign = 1 ORDER BY created_at DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":"107145","p3":5}-```--### profilePropertyKeysQuery--**statement** — IDENTICAL (as row sets; no ORDER BY); rows V1/V2 = 23/23; rows_read V1/V2 = 49152/49152; wall V1/V2 = 8.4 ms / 11.6 ms; clickhouse_settings same.--```sql--- V1-SELECT DISTINCT arrayJoin(mapKeys(properties)) as key FROM profiles WHERE project_id = 'redcollege' AND is_external = true--- V2-SELECT DISTINCT arrayJoin(mapKeys(properties)) as key FROM profiles WHERE project_id = {p1:String} AND is_external = {p2:Bool}--- V2 params: {"p1":"redcollege","p2":true}-```--Result (first rows, identical on both sides): `[{"key":"__referrer"},{"key":"roles"},{"key":"cargo"},{"key":"establecimientoId"},{"key":"establecimientoNombre"},{"key":"country"},{"key":"city"},{"key":"region"},{"key":"longitude"},{"key":"latitude`--### profileActivityQuery (profile.activity)--**statement** — IDENTICAL; rows V1/V2 = 11/11; rows_read V1/V2 = 122874/122874; wall V1/V2 = 12.2 ms / 10.4 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count, toStartOfDay(created_at) as date FROM events WHERE project_id = 'redcollege' and profile_id = '107145' GROUP BY date ORDER BY date DESC--- V2-SELECT count(*) as count, toStartOfDay(created_at) as date FROM events WHERE project_id = {p1:String} and profile_id = {p2:String} GROUP BY date ORDER BY date DESC--- V2 params: {"p1":"redcollege","p2":"107145"}-```--Result (first rows, identical on both sides): `[{"count":195,"date":"2026-08-24 00:00:00"},{"count":90,"date":"2026-08-21 00:00:00"},{"count":193,"date":"2026-08-20 00:00:00"},{"count":175,"date":"2026-08-19 00:00:00"},{"count":132,"date":"2026-08`--### profileMostEventsQuery (profile.mostEvents)--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 114683/114683; wall V1/V2 = 11.7 ms / 12.1 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count, name FROM events WHERE name NOT IN ('screen_view', 'session_start', 'session_end') AND project_id = 'redcollege' and profile_id = '107145' GROUP BY name ORDER BY count DESC--- V2-SELECT count(*) as count, name FROM events WHERE name NOT IN ('screen_view', 'session_start', 'session_end') AND project_id = {p1:String} and profile_id = {p2:String} GROUP BY name ORDER BY count DESC--- V2 params: {"p1":"redcollege","p2":"107145"}-```--Result (first rows, identical on both sides): `[{"count":31,"name":"link_out"}]`--### profilePopularRoutesQuery (profile.popularRoutes)--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 122874/122874; wall V1/V2 = 15.4 ms / 17.6 ms; clickhouse_settings same.--```sql--- V1-SELECT count(*) as count, path FROM events WHERE name = 'screen_view' AND project_id = 'redcollege' and profile_id = '107145' GROUP BY path ORDER BY count DESC LIMIT 10--- V2-SELECT count(*) as count, path FROM events WHERE name = 'screen_view' AND project_id = {p1:String} and profile_id = {p2:String} GROUP BY path ORDER BY count DESC LIMIT {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":"107145","p3":10}-```--Result (first rows, identical on both sides): `[{"count":485,"path":"/271/2026/libros"},{"count":231,"path":"/271/2026/asistencia-consolidada"},{"count":33,"path":"/271/2026/inicio"},{"count":28,"path":"/271/2026/libros/12533/asistencia"},{"count"`--### profilePropertyNamesQuery (profile.properties)--**statement** — IDENTICAL (as row sets; no ORDER BY); rows V1/V2 = 281/281; rows_read V1/V2 = 57344/57344; wall V1/V2 = 9.4 ms / 9.4 ms; clickhouse_settings same.--```sql--- V1-SELECT distinct mapKeys(properties) as keys from profiles where project_id = 'redcollege';--- V2-SELECT distinct mapKeys(properties) as keys from profiles where project_id = {p1:String};--- V2 params: {"p1":"redcollege"}-```--Result (first rows, identical on both sides): `[{"keys":["path","country","city","region","longitude","latitude","os","os_version","browser","browser_version","device","referrer","referrer_name"]},{"keys":["path","country","city","region","longitu`--### powerUsersQuery — page 2 (profile.powerUsers)--**statement 1** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 106218/106218; wall V1/V2 = 34.7 ms / 34.0 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = 'redcollege' AND id IN ('102208','91117','36357','183365','19316','133571','157236','161982','133563','107114')--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} AND id IN {p2:Array(String)}--- V2 params: {"p1":"redcollege","p2":["102208","91117","36357","183365","19316","133571","157236","161982","133563","107114"]}-```--**statement 2** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 155641/155641; wall V1/V2 = 10.6 ms / 13.6 ms; clickhouse_settings same.--```sql--- V1-SELECT profile_id, count(*) as count FROM events WHERE profile_id != '' AND project_id = 'redcollege' GROUP BY profile_id ORDER BY count() DESC LIMIT 10 OFFSET 10--- V2-SELECT profile_id, count(*) as count FROM events WHERE profile_id != '' AND project_id = {p1:String} GROUP BY profile_id ORDER BY count() DESC LIMIT {p2:UInt64} OFFSET {p3:UInt64}--- V2 params: {"p1":"redcollege","p2":10,"p3":10}-```--Result (first rows, identical on both sides): `[{"profile_id":"102208","count":776},{"profile_id":"91117","count":728},{"profile_id":"36357","count":722},{"profile_id":"183365","count":721},{"profile_id":"19316","count":687},{"profile_id":"133571"`--### powerUsersQuery — first page (no OFFSET)--**statement 1** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 106218/106218; wall V1/V2 = 34.9 ms / 33.6 ms; clickhouse_settings same.--```sql--- V1-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = 'redcollege' AND id IN ('179221','107145','132720','107075','107139','107098','112629','133575','107144','167538')--- V2-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL WHERE project_id = {p1:String} AND id IN {p2:Array(String)}--- V2 params: {"p1":"redcollege","p2":["179221","107145","132720","107075","107139","107098","112629","133575","107144","167538"]}-```--**statement 2** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 155641/155641; wall V1/V2 = 10.0 ms / 10.7 ms; clickhouse_settings same.--```sql--- V1-SELECT profile_id, count(*) as count FROM events WHERE profile_id != '' AND project_id = 'redcollege' GROUP BY profile_id ORDER BY count() DESC LIMIT 10--- V2-SELECT profile_id, count(*) as count FROM events WHERE profile_id != '' AND project_id = {p1:String} GROUP BY profile_id ORDER BY count() DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"redcollege","p2":10}-```--Result (first rows, identical on both sides): `[{"profile_id":"179221","count":2377},{"profile_id":"107145","count":1482},{"profile_id":"132720","count":1387},{"profile_id":"107075","count":1361},{"profile_id":"107139","count":1182},{"profile_id":`--### profileValuesQuery — properties.* path with array wildcard--**statement** — IDENTICAL; rows V1/V2 = 14/14; rows_read V1/V2 = 57344/57344; wall V1/V2 = 11.4 ms / 10.9 ms; clickhouse_settings same.--```sql--- V1-SELECT distinct arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, 'roles'))) as values FROM profiles WHERE project_id = 'redcollege'--- V2-SELECT distinct arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, {p1:String}))) as values FROM profiles WHERE project_id = {p2:String}--- V2 params: {"p1":"roles","p2":"redcollege"}-```--Result (first rows, identical on both sides): `[{"values":[]},{"values":["[\"Profesor\"]"]},{"values":["[\"Admin\"]"]},{"values":["[\"Admin\",\"Profesor\"]"]},{"values":["[\"Admin\",\"Apoderado\"]"]},{"values":["[\"Profesor\",\"Apoderado\"]"]},{"v`--### profileValuesQuery — bare column--**statement** — IDENTICAL; rows V1/V2 = 5604/5604; rows_read V1/V2 = 57344/57344; wall V1/V2 = 6.6 ms / 6.7 ms; clickhouse_settings same.--```sql--- V1-SELECT first_name as values FROM profiles WHERE project_id = 'redcollege'--- V2-SELECT first_name as values FROM profiles WHERE project_id = {p1:String}--- V2 params: {"p1":"redcollege"}-```--## profileMetricsQuery — EXPLAIN--`profile-metrics-sql.test.ts` drops V1's `itCH('parses and resolves against ClickHouse')` case (see its header for why core's suite cannot host a reachability check). The same check was run by hand on the rendered V2 statement with its bound params (`profile-1` / `test-sql-validation`, the test's own fixtures) against the prod-copy:--```-EXPLAIN <profileMetricsQuery(...).toStatement().query> -- params {"p1":"profile-1","p2":"test-sql-validation","p3":"profile-1","p4":"test-sql-validation"}-Expression ((Project names + (Projection + (Change column names to column identifiers + (Project names + Projection)))))- Aggregating- Expression (Before GROUP BY)- Expression ((WHERE + Change column names to column identifiers))- ReadFromMergeTree (openpanel.events)-```--Parsed and resolved (73.6 ms). The plan shows one `ReadFromMergeTree` on `events` — the property the string tests guard; the `profiles` CTE is consumed through scalar subqueries, which ClickHouse evaluates ahead of the plan it prints. The result-set diff for the same builder on a real profile is the `profileMetricsQuery` case above.--## M31-003 — the explicit window (2026-09-16)--Run against the local prod-copy `openpanel` on **2026-09-16**, `use_query_condition_cache=0`,-`session_timezone=UTC`, numbers off `X-ClickHouse-Summary`, every statement rendered by the builder-itself (not retyped) and bound through `param_pN=`. Old and new were **interleaved** within each-5-iteration loop so neither owns the warm cache; the ms column is the median of 5, the rows/bytes-columns are invariant across iterations. `LIMIT 50`, which is `DEFAULT_LIST_TAKE`.--**A caveat this copy forces, stated first.** The copy's whole history fits inside three months —-`events` end 2026-08-25 and `profiles.created_at` spans 2026-07-01 -> 2026-08-30 — so at the default-`3m` range the window covers **all** the data and cannot prune anything. The `3m` column below is-therefore the *floor* case (what the change costs when it buys nothing), and the `7d` column is what-it buys as soon as the window is narrower than the tenant's history. On a tenant older than the-window the `3m` column moves toward the `7d` one; nothing on this box can show that, because no-project here is older than the window.--### `powerUsersQuery` (`events`)--| project | unbounded (V1) | default `3m` | `7d` (2026-08-18 -> 08-25) |-|---|---|---|---|-| `verdict` | 657 ms / 44,164,383 rows / 1017 MiB | 834 ms / 44,164,383 / 1354 MiB | **105 ms / 4,821,286 / 154 MiB** |-| `earlysalary-production` | 621 ms / 26,787,424 / 1624 MiB | 725 ms / 26,787,424 / 1828 MiB | **100 ms / 3,465,150 / 228 MiB** |-| `chatpaper` | 666 ms / 19,797,378 / 888 MiB | 777 ms / 19,797,378 / 1039 MiB | **101 ms / 2,662,273 / 134 MiB** |--At a window narrower than the data this is **6.3x fewer rows and ~6x faster**. At the default on this-copy it is **15-27 % slower**, and that is not noise: the `BETWEEN` adds `created_at` to the columns-read (+337 / +204 / +151 MiB) while pruning nothing, because everything is inside the window. That is-the unavoidable floor price of any date filter on this table, and it is bounded — after the change-the endpoint can never read more than three months, where before it read the tenant's whole life.--### `profileListQuery` / `profileListCountQuery` (`profiles`)--| statement | project | unbounded (V1) | default `3m` | `7d` |-|---|---|---|---|---|-| list | `chatpaper` | 309 ms / 1,858,944 / 707 MiB | 292 ms / 1,858,944 / 707 MiB | **125 ms / 794,624 / 301 MiB** |-| list | `earlysalary-production` | 278 ms / 1,827,940 / 861 MiB | 279 ms / 1,827,940 / 861 MiB | **128 ms / 851,968 / 406 MiB** |-| list | `verdict` | 156 ms / 916,864 / 380 MiB | 155 ms / 916,864 / 380 MiB | **71 ms / 434,176 / 178 MiB** |-| count | `chatpaper` | 65 ms / 1,662,816 / 74 MiB | 78 ms / 1,662,816 / 87 MiB | **40 ms / 745,472 / 39 MiB** |-| count | `earlysalary-production` | 49 ms / 1,624,345 / 95 MiB | 54 ms / 1,624,345 / 107 MiB | **24 ms / 802,816 / 33 MiB** |-| count | `verdict` | 30 ms / 745,312 / 32 MiB | 37 ms / 745,312 / 37 MiB | **31 ms / 385,024 / 19 MiB** |--The list pays **nothing** at the default — `SELECT *` already read `created_at` — and halves at a-narrower window. Only the count pays the extra column (+5 to +13 ms), for the same reason-`powerUsers` does.--### Result sets: what changed, and what did not--The window is a pure restriction, so where it covers all the data the answer must be unchanged. It-is, on every anchor — compared as result **sets** (`sorted(rows)`, sha256), `LIMIT 50`:--| query | `verdict` | `chatpaper` | `earlysalary-production` | `bayse` | `website-8103` |-|---|---|---|---|---|---|-| `powerUsersQuery` unbounded vs default `3m` | IDENTICAL | IDENTICAL | IDENTICAL | IDENTICAL | IDENTICAL |-| `profileListQuery` unbounded vs default `3m` | IDENTICAL | IDENTICAL | — | — | — |-| `profileListCountQuery` unbounded vs default `3m` | 696,160 = 696,160 | 1,609,483 = 1,609,483 | — | — | — |--At `7d` they differ, which is the approved change: `verdict`'s top-50 power users keep **23 of 50**-ids, `bayse` **39 of 50**; the profile count falls 1,609,483 -> 208,529 on `chatpaper` and-696,160 -> 92,275 on `verdict`.--**One thing to know before comparing `powerUsersQuery` by ordered rows: it was already-nondeterministic, and still is.** `ORDER BY count() DESC` has no tiebreak, so equal-count rows come-back in whatever order the parallel aggregation produced. Five runs of the **unbounded** statement,-unchanged, on 2026-09-16: `chatpaper` returned **4 distinct** ordered-row hashes, `earlysalary-production`-**5 distinct**. The top-50 *set* was stable across all of them. This is pre-existing (M31-003 changed-no `ORDER BY`), and it is why the table above compares sets — an ordered-row diff of this builder-reports a difference that is not a change.--### M34-002 — the rest of fix 8--- **`page_titles` in `event.pages` / `event.previousPages`**: done. It uses the same- `created_at BETWEEN toDateTime(..) AND toDateTime(..)` spelling. The proof is in- `overview/src/pages.sql.proof.md`, section "M34-002".-- **The REST retention series** (`/insights/:projectId/retention`, `/engagement`): done, after the- task was re-scoped to `chart` and `export`. `retentionSeriesQuery` and- `retentionLastSeenSeriesQuery` use the same `created_at BETWEEN toDateTime(..) AND toDateTime(..)`- spelling. Both routes now accept `range` / `startDate` / `endDate`, and the default is `3m`, the- same as here. The default is applied on the routes only: the MCP tools that call the same- service without dates still read all time. The proof is in `chart/src/retention.sql.proof.md`, section "M34-002".--## M38-001 — explicit PREWHERE on `profilesByIdsQuery` (2026-09-16)--`FINAL` turns off automatic PREWHERE (`optimize_move_to_prewhere_if_final = 0` on this server), so-the V1 shape read all 11 columns for every row in the project's key range. The statement now reads:--```sql-SELECT id, first_name, last_name, email, avatar, properties, project_id, is_external, created_at, last_seen_at, groups FROM profiles FINAL PREWHERE project_id = {p1:String} AND id IN {p2:Array(String)}-```--The setting was **not** changed server-wide or in `CLICKHOUSE_SETTINGS`. The PREWHERE is on this one-statement only. Both conditions use sort-key columns only, and every version of a-`ReplacingMergeTree` row shares them, so filtering before the `FINAL` merge drops no version that-the merge would keep. The `IN` takes a bound literal array, not a subquery, so `GLOBAL IN` does not-apply. On a `Distributed` table, the shards receive the PREWHERE with the rest of the statement, and-`FINAL` stays per shard, as before.--**Method.** 2026-09-16, 17:40–17:55 UTC, single node, ClickHouse 26.1.3.52, prod copy `openpanel`-(SELECT only), HTTP with `use_query_cache=0` and the client's settings. The ids were bound as-`{p2:Array(String)}`, the same as production. **The page cache was warm and not controlled.**-Every pair was compared three ways: the row count, sha256 of the sorted `FORMAT TSVRaw` output,-and `cityHash64(arraySort(groupArray(cityHash64(tuple(*)))))` computed on the server. The hashes-are truncated to 16 hex characters. No rows left the box or were printed.--**Result sets: identical in all 18 prod-copy pairs and all 9 duplicate-version pairs.** Only the-unordered row order differs. The statement has no `ORDER BY`, and all six `getProfiles` /-`getProfilesCached` callers index the result by `id` (see "Callers" below).--| project | id set | rows | sorted sha (old = new) | server hash (old = new) |-|---|---|--:|---|--:|-| verdict | 200 sampled + 2 missing | 200 | 990ff37720bbd9ee | 2207503090764657581 |-| verdict | 1,000 sampled | 1000 | 52f97c198baf11aa | 10633293728532801169 |-| verdict | 2026-08-20 bucket, first 200 | 113 | 89e5dfe568bc840f | 3782160794143776797 |-| verdict | 2026-08-20 bucket, ≤1,000 | 557 | f923bf2f66e0f529 | 9998950015958726181 |-| bayse | 200 sampled + 2 missing | 200 | a3c5fa45f03e566f | 5808497201729836461 |-| bayse | 1,000 sampled | 1000 | 6bccde35694a0d5d | 15599780444145327832 |-| bayse | 2026-08-20 bucket, first 200 | 67 | 787b5b61b92fab5e | 15475558395705370151 |-| bayse | 2026-08-20 bucket, ≤1,000 | 476 | ab1ba0dac490c5f6 | 17356756279215469892 |-| earlysalary-production | 200 sampled + 2 missing | 200 | c672481141af7754 | 10996104250063144912 |-| earlysalary-production | 1,000 sampled | 1000 | e385c4fe9b40e97b | 4868776334728909166 |-| earlysalary-production | 2026-08-20 bucket, first 200 | 195 | 7fd9304dd609e859 | 1770102371015330504 |-| earlysalary-production | 2026-08-20 bucket, ≤1,000 | 974 | f1ad3f126d5466aa | 16534687301997138277 |-| website-8103 | 200 sampled + 2 missing | 200 | fc35ccc87636163b | 14505134278598945611 |-| website-8103 | 1,000 sampled | 1000 | 5a906205e04747c6 | 6368711441762070328 |-| chatpaper | 200 sampled + 2 missing | 200 | caf0a176212258cb | 9471910246293331129 |-| chatpaper | 1,000 sampled | 1000 | 5c278c8382b2413b | 13601208562850535735 |-| chatpaper | `screen_view` 2026-08-20 bucket, first 200 | 200 | aa019808e0770ee3 | 17930342762468771172 |-| chatpaper | `screen_view` 2026-08-20 bucket, 1,000 | 1000 | 01cb23d19b21b6e9 | 12578565101048520051 |--Key to the id sets. "Sampled" means `ORDER BY cityHash64(id) LIMIT n` over the project's profiles.-"Missing" means one unknown id and one quote-injection string. "Bucket" means-`DISTINCT profile_id` from `events` on that day. `website-8103` has no non-empty bucket ids.--**Duplicate versions.** The prod copy has no un-merged duplicates (M37-002 §4), so it cannot-exercise the `FINAL` merge. A scratch database, `openpanel_m38`, held a copy of the `profiles` DDL-with **synthetic** rows only: 5 inserts with merges stopped, 20 parts, and 75,000 rows over 15,000-`(project_id, id)` keys. Each key had 5 versions, with `created_at` spread across 4 partitions and-tied `last_seen_at` values. Old and new returned the same result for 200, 1,000 and 5,000 ids in each-of 3 projects:--| project | ids | rows | sorted sha (old = new) |-|---|--:|--:|---|-| proj-a | 201 / 1000 / 5000 | 200 / 1000 / 5000 | e0eb58de4d3d5c46 / 715b257a3034cabb / f0394f87bd48b50a |-| proj-b | 201 / 1000 / 5000 | 200 / 1000 / 5000 | 0027b01ee499da6f / d1da354936467673 / 881ec0da794c33ca |-| proj-c | 201 / 1000 / 5000 | 200 / 1000 / 5000 | c32dab9e4f45d2a5 / 4e594a31dd87bf2f / 2f73bcde4061e82e |--**Cost** (`X-ClickHouse-Summary`, `FORMAT Null`, warm cache). `chatpaper` runs 3 times each and the-other projects once:--| project / id set | read_rows (old = new) | bytes old → new | ClickHouse ms old → new |-|---|--:|--:|--:|-| chatpaper, bucket 200 | 1,809,792 | 686.2 → **191.4 MiB** | 278–280 → **105–108** |-| chatpaper, bucket 1,000 | 1,850,752 | 701.6 → **196.3 MiB** | 285–287 → **111–117** |-| chatpaper, 200 sampled | 1,793,408 | 680.0 → 372.2 MiB | 275–281 → 159–167 |-| chatpaper, 1,000 sampled | 1,850,752 | 701.6 → 663.8 MiB | 290–298 → 217–220 |-| verdict, bucket ≤1,000 | 916,864 | 379.8 → 136.1 MiB | 149 → 67 |-| bayse, bucket ≤1,000 | 400,928 | 197.8 → 149.5 MiB | 86 → 63 |-| earlysalary-production, bucket ≤1,000 | 959,588 | 464.6 → 125.5 MiB | 169 → 62 |-| website-8103, 1,000 sampled | 57,184 | 27.2 → 13.5 MiB | 19 → 15 |--These reproduce M37-002's figures of 683 → 194 MiB and 702 → 196 MiB. As predicted, `read_rows` does-not fall. The bytes saved depend on the id set. Ids drawn uniformly by hash across the whole table-save less: 1,000 sampled `chatpaper` ids read 664 MiB. The likely cause is that those ids touch more-parts and partitions, so more wide-column ranges are read. This was not verified. No case read more.--**Callers.** `getProfiles` / `getProfilesCached` are called from `event.service.ts:433`-(`attachProfiles`, Map by id), `session.service.ts:296` (Map by id), `cohort.service.ts:919` and-`group.service.ts:355` (Map by id, re-ordered by the page's ids), `realtime.service.ts:365` (Map by-id) and `profile.service.ts:581` (`find` by id, in `powerUsers` row order). None of these reads the-statement's row order. The chart drill-down (`chart.service.ts:213`, `getProfilesInBatches`)-flattens batches in ClickHouse order, and that order was never defined (M37-002 §5).--### M38-001 re-verification (2026-09-16, 18:14–18:16 UTC)--The task was queued again after `a5de15cc` landed. The statement was left unchanged and checked-again with fresh id sets: sampled with `ORDER BY cityHash64(id, 'm38r')`, a different seed from-above. The bucket sets were the first 200 and the first 1,000 `DISTINCT profile_id` values for-2026-08-20. Setup was the same as above: SELECT only, `use_query_cache=0`, ids bound as-`{ids:Array(String)}`, warm page cache (not controlled), 3 runs per statement, `FORMAT Null`-for the timings. `optimize_move_to_prewhere_if_final` was still `0` and unchanged, and-`openpanel.events` read 321,192,097 rows afterwards.--**Harness trap.** The bucket query has no `ORDER BY` (M37-002 §5). If it is re-run separately for-the old and new statement, each gets a *different* id set, and the results then "differ"-(`verdict` 553 vs 555 rows). **The id set must be fetched once and then bound into both-statements.** Every pair below was run that way.--| project | id set | rows | server hash (old = new) | sorted TSVRaw sha256 (old = new) | read_rows (old = new) | MiB old → new | ms old → new (3 runs) |-|---|---|--:|--:|---|--:|--:|---|-| chatpaper | 200 sampled | 200 | 6044796785930619165 | 0703cff63baa2122 | 1,777,024 | 673 → 339 | 273–277 → 145–150 |-| chatpaper | 1,000 sampled | 1000 | 5118306366967811222 | eac298181769fc78 | 1,850,752 | 701 → 645 | 290–294 → 215–227 |-| chatpaper | bucket 200 | 200 | 2748211310319356327 | 754e2bc6157f695d | 1,793,408 | 679 → **189** | 274–285 → **105–120** |-| chatpaper | bucket 1,000 | 1000 | 5238269254189401937 | 61b52e790eb31ba9 | 1,850,752 | 701 → **196** | 290–292 → **113–119** |-| verdict | 200 sampled | 200 | 7985449783458714454 | 77f9befd42dc88c2 | 908,672 | 375 → 284 | 150–153 → 100–101 |-| verdict | 1,000 sampled | 1000 | 12521734476894561923 | 8021782b8712c0c9 | 916,864 | 379 → 359 | 156–157 → 114–116 |-| verdict | bucket 200 | 99 | 14408474298995108646 | e2213ef60e4d5a49 | 892,288 | 368 → 105 | 146–147 → 57–60 |-| verdict | bucket ≤1,000 | 553 | 9329860756388786918 | 54070a37ae21af23 | 916,864 | 379 → 136 | 148–158 → 70–73 |-| bayse | 200 sampled | 200 | 15279523433519712370 | e163fbea8a9613fb | 400,928 | 197 → 144 | 85–88 → 61–68 |-| bayse | 1,000 sampled | 1000 | 3597386053856923017 | 976b8a4a265a3361 | 400,928 | 197 → 156 | 86–95 → 68–71 |-| bayse | bucket 200 | 67 | 15475558395705370151 | 942bd52c2f664459 | 400,928 | 197 → 82 | 85–92 → 42–45 |-| bayse | bucket ≤1,000 | 454 | 7213855973727416649 | c2c2da5bb64327c9 | 400,928 | 197 → 148 | 88–93 → 65–68 |-| earlysalary-production | 200 sampled | 200 | 17838043424397308023 | 48925bfd2828b164 | 1,418,340 | 674 → 415 | 230–234 → 150 |-| earlysalary-production | 1,000 sampled | 1000 | 159571559975720793 | 2cbd707917a26725 | 1,827,940 | 861 → 799 | 289–290 → 222–230 |-| earlysalary-production | bucket 200 | 195 | 1770102371015330504 | 88215b4312829db2 | 885,860 | 428 → 111 | 155–164 → 53–58 |-| earlysalary-production | bucket ≤1,000 | 974 | 16534687301997138277 | 82ceee10f8e2f477 | 959,588 | 464 → 125 | 171–180 → 61–65 |-| website-8103 | 200 sampled | 200 | 17137450707755332480 | 90779f0deb7b8b50 | 57,184 | 27 → 13 | 18–20 → 14–20 |-| website-8103 | 1,000 sampled | 1000 | 10463793702330735470 | 2c684ab785246424 | 57,184 | 27 → 13 | 22–23 → 15–17 |-| website-8103 | bucket (no non-empty ids) | 0 | 4761183170873013810 | e3b0c44298fc1c14 | 0 | 0 → 0 | 3 → 1–2 |--All 19 pairs were identical. The server hashes for `bayse` bucket 200 and for-`earlysalary-production` bucket 200 and ≤1,000 are the same values as in the first table, so the-bucket sets and the results reproduced across runs. This section's `sha256` is `sort | sha256sum` over the-`TSVRaw` output. For the same result it does not match the first table's sha, so that table must-have used a different method. Compare only the server hashes across the two tables.-The figures from M37-002 were reproduced again: 683 → 194 MiB for a 200-id batch and 702 → 196 MiB-for a 1,000-id statement.diff --git a/packages/core/src/modules/profile/src/sql.ts b/packages/core/src/modules/profile/src/sql.tsindex 6cd2dfc59..7463a3e0b 100644--- a/packages/core/src/modules/profile/src/sql.ts+++ b/packages/core/src/modules/profile/src/sql.ts@@ -1,17 +1,10 @@// Every ClickHouse query the profile module runs, as pure `sql` fragments-// (ADR-013). Converted 1:1 from packages/db/src/services/profile.service.ts-// and packages/trpc/src/routers/profile.ts (M7-002): the SQL text is V1's,-// with every value bound as a `{pN:Type}` parameter instead of an escaped-// literal. Each builder's result set was diffed against V1's on the local-// prod-copy; the statements, params, row counts and timings are in-// profile.sql.proof.md.+// (ADR-013).//-// Cluster note (docs/ENVIRONMENT.md): `profiles`, `events` and `sessions` are-// Distributed on Cloud. `findProfilesQuery`'s three `IN (SELECT ...)`-// subqueries and any a filter compiles to keep V1's exact shape and run under-// the client's `distributed_product_mode: 'allow'` as before — converting a-// query is not the place to change its cluster semantics. Every `IN` list-// binds as `Array(String)`, a literal list to the planner.+// Cluster note: `profiles`, `events` and `sessions` are Distributed on Cloud.+// `findProfilesQuery`'s three `IN (SELECT ...)` subqueries, and any a filter+// compiles to, run under the client's `distributed_product_mode: 'allow'`.+// Every `IN` list binds as `Array(String)`, a literal list to the planner.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import { toRangeBoundaryLiteral } from '../../../shared/ch-dates';diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.tsindex 5b463048c..bbb086ca3 100644--- a/packages/core/src/modules/project/project.service.ts+++ b/packages/core/src/modules/project/project.service.ts@@ -1,24 +1,6 @@-// Moved from packages/db/src/services/project.service.ts (M6-002, module-// map: project owns "R,H,S,C"). packages/db keeps a re-export shim: its own-// access.service.ts and notification.service.ts still reach `getProjectById`-// / `getProjectByIdCached` through the same relative path, and-// apps/api/src/utils/auth.ts reaches them through @openpanel/db's barrel;-// auth.service.ts's permission ladder (M10-002) reaches a project through-// `shared/access-lookups.ts`, which has no `ServiceDeps` of its own to carry-// (M15-005: it reads Postgres from `context.ts`'s `unscopedDb()` instead).-//-// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` lazy loader is gone. M15-005: `getProjectByIdCached`-// is a module-scope `cacheablePerDb` for the same reason `getClientByIdCached`-// is in client.service.ts — see that file's header.-//-// M12-006 converted this module's two ClickHouse statements-// (`getProjectEventsCount` / `getLastEventPerProject`) onto the ADR-013 `sql`-// tag: every value binds as a `{pN:Type}` param, so `sqlstring` and `clix` are-// both gone. The CLIENT is `deps.ch` either way, through core's own `chQuery`-// (ch-query.ts) — M10-009 dropped the `compatChHelpers()` hop these two-// used to make. The V1-vs-V2 result-set proof is `project.sql.proof.md` beside-// this file.+// `getProjectByIdCached` is a module-scope `cacheablePerDb` for the same+// reason `getClientByIdCached` is in client.service.ts — see that file's+// header.import crypto from 'node:crypto';import { sql } from '@openpanel/db/src/clickhouse/sql';diff --git a/packages/core/src/modules/project/project.sql.proof.md b/packages/core/src/modules/project/project.sql.proof.mddeleted file mode 100644index 36997e4f2..000000000--- a/packages/core/src/modules/project/project.sql.proof.md+++ /dev/null@@ -1,146 +0,0 @@-# project.service.ts — V1 → V2 result-set proof (M12-006)--Both ClickHouse statements `packages/core/src/modules/project/project.service.ts`-runs, executed V1 against V2 on the local prod-copy `openpanel`. V1 is the file-at commit `78098bdc`-(`git show HEAD:packages/core/src/modules/project/project.service.ts`), which-builds `getProjectEventsCount` as a `sqlstring.escape`d template string and-`getLastEventPerProject` with `clix`; V2 is the converted file, every value-bound as a `{pN:Type}` param. **Both files were imported into one Bun process-and called with the same inputs** — the SQL below was produced by calling the-real exported functions with a `deps.ch.query` stub that captures-`{query, query_params, clickhouse_settings}`, never by retyping V1 by hand. Each-captured statement was then executed through the local HTTP interface at-`format: 'JSON'` with the settings its own side asked for; V1 went as `query`,-V2 as `query` + `param_pN`. `data` was compared row-for-row and `meta`-column-for-column.--**One case was compared as a set**: `getLastEventPerProject` is-`GROUP BY project_id` with **no `ORDER BY` at all**, so ClickHouse is free to-emit the 1,864 groups in any order and V1-vs-V2 row order carries no meaning.-Its 1,864 rows are identical as a set (`{project_id, last_event_at}` pairs-sorted and compared) and the two sides did in fact come back in different orders-— V1's 3rd/4th rows are `paper`/`2334`, V2's are `2334`/`paper`, same pairs — so-the set comparison is load-bearing here rather than a formality. Nothing was-sorted away that is not explained here.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,850,903 events;- `distinct_event_names_mv` holds 1,864 projects. Fixtures: `verdict`- (41,921,451 non-session events) for the positive-row case, and- `o'brien-prod` — **which does not exist** — for the quote-in-the-value- escaping case. That second case returns one row whose `count` is 0; its- positive-row twin is the `verdict` run immediately above it, and it is listed- because a value carrying a `'` is the whole point of the escaping half of this- conversion.-- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either- direction.** `grep -c GLOBAL` is `0` on the V1 file and `0` on the V2 file;- both sides emit exactly one `NOT IN` per statement and its operand is a- literal value list (V1 an inline tuple, V2 an `Array(String)` param) — there- is no `IN (subquery)` in this module, so the distributed-`IN` trap does not- arise.-- **Verdict**: **3 statement pairs, all IDENTICAL.**--## `session_timezone`--`clix(client)` with no timezone argument defaults to `'UTC'`-(`query-builder.ts:696-697`) and sends it as-`clickhouse_settings.session_timezone` on every `execute()` (`:562`).-`getProjectEventsCount` was already a raw `chQuery(deps, text)` call and sent-none. V2 preserves both halves via `CLIX_SESSION_TIMEZONE`, and the capture-confirms it per statement:--| statement | built by (V1) | V1 sent | V2 sends |-|---|---|---|---|-| `getProjectEventsCount` | raw `chQuery` | *(none)* | *(none)* |-| `getLastEventPerProject` | `clix` | `UTC` | `UTC` |--## `getProjectEventsCount` — `verdict`--**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 =-**41921451/41921451**; `meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`;-rows_read V1/V2 = 221184/221184; wall V1/V2 = 10 ms / 9 ms;-clickhouse_settings: *(none)* on both.--```sql--- V1-SELECT sum(event_count) as count FROM distinct_event_names_mv-WHERE project_id = 'verdict' AND name NOT IN ('session_start', 'session_end')--- V2-SELECT sum(event_count) as count FROM distinct_event_names_mv-WHERE project_id = {p1:String} AND name NOT IN {p2:Array(String)}--- V2 params: {"p1":"verdict","p2":["session_start","session_end"]}-```--## `getProjectEventsCount` — `o'brien-prod` (quote in the value)--**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **0/0**; `meta`-V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 = 8192/8192; wall-V1/V2 = 4 ms / 4 ms; clickhouse_settings: *(none)* on both.--The single quote is handled on both sides — V1 by `sqlstring`'s backslash escape-(`'o\'brien-prod'`), V2 by never putting the value in the text at all. No such-project exists in the prod copy, so the count is 0 on both sides; the row-bearing-coverage for this statement is the `verdict` case above.--```sql--- V1-SELECT sum(event_count) as count FROM distinct_event_names_mv-WHERE project_id = 'o\'brien-prod' AND name NOT IN ('session_start', 'session_end')--- V2-SELECT sum(event_count) as count FROM distinct_event_names_mv-WHERE project_id = {p1:String} AND name NOT IN {p2:Array(String)}--- V2 params: {"p1":"o'brien-prod","p2":["session_start","session_end"]}-```--## `getLastEventPerProject`--**statement** — IDENTICAL (**compared as a set**, see the header); rows V1/V2 =-**1864/1864**; `meta` V1/V2 =-`[{"name":"project_id","type":"String"},{"name":"last_event_at","type":"DateTime64(3)"}]`;-rows_read V1/V2 = 10992588/11000780; wall V1/V2 = 125 ms / 134 ms;-clickhouse_settings: `session_timezone=UTC` (both).--`rows_read` differs by 8,192 (one granule) between the two sides. That is index-analysis treating a bound `{p1:Array(String)}` differently from an inline tuple-for the `NOT IN` on a `LowCardinality(String)` column — a perf note, not a-semantic one: the 1,864 returned groups and their `max(created_at)` values are-identical.--```sql--- V1-SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv-WHERE name NOT IN ('session_start', 'session_end')-GROUP BY project_id--- V2-SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv-WHERE name NOT IN {p1:Array(String)}-GROUP BY project_id--- V2 params: {"p1":["session_start","session_end"]}-```--## Tests--No test in this module compares generated SQL text, so none had to be retargeted-to compare statement + params. `project.service.test.ts` exercises the Postgres-half of the service through a fake `deps.db`; its assertions are unchanged and-the file is untouched by this task.--## Reproduce--```bash-# getLastEventPerProject, V1-curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC&default_format=JSONCompact' \- --data-binary "SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv WHERE name NOT IN ('session_start', 'session_end') GROUP BY project_id"--# getLastEventPerProject, V2-curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \- --data-urlencode 'default_format=JSONCompact' \- --data-urlencode "param_p1=['session_start','session_end']" \- --data-urlencode 'query=SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv WHERE name NOT IN {p1:Array(String)} GROUP BY project_id'-```--Both return 1,864 rows.diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.tsindex 3207a19d9..e7a40dcf5 100644--- a/packages/core/src/modules/realtime/realtime.service.ts+++ b/packages/core/src/modules/realtime/realtime.service.ts@@ -1,40 +1,11 @@-// Two halves ported from different V1 places, both landing here (module map:-// realtime owns "R,H,S"):+// The realtime queries plus the `/live` websocket glue:+// `getActiveVisitorCount` and the four `subscribeToPublishedEvent` calls,+// filtered by projectId.//-// 1. The six ClickHouse queries, moved from-// packages/trpc/src/routers/realtime.ts (M6-007). V1's trpc router stays-// the LIVE route (DELEGATE PATTERN, ONE shared tRPC instance) and now-// delegates its handler bodies onto the functions below, exported through-// `@openpanel/core`'s barrel, same as notification.ts/reference.ts.-//-// 2. The `/live` websocket glue, ported FRESH from-// apps/api/src/controllers/live.controller.ts's business logic —-// `getActiveVisitorCount` and the four `subscribeToPublishedEvent` calls,-// filtered by projectId where V1 filters inline in the callback. V1's-// Fastify `@fastify/websocket` controller is LEFT UNTOUCHED: its socket-// type (the `ws` package's `WebSocket`) has nothing in common with-// Elysia/Bun's `ElysiaWS`, so there is no shim to delegate through, and-// touching the golden-harness-critical V1 ws stack for a few lines of-// framework glue is the risk this port avoids (task M6-007 notes).-// `subscribeToPublishedEvent` itself is already framework-agnostic-// (`@openpanel/redis`, plain callback), so both stacks call the exact-// same Redis subscription underneath.-//-// M10-005: every query function takes `ServiceDeps`. The ClickHouse CLIENT is-// `deps.ch` — reads through ch-query.ts — and the event buffer is-// `deps.buffers.event`, so the `loadChClient` / `loadEventBuffer` lazy imports-// of @openpanel/db are gone and the requestId reaches the query (ADR-018 R1,-// docs/TECH_DEBT.md §2, §4).-//-// M12-005 converted all ten ClickHouse statements here onto the ADR-013 `sql`-// tag: every value binds as a `{pN:Type}` param, table names go through-// `sql.id`, and the location filters compose as fragments instead of escaped-// text. `sqlstring`, `clix` and the `loadChHelpers()` lazy hop into-// `@openpanel/db` are all gone — `TABLE_NAMES` and the date helpers come from-// core's own pure copies (shared/ch-tables.ts, shared/ch-dates.ts), which is-// what lets the import be static without constructing a ClickHouse client or a-// pino transport at module load. The V1-vs-V2 result-set proof is-// `realtime.sql.proof.md` beside this file.+// `TABLE_NAMES` and the date helpers come from core's own pure copies+// (shared/ch-tables.ts, shared/ch-dates.ts) rather than @openpanel/db, which+// is what lets the import stay static: db's clickhouse/client.ts constructs a+// real client and a pino transport at module load.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import {diff --git a/packages/core/src/modules/realtime/realtime.sql.proof.md b/packages/core/src/modules/realtime/realtime.sql.proof.mddeleted file mode 100644index ee1069b26..000000000--- a/packages/core/src/modules/realtime/realtime.sql.proof.md+++ /dev/null@@ -1,609 +0,0 @@-# realtime.service.ts — V1 → V2 result-set proof (M12-005)--Every ClickHouse statement `packages/core/src/modules/realtime/realtime.service.ts`-runs, executed V1 against V2 on the local prod-copy `openpanel`. V1 is the file-at commit `794bef39` (`git show HEAD:packages/core/src/modules/realtime/realtime.service.ts`),-which builds four statements with `clix` and six with `sqlstring.escape`; V2 is-the converted file, every value bound as a `{pN:Type}` param. **Both were-imported into one Bun process and called with the same inputs** — the SQL below-was produced by calling the real functions with a `deps.ch.query` stub that-captures `{query, query_params, clickhouse_settings}`, never by retyping V1 by-hand — and each captured statement was then executed through one-`@clickhouse/client` at `format: 'JSON'` with the settings its own side asked-for. `data` was compared row-for-row and `meta` column-for-column.--No case needed set comparison: every statement either has a total `ORDER BY`-over a unique key, returns one row, or (`coordinates`, `geo`, `paths`,-`referrals`, `activeSessions`) was byte-identical in the emitted row order on-both sides.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,850,758 events. Project- `pincali-production` (the primary fixture: 3,523 events, 74 distinct- countries in the reference window) plus `verdict` during harness bring-up.- Nothing is empty here — every statement below returns rows.-- **Reference time**: the prod copy's newest event is `2026-08-25 08:49:53`, so- a realtime window anchored on the wall clock is empty by construction. Both- sides were run with `Date` frozen at **`2026-08-25 08:49:53Z`**, which makes- `since()` = `2026-08-25 08:19:53` on both. `getRealtimeCoordinates` computes- its window in SQL (`now() - INTERVAL 30 MINUTE`), so for the row-bearing runs- `now()` was textually replaced with `toDateTime('2026-08-25 08:49:53')`- **on both sides**; run R7 in the results table is the same pair executed- exactly as rendered, with the real `now()`, and returns 0/0 — recorded because- a zero-row case proves only that both texts parse.-- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are- directional only; production is 2 shards × 2 replicas (`docs/ENVIRONMENT.md`).- **No `IN` / `GLOBAL IN` was changed in either direction.** `grep -c GLOBAL`- is `0` on the V1 file and `0` on the V2 file; V1 emits `IN (` 3× plus one- `NOT IN`, V2 emits `IN (` 2× plus one `IN ${...}` (the country list, now an- `Array(String)` param) plus one `NOT IN`. Every `IN` operand on both sides is- a literal value list — there is no `IN (subquery)` anywhere in this module, so- the distributed-`IN` trap does not arise.-- **Verdict**: **70 statement pairs, all IDENTICAL** — 65 IDENTICAL and 5- IDENTICAL ERROR (one V1 defect, reproduced byte-for-byte; §*Filter shapes*,- "country, 7-character value").--## `session_timezone`, per statement--The behaviour the conversion had to preserve: `clix(client)` with no timezone-argument defaults to `'UTC'` (`query-builder.ts:696-697`) and sends it as-`clickhouse_settings.session_timezone` on every `execute()`-(`query-builder.ts:562`). The three statements that were already raw-`chQuery(deps, text)` calls sent **no** `session_timezone` at all. V2 keeps both-halves: `CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' }` on the seven that-came off clix, nothing on the three that did not.--| statement | built by (V1) | V1 sent | V2 sends |-|---|---|---|---|-| `getRealtimeCoordinates` | raw `chQuery` | *(none)* | *(none)* |-| mapBadge `summary` | `clix` | `UTC` | `UTC` |-| mapBadge `topReferrers` | `clix` | `UTC` | `UTC` |-| mapBadge `topPaths` | `clix` | `UTC` | `UTC` |-| mapBadge `topEvents` | `clix` | `UTC` | `UTC` |-| mapBadge `recentSessions` | raw `chQuery` | *(none)* | *(none)* |-| `getRealtimeActiveSessions` | raw `chQuery` | *(none)* | *(none)* |-| `getRealtimePaths` | `clix` | `UTC` | `UTC` |-| `getRealtimeReferrals` | `clix` | `UTC` | `UTC` |-| `getRealtimeGeo` | `clix` | `UTC` | `UTC` |--The `session_timezone V1 -> V2` column of the results table is not a-restatement of this table: it is what the harness read back off each captured-call, on every one of the 70 pairs.--## No lazy loads left--The task's gate is a recursive `grep` for the two-token phrase *await* +-*import* across `packages/core/src/modules/realtime`, negated. It exits 0 on-this tree: **there is no deferred module load left in the module, source or-test.** (This file deliberately does not spell that phrase out, so the proof-does not become the match it is certifying.)--`loadChHelpers()` — `import('../../v1-compat').then((m) => m.compatChHelpers())`,-whose `compatChHelpers` is a `Promise.all([import('@openpanel/db/src/clickhouse/client'),-import('@openpanel/db/src/clickhouse/query-builder')])` — is gone. `TABLE_NAMES`-and `formatClickhouseDate`/`convertClickhouseDateToJs` are static imports of-core's own pure copies (`shared/ch-tables.ts`, `shared/ch-dates.ts`, both-parity-tested against `@openpanel/db`), and the ClickHouse client is `deps.ch`-as it already was. That is ADR-007's deps rule and docs/TECH_DEBT.md §4 step 2.--`loadRedis()` stays, and is the one deliberate exception: it is an intra-package-deferral with its own header (several other modules' tests replace-`@openpanel/redis` wholesale with a partial factory, and a static named import-here would demand `subscribeToPublishedEvent` on every one of those subsets the-moment this module joins the eager barrel chain). It is not a `@openpanel/db`-load and it reaches no client — `deps` still carries every connection.--## Grep gate--```-$ bash tooling/gates/p12-grep-gates.sh --report | grep -E 'realtime|TOTAL'-```--| | sqlstring | clix | sql-builder |-|---|---|---|---|-| `realtime.service.ts` before | 8 | 7 | 0 |-| `realtime.service.ts` after | **absent from the report (0/0/0)** | | |-| TOTAL before | 36 | 73 | 6 |-| TOTAL after | **28** | **66** | 6 |--The module-header paragraph that said its queries "still go through-clix/sqlstring" is deleted.--## Tests that compared statement text--`realtime.service.test.ts`'s `getRealtimeActiveSessions` case asserted-`query` contained `project_id = 'proj_1'` and `LIMIT 50`. Its assertions are-unchanged in what they check — the same project scoping, the same 30-minute-window, the same limit — but they now read the statement **and its params**:-`project_id = {p1:String}` / `created_at >= {p2:String}` / `LIMIT {p3:UInt64}`-in the text, and `p1 === 'proj_1'`, `p2` inside the 30-minute window, `p3 === 50`-in `query_params`. It is the only text-comparing test in the module; nothing-else in `packages/core` asserts on realtime SQL.--## Reproducing a case--Every statement below runs under-`curl 'http://127.0.0.1:8123/?database=openpanel'`, binding V2's params as-`param_pN=`. Worked example — `getRealtimeGeo`, both sides:--```bash-curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \- --data-urlencode 'default_format=JSONCompact' \- --data-urlencode "query=SELECT country, city, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = 'pincali-production' AND created_at >= '2026-08-25 08:19:53' GROUP BY country, city ORDER BY count DESC LIMIT 50"--curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \- --data-urlencode 'default_format=JSONCompact' \- --data-urlencode 'param_p1=pincali-production' \- --data-urlencode 'param_p2=2026-08-25 08:19:53' \- --data-urlencode 'param_p3=50' \- --data-urlencode "query=SELECT country, city, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = {p1:String} AND created_at >= {p2:String} GROUP BY country, city ORDER BY count DESC LIMIT {p3:UInt64}"-```--Both return the same 50 rows, the first being-`["MX","Iztapalapa",277,9,55.82]`.--## The ten statements--Texts and numbers below are run **R3** (`detailScope: 'city'`,-`locations = [{MX, Iztapalapa}, {MX, Iztapalapa}, {MX, O'Brien}]` — the-duplicate exercises V1's tuple de-duplication, the apostrophe exercises the-escaping V2 replaces with binding). The other five location shapes are in-*Filter shapes*; all ten statements were run under every shape, and the full-70-pair table is at the end.--### getRealtimeCoordinates--**statement** — IDENTICAL; rows V1/V2 = 440/440; rows_read V1/V2 = 8192/8192; wall V1/V2 = 37 ms / 11 ms; clickhouse_settings: no session_timezone sent (both). `meta` identical: `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "city", "type": "String"}, {"name": "long", "type": "Nullable(Float32)"}, {"name": "lat", "type": "Nullable(Float32)"}, {"name": "count", "type": "UInt64"}]`.--```sql--- V1-SELECT- country,- city,- longitude as long,- latitude as lat,- COUNT(DISTINCT session_id) as count- FROM events- WHERE project_id = 'pincali-production'- AND created_at >= now() - INTERVAL 30 MINUTE- AND longitude IS NOT NULL- AND latitude IS NOT NULL- GROUP BY country, city, longitude, latitude- ORDER BY count DESC- LIMIT 5000---- V2-SELECT- country,- city,- longitude as long,- latitude as lat,- COUNT(DISTINCT session_id) as count- FROM events- WHERE project_id = {p1:String}- AND created_at >= now() - INTERVAL {p2:UInt64} MINUTE- AND longitude IS NOT NULL- AND latitude IS NOT NULL- GROUP BY country, city, longitude, latitude- ORDER BY count DESC- LIMIT {p3:UInt64}--- V2 params: {"p1": "pincali-production", "p2": 30, "p3": 5000}-```--First row, both sides:--```json-{"country": "US", "city": "", "long": -97.822, "lat": 37.751, "count": 30}-```--### getRealtimeMapBadgeDetails - summary--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 30440/8192; wall V1/V2 = 14 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both). `meta` identical: `[{"name": "total_sessions", "type": "UInt64"}, {"name": "total_profiles", "type": "UInt64"}]`.--```sql--- V1-SELECT COUNT(DISTINCT session_id) as total_sessions, COUNT(DISTINCT nullIf(profile_id, '')) as total_profiles FROM events WHERE project_id = 'pincali-production' AND created_at >= '2026-08-25 08:19:53' AND (coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'O\'Brien'))---- V2-SELECT COUNT(DISTINCT session_id) as total_sessions, COUNT(DISTINCT nullIf(profile_id, '')) as total_profiles FROM events WHERE project_id = {p1:String} AND created_at >= {p2:String} AND (coalesce(country, ''), coalesce(city, '')) IN (({p3:String}, {p4:String}), ({p5:String}, {p6:String}))--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "MX", "p4": "Iztapalapa", "p5": "MX", "p6": "O'Brien"}-```--First row, both sides:--```json-{"total_sessions": 9, "total_profiles": 9}-```--### getRealtimeMapBadgeDetails - topReferrers--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 30440/8192; wall V1/V2 = 9 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both). `meta` identical: `[{"name": "referrer_name", "type": "String"}, {"name": "count", "type": "UInt64"}]`.--```sql--- V1-SELECT referrer_name, COUNT(DISTINCT session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= '2026-08-25 08:19:53' AND referrer_name != '' AND (coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'O\'Brien')) GROUP BY referrer_name ORDER BY count DESC LIMIT 3---- V2-SELECT referrer_name, COUNT(DISTINCT session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= {p2:String} AND referrer_name != {p3:String} AND (coalesce(country, ''), coalesce(city, '')) IN (({p4:String}, {p5:String}), ({p6:String}, {p7:String})) GROUP BY referrer_name ORDER BY count DESC LIMIT {p8:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "", "p4": "MX", "p5": "Iztapalapa", "p6": "MX", "p7": "O'Brien", "p8": 3}-```--First row, both sides:--```json-{"referrer_name": "Instagram", "count": 5}-```--### getRealtimeMapBadgeDetails - topPaths--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 30440/8192; wall V1/V2 = 15 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both). `meta` identical: `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "count", "type": "UInt64"}]`.--```sql--- V1-SELECT origin, path, COUNT(DISTINCT session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= '2026-08-25 08:19:53' AND path != '' AND (coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'O\'Brien')) GROUP BY origin, path ORDER BY count DESC LIMIT 3---- V2-SELECT origin, path, COUNT(DISTINCT session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= {p2:String} AND path != {p3:String} AND (coalesce(country, ''), coalesce(city, '')) IN (({p4:String}, {p5:String}), ({p6:String}, {p7:String})) GROUP BY origin, path ORDER BY count DESC LIMIT {p8:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "", "p4": "MX", "p5": "Iztapalapa", "p6": "MX", "p7": "O'Brien", "p8": 3}-```--First row, both sides:--```json-{"origin": "https://www.pincali.com", "path": "/inmuebles/departamentos-en-renta-en-lomas-de-angelopolis-san-andres-cholula-puebla", "count": 4}-```--### getRealtimeMapBadgeDetails - topEvents--**statement** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 30440/30440; wall V1/V2 = 11 ms / 13 ms; clickhouse_settings: session_timezone=UTC (both). `meta` identical: `[{"name": "name", "type": "LowCardinality(String)"}, {"name": "count", "type": "UInt64"}]`.--```sql--- V1-SELECT name, COUNT(DISTINCT session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= '2026-08-25 08:19:53' AND name NOT IN ('screen_view', 'session_start', 'session_end') AND (coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'O\'Brien')) GROUP BY name ORDER BY count DESC LIMIT 3---- V2-SELECT name, COUNT(DISTINCT session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= {p2:String} AND name NOT IN {p3:Array(String)} AND (coalesce(country, ''), coalesce(city, '')) IN (({p4:String}, {p5:String}), ({p6:String}, {p7:String})) GROUP BY name ORDER BY count DESC LIMIT {p8:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": ["screen_view", "session_start", "session_end"], "p4": "MX", "p5": "Iztapalapa", "p6": "MX", "p7": "O'Brien", "p8": 3}-```--First row, both sides:--```json-{"name": "viewed_property", "count": 8}-```--### getRealtimeMapBadgeDetails - recentSessions--**statement** — IDENTICAL; rows V1/V2 = 8/8; rows_read V1/V2 = 30440/8192; wall V1/V2 = 13 ms / 10 ms; clickhouse_settings: no session_timezone sent (both). `meta` identical: `[{"name": "session_id", "type": "String"}, {"name": "profile_id", "type": "String"}, {"name": "created_at", "type": "DateTime64(3)"}, {"name": "path", "type": "String"}, {"name": "name", "type": "LowCardinality(String)"}, {"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "city", "type": "String"}]`.--```sql--- V1-SELECT- session_id,- profile_id,- created_at,- path,- name,- country,- city- FROM (- SELECT- session_id,- profile_id,- created_at,- path,- name,- country,- city,- row_number() OVER (- PARTITION BY session_id ORDER BY created_at DESC- ) AS rn- FROM events- WHERE project_id = 'pincali-production'- AND created_at >= '2026-08-25 08:19:53'- AND ((coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'O\'Brien')))- ) AS latest_event_per_session- WHERE rn = 1- ORDER BY created_at DESC- LIMIT 8---- V2-SELECT- session_id,- profile_id,- created_at,- path,- name,- country,- city- FROM (- SELECT- session_id,- profile_id,- created_at,- path,- name,- country,- city,- row_number() OVER (- PARTITION BY session_id ORDER BY created_at DESC- ) AS rn- FROM events- WHERE project_id = {p1:String}- AND created_at >= {p2:String}- AND ((coalesce(country, ''), coalesce(city, '')) IN (({p3:String}, {p4:String}), ({p5:String}, {p6:String})))- ) AS latest_event_per_session- WHERE rn = 1- ORDER BY created_at DESC- LIMIT {p7:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "MX", "p4": "Iztapalapa", "p5": "MX", "p6": "O'Brien", "p7": 8}-```--First row, both sides:--```json-{"session_id": "lQLYoMO0FxZQscKsbvv-nA", "profile_id": "965388", "created_at": "2026-08-25 08:45:01.457", "path": "/inmueble/departamento-en-torre-uma-puebla-8fafd079-af3d-4436-9b2d-274a1fd92d0e", "name": "session_end", "country": "MX", "city": "Iztapalapa"}-```--### getRealtimeActiveSessions--**statement** — IDENTICAL; rows V1/V2 = 50/50; rows_read V1/V2 = 16384/16384; wall V1/V2 = 11 ms / 20 ms; clickhouse_settings: no session_timezone sent (both). `meta` identical: `[{"name": "name", "type": "LowCardinality(String)"}, {"name": "session_id", "type": "String"}, {"name": "created_at", "type": "DateTime64(3)"}, {"name": "path", "type": "String"}, {"name": "origin", "type": "String"}, {"name": "referrer", "type": "String"}, {"name": "referrer_name", "type": "String"}, {"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "city", "type": "String"}, {"name": "region", "type": "LowCardinality(String)"}, {"name": "os", "type": "LowCardinality(String)"}, {"name": "os_version", "type": "LowCardinality(String)"}, {"name": "browser", "type": "LowCardinality(String)"}, {"name": "browser_version", "type": "LowCardinality(String)"}, {"name": "device", "type": "LowCardinality(String)"}]`.--```sql--- V1-SELECT- name, session_id, created_at, path, origin, referrer, referrer_name,- country, city, region, os, os_version, browser, browser_version,- device- FROM events- WHERE project_id = 'pincali-production'- AND created_at >= '2026-08-25 08:19:53'- ORDER BY created_at DESC- LIMIT 50---- V2-SELECT- name, session_id, created_at, path, origin, referrer, referrer_name,- country, city, region, os, os_version, browser, browser_version,- device- FROM events- WHERE project_id = {p1:String}- AND created_at >= {p2:String}- ORDER BY created_at DESC- LIMIT {p3:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": 50}-```--First row, both sides:--```json-{"name": "screen_view", "session_id": "ITvWNzUlSBMtKLgwxnbqGg", "created_at": "2026-08-25 08:49:53.034", "path": "/inmobiliarios/lucas_vazquez/inmueble/excelente-departamento-en-renta-en-la-colonia-roma-roma-norte", "origin": "https://www.pincali.com", "referrer": "", "referrer_name": "easybroker.com", "country": "MX", "city": "Miguel Hidalgo", "region": "Mexico City", "os": "Android", "os_version": "10", "browser": "Mobile Chrome", "browser_version": "151.0.0.0", "device": "mobile"}-```--### getRealtimePaths--**statement** — IDENTICAL; rows V1/V2 = 50/50; rows_read V1/V2 = 8192/8192; wall V1/V2 = 11 ms / 11 ms; clickhouse_settings: session_timezone=UTC (both). `meta` identical: `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "count", "type": "UInt64"}, {"name": "unique_sessions", "type": "UInt64"}, {"name": "avg_duration", "type": "Float64"}]`.--```sql--- V1-SELECT origin, path, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = 'pincali-production' AND path != '' AND created_at >= '2026-08-25 08:19:53' GROUP BY path, origin ORDER BY count DESC LIMIT 50---- V2-SELECT origin, path, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = {p1:String} AND path != {p2:String} AND created_at >= {p3:String} GROUP BY path, origin ORDER BY count DESC LIMIT {p4:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "", "p3": "2026-08-25 08:19:53", "p4": 50}-```--First row, both sides:--```json-{"origin": "https://www.pincali.com", "path": "/inmuebles/casas-en-venta", "count": 109, "unique_sessions": 1, "avg_duration": 6.55}-```--### getRealtimeReferrals--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 8192/8192; wall V1/V2 = 15 ms / 10 ms; clickhouse_settings: session_timezone=UTC (both). `meta` identical: `[{"name": "referrer_name", "type": "String"}, {"name": "count", "type": "UInt64"}, {"name": "unique_sessions", "type": "UInt64"}, {"name": "avg_duration", "type": "Float64"}]`.--```sql--- V1-SELECT referrer_name, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = 'pincali-production' AND referrer_name IS NOT NULL AND created_at >= '2026-08-25 08:19:53' GROUP BY referrer_name ORDER BY count DESC LIMIT 50---- V2-SELECT referrer_name, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = {p1:String} AND referrer_name IS NOT NULL AND created_at >= {p2:String} GROUP BY referrer_name ORDER BY count DESC LIMIT {p3:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": 50}-```--First row, both sides:--```json-{"referrer_name": "", "count": 2677, "unique_sessions": 582, "avg_duration": 10.43}-```--### getRealtimeGeo--**statement** — IDENTICAL; rows V1/V2 = 50/50; rows_read V1/V2 = 8192/8192; wall V1/V2 = 8 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both). `meta` identical: `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "city", "type": "String"}, {"name": "count", "type": "UInt64"}, {"name": "unique_sessions", "type": "UInt64"}, {"name": "avg_duration", "type": "Float64"}]`.--```sql--- V1-SELECT country, city, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = 'pincali-production' AND created_at >= '2026-08-25 08:19:53' GROUP BY country, city ORDER BY count DESC LIMIT 50---- V2-SELECT country, city, COUNT(*) as count, COUNT(DISTINCT session_id) as unique_sessions, round(avg(duration)/1000, 2) as avg_duration FROM events WHERE project_id = {p1:String} AND created_at >= {p2:String} GROUP BY country, city ORDER BY count DESC LIMIT {p3:UInt64}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": 50}-```--First row, both sides:--```json-{"country": "MX", "city": "Iztapalapa", "count": 277, "unique_sessions": 9, "avg_duration": 55.82}-```--## Filter shapes--`buildRealtimeBadgeDetailsFilter` picks one of three filters by `detailScope`,-with two fallbacks (`coordinate` with no numeric lat/long falls back to the city-filter; the city filter with no locations falls back to the country filter).-Every branch below is the same five mapBadge statements with only the filter-fragment changed; the `summary` statement's WHERE tail is shown.--### country (`detailScope: "country"`)--**IDENTICAL**; rows V1/V2 = 1/1.--```sql--- V1-AND coalesce(country, '') IN ('MX', 'O\'')---- V2-AND coalesce(country, '') IN {p3:Array(String)}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": ["MX", "O'"]}-```--### country, 7-character value (`detailScope: "country"`)--**IDENTICAL ERROR**; rows V1/V2 = None/None. Both sides fail with `Too large string for FixedString column.`--```sql--- V1-AND coalesce(country, '') IN ('MX', 'O\'Brien')---- V2-AND coalesce(country, '') IN {p3:Array(String)}--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": ["MX", "O'Brien"]}-```--### city (`detailScope: "city"`)--**IDENTICAL**; rows V1/V2 = 1/1.--```sql--- V1-AND (coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'O\'Brien'))---- V2-AND (coalesce(country, ''), coalesce(city, '')) IN (({p3:String}, {p4:String}), ({p5:String}, {p6:String}))--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "MX", "p4": "Iztapalapa", "p5": "MX", "p6": "O'Brien"}-```--### merged (`detailScope: "merged"`)--**IDENTICAL**; rows V1/V2 = 1/1.--```sql--- V1-AND (coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'Mexico City'))---- V2-AND (coalesce(country, ''), coalesce(city, '')) IN (({p3:String}, {p4:String}), ({p5:String}, {p6:String}))--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "MX", "p4": "Iztapalapa", "p5": "MX", "p6": "Mexico City"}-```--### coordinate (`detailScope: "coordinate"`)--**IDENTICAL**; rows V1/V2 = 1/1.--```sql--- V1-AND (coalesce(country, ''), coalesce(city, ''), toDecimal64(longitude, 4), toDecimal64(latitude, 4)) IN (('MX', 'Iztapalapa', toDecimal64(-99.0539, 4), toDecimal64(19.3474, 4)), ('MX', '', toDecimal64(-99.0111, 4), toDecimal64(19.4371, 4)))---- V2-AND (coalesce(country, ''), coalesce(city, ''), toDecimal64(longitude, 4), toDecimal64(latitude, 4)) IN (({p3:String}, {p4:String}, toDecimal64({p5:String}, 4), toDecimal64({p6:String}, 4)), ({p7:String}, {p8:String}, toDecimal64({p9:String}, 4), toDecimal64({p10:String}, 4)))--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "MX", "p4": "Iztapalapa", "p5": "-99.0539", "p6": "19.3474", "p7": "MX", "p8": "", "p9": "-99.0111", "p10": "19.4371"}-```--### coordinate with no lat/long -> city fallback--**IDENTICAL**; rows V1/V2 = 1/1.--```sql--- V1-AND (coalesce(country, ''), coalesce(city, '')) IN (('MX', 'Iztapalapa'), ('MX', 'Mexico City'))---- V2-AND (coalesce(country, ''), coalesce(city, '')) IN (({p3:String}, {p4:String}), ({p5:String}, {p6:String}))--- V2 params: {"p1": "pincali-production", "p2": "2026-08-25 08:19:53", "p3": "MX", "p4": "Iztapalapa", "p5": "MX", "p6": "Mexico City"}-```--## All 70 pairs--| run | statement | verdict | rows V1/V2 | rows_read V1/V2 | ms V1/V2 | session_timezone V1 → V2 |-|---|---|---|---|---|---|---|-| R1 country | coordinates | IDENTICAL | 440/440 | 8192/8192 | 28/9 | — → — |-| R1 country | summary | IDENTICAL | 1/1 | 30440/30440 | 9/8 | UTC → UTC |-| R1 country | topReferrers | IDENTICAL | 3/3 | 30440/30440 | 10/8 | UTC → UTC |-| R1 country | topPaths | IDENTICAL | 3/3 | 30440/30440 | 9/13 | UTC → UTC |-| R1 country | topEvents | IDENTICAL | 3/3 | 30440/30440 | 15/10 | UTC → UTC |-| R1 country | recentSessions | IDENTICAL | 8/8 | 30440/30440 | 14/16 | — → — |-| R1 country | activeSessions | IDENTICAL | 50/50 | 16384/16384 | 16/18 | — → — |-| R1 country | paths | IDENTICAL | 50/50 | 8192/8192 | 15/17 | UTC → UTC |-| R1 country | referrals | IDENTICAL | 10/10 | 8192/8192 | 9/7 | UTC → UTC |-| R1 country | geo | IDENTICAL | 50/50 | 8192/8192 | 7/10 | UTC → UTC |-| R2 country, 7-char value | coordinates | IDENTICAL | 440/440 | 8192/8192 | 37/9 | — → — |-| R2 country, 7-char value | summary | IDENTICAL ERROR | error/error | — | 4/4 | UTC → UTC |-| R2 country, 7-char value | topReferrers | IDENTICAL ERROR | error/error | — | 3/4 | UTC → UTC |-| R2 country, 7-char value | topPaths | IDENTICAL ERROR | error/error | — | 3/3 | UTC → UTC |-| R2 country, 7-char value | topEvents | IDENTICAL ERROR | error/error | — | 3/3 | UTC → UTC |-| R2 country, 7-char value | recentSessions | IDENTICAL ERROR | error/error | — | 4/4 | — → — |-| R2 country, 7-char value | activeSessions | IDENTICAL | 50/50 | 16384/16384 | 11/21 | — → — |-| R2 country, 7-char value | paths | IDENTICAL | 50/50 | 8192/8192 | 15/10 | UTC → UTC |-| R2 country, 7-char value | referrals | IDENTICAL | 10/10 | 8192/8192 | 9/12 | UTC → UTC |-| R2 country, 7-char value | geo | IDENTICAL | 50/50 | 8192/8192 | 9/10 | UTC → UTC |-| R3 city | coordinates | IDENTICAL | 440/440 | 8192/8192 | 37/11 | — → — |-| R3 city | summary | IDENTICAL | 1/1 | 30440/8192 | 14/8 | UTC → UTC |-| R3 city | topReferrers | IDENTICAL | 3/3 | 30440/8192 | 9/11 | UTC → UTC |-| R3 city | topPaths | IDENTICAL | 3/3 | 30440/8192 | 15/16 | UTC → UTC |-| R3 city | topEvents | IDENTICAL | 3/3 | 30440/30440 | 11/13 | UTC → UTC |-| R3 city | recentSessions | IDENTICAL | 8/8 | 30440/8192 | 13/10 | — → — |-| R3 city | activeSessions | IDENTICAL | 50/50 | 16384/16384 | 11/20 | — → — |-| R3 city | paths | IDENTICAL | 50/50 | 8192/8192 | 11/11 | UTC → UTC |-| R3 city | referrals | IDENTICAL | 10/10 | 8192/8192 | 15/10 | UTC → UTC |-| R3 city | geo | IDENTICAL | 50/50 | 8192/8192 | 8/8 | UTC → UTC |-| R4 merged | coordinates | IDENTICAL | 440/440 | 8192/8192 | 36/11 | — → — |-| R4 merged | summary | IDENTICAL | 1/1 | 30440/8192 | 13/9 | UTC → UTC |-| R4 merged | topReferrers | IDENTICAL | 3/3 | 30440/8192 | 9/8 | UTC → UTC |-| R4 merged | topPaths | IDENTICAL | 3/3 | 30440/8192 | 12/14 | UTC → UTC |-| R4 merged | topEvents | IDENTICAL | 3/3 | 30440/30440 | 23/18 | UTC → UTC |-| R4 merged | recentSessions | IDENTICAL | 8/8 | 30440/8192 | 21/14 | — → — |-| R4 merged | activeSessions | IDENTICAL | 50/50 | 16384/16384 | 11/9 | — → — |-| R4 merged | paths | IDENTICAL | 50/50 | 8192/8192 | 9/11 | UTC → UTC |-| R4 merged | referrals | IDENTICAL | 10/10 | 8192/8192 | 8/11 | UTC → UTC |-| R4 merged | geo | IDENTICAL | 50/50 | 8192/8192 | 11/9 | UTC → UTC |-| R5 coordinate | coordinates | IDENTICAL | 440/440 | 8192/8192 | 35/10 | — → — |-| R5 coordinate | summary | IDENTICAL | 1/1 | 30440/8192 | 16/10 | UTC → UTC |-| R5 coordinate | topReferrers | IDENTICAL | 3/3 | 30440/8192 | 14/15 | UTC → UTC |-| R5 coordinate | topPaths | IDENTICAL | 3/3 | 30440/8192 | 23/12 | UTC → UTC |-| R5 coordinate | topEvents | IDENTICAL | 3/3 | 30440/30440 | 18/15 | UTC → UTC |-| R5 coordinate | recentSessions | IDENTICAL | 8/8 | 30440/8192 | 13/11 | — → — |-| R5 coordinate | activeSessions | IDENTICAL | 50/50 | 16384/16384 | 20/18 | — → — |-| R5 coordinate | paths | IDENTICAL | 50/50 | 8192/8192 | 14/15 | UTC → UTC |-| R5 coordinate | referrals | IDENTICAL | 10/10 | 8192/8192 | 13/13 | UTC → UTC |-| R5 coordinate | geo | IDENTICAL | 50/50 | 8192/8192 | 8/8 | UTC → UTC |-| R6 coordinate -> city fallback | coordinates | IDENTICAL | 440/440 | 8192/8192 | 28/9 | — → — |-| R6 coordinate -> city fallback | summary | IDENTICAL | 1/1 | 8192/8192 | 9/8 | UTC → UTC |-| R6 coordinate -> city fallback | topReferrers | IDENTICAL | 3/3 | 8192/8192 | 8/9 | UTC → UTC |-| R6 coordinate -> city fallback | topPaths | IDENTICAL | 3/3 | 8192/8192 | 9/13 | UTC → UTC |-| R6 coordinate -> city fallback | topEvents | IDENTICAL | 3/3 | 8192/8192 | 12/22 | UTC → UTC |-| R6 coordinate -> city fallback | recentSessions | IDENTICAL | 8/8 | 8192/8192 | 17/15 | — → — |-| R6 coordinate -> city fallback | activeSessions | IDENTICAL | 50/50 | 16384/16384 | 16/13 | — → — |-| R6 coordinate -> city fallback | paths | IDENTICAL | 50/50 | 8192/8192 | 9/8 | UTC → UTC |-| R6 coordinate -> city fallback | referrals | IDENTICAL | 10/10 | 8192/8192 | 8/11 | UTC → UTC |-| R6 coordinate -> city fallback | geo | IDENTICAL | 50/50 | 8192/8192 | 8/10 | UTC → UTC |-| R7 as rendered, real now() | coordinates | IDENTICAL | 0/0 | 193/193 | 30/8 | — → — |-| R7 as rendered, real now() | summary | IDENTICAL | 1/1 | 30440/30440 | 16/14 | UTC → UTC |-| R7 as rendered, real now() | topReferrers | IDENTICAL | 3/3 | 30440/30440 | 11/12 | UTC → UTC |-| R7 as rendered, real now() | topPaths | IDENTICAL | 3/3 | 30440/30440 | 23/20 | UTC → UTC |-| R7 as rendered, real now() | topEvents | IDENTICAL | 3/3 | 30440/30440 | 11/16 | UTC → UTC |-| R7 as rendered, real now() | recentSessions | IDENTICAL | 8/8 | 30440/30440 | 17/18 | — → — |-| R7 as rendered, real now() | activeSessions | IDENTICAL | 50/50 | 16384/16384 | 19/17 | — → — |-| R7 as rendered, real now() | paths | IDENTICAL | 50/50 | 8192/8192 | 14/11 | UTC → UTC |-| R7 as rendered, real now() | referrals | IDENTICAL | 10/10 | 8192/8192 | 15/15 | UTC → UTC |-| R7 as rendered, real now() | geo | IDENTICAL | 50/50 | 8192/8192 | 11/13 | UTC → UTC |--`rows_read` differing between the two sides on some pairs (e.g. R3 `summary`,-30440 V1 / 8192 V2) is ClickHouse's index analysis treating a bound-`{p:String}` differently from an inline literal on the `created_at` range — a-performance note, not a semantic one, and the returned `data` is byte-identical.--**Verdict: 70 cases, all IDENTICAL** (5 of them IDENTICAL ERROR — V1's-FixedString(2) overflow, reproduced byte-for-byte and not fixed here).diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.tsindex 05d9d517b..76912de3d 100644--- a/packages/core/src/modules/session/session.service.ts+++ b/packages/core/src/modules/session/session.service.ts@@ -1,21 +1,11 @@-// Ported from packages/db/src/services/session.service.ts (M7-001); that file-// and its re-export shim are gone (M9-CLEANUP-001), so this is the only-// session read path.+// The session read path. Every query is a `sql` fragment (src/sql.ts), per+// ADR-013; `buildFilterWhere` is the shared filter compiler and+// src/filter-clauses.ts is the bridge to it.//-// Every query here is a `sql` fragment (src/sql.ts) — the module's-// queries are converted, one at a time with a result-set proof each, per-// ADR-013. `buildFilterWhere` is NOT converted here: it is the shared filter-// compiler, out of this task's scope; src/filter-clauses.ts is the one bridge.-//-// M10-009: the ClickHouse client is `deps.ch`, reached through core's own-// `chQuery` (ch-query.ts), so the requestId minted at the edge reaches-// every query here (ADR-018, docs/TECH_DEBT.md §4). `getSessionsCountCached`-// is `cacheablePerDeps` (M15-004): `cacheable` keys on the call's ARGUMENTS-// (packages/redis/cachable.ts), so the caller's deps travel beside the key-// rather than inside it, and the Redis key stays byte-identical. The one-// remaining `load*` function is an intra-package lazy import, kept lazy for a-// cycle, not for a client — the date helpers left that set in M15-010, because-// @openpanel/shared sits below this package and cannot cycle back into it.+// `getSessionsCountCached` is `cacheablePerDeps`: `cacheable` keys on the+// call's ARGUMENTS (packages/redis/cachable.ts), so the caller's deps have to+// travel beside the key rather than inside it, or the Redis key would change+// per request.import { getSafeJson, resolveDateRange } from '@openpanel/shared';import { cacheablePerDeps } from '../../cacheable-per-deps';diff --git a/packages/core/src/modules/session/src/sql.proof.md b/packages/core/src/modules/session/src/sql.proof.mddeleted file mode 100644index 5c4445641..000000000--- a/packages/core/src/modules/session/src/sql.proof.md+++ /dev/null@@ -1,200 +0,0 @@-# session/src/sql.ts — `sessionByIdQuery` PREWHERE proof (M39-001)--`sessionByIdQuery` keeps `FINAL`. It now reads-`FROM sessions FINAL PREWHERE id = … AND project_id = … WHERE sign = 1`; before, all three-conditions were in `WHERE`. This is rank 1 of `docs/FINAL_USAGE.md` §7 (M38-002).--**Why it helps.** On this server `optimize_move_to_prewhere_if_final = 0`, and `FINAL` widens the-`idx_id` bloom-filter hit (`use_skip_indexes_if_final_exact_mode = 1`). With `FINAL`, every column-was read for every widened granule. `EXPLAIN indexes=1` is the same for both spellings: bayse-`idx_id` Parts 2/9, Granules 4/101, then `FINAL` widens this to Parts 9/2, Granules 173/4. The-statements differ only in which columns are read for those granules. `EXPLAIN actions=1` on the-new statement shows `Prewhere filter column: and(equals(id, …), equals(project_id, …))`, and the-outer `Filter column: equals(__table1.sign, 1_UInt8)`.--**Why it is safe.** `project_id` is a sort-key column. `id` is not, but a −1 row is a full copy-of its +1 (`buffers/session-buffer.ts`), so both rows of a pair pass the PREWHERE and still-collapse. **`sign` stays in `WHERE`.** A PREWHERE on `sign` drops the −1 before the collapse, so-the stale +1 survives (control below).--## Setup--- **When and where:** 2026-09-16, 21:30–21:34 UTC, on the local prod-copy ClickHouse- (`127.0.0.1:8123`, database `openpanel`), with load average 2.9–3.9.-- **Access:** SELECT and EXPLAIN only. `openpanel.events` read 321,192,117 rows.-- **Request settings:** every request used `use_query_cache=0`, `use_query_condition_cache=0` and- `wait_end_of_query=1`. Ids were bound as `{p1:String}`/`{p2:String}`, exactly as the builder- renders them.-- **Where the numbers come from:** `read_rows`, `read_bytes`, `elapsed_ns` and `memory_usage` are- read off `X-ClickHouse-Summary`, from `FORMAT Null` runs. `memory_usage` is the summary figure,- not a sampled peak.-- **Caching:** page cache was not controlled, so **every number is warm**.--## Result-set equality--Each check runs `SELECT count(), sum(h), cityHash64(groupArray(h)) FROM (SELECT-sipHash64(formatRow('TSV', *)) h FROM (<statement>))`. `sum(h)` is the order-independent-result-set hash.--| project | ids checked | old = new |-|---|---|--:|-| verdict | top 3 by row count + 5 `cityHash64(id,'m39')` samples | 8/8 |-| bayse | same | 8/8 |-| earlysalary-production | same | 8/8 |-| chatpaper | same | 8/8 |-| e2e-sessions | same (top id: 4 rows) | 8/8 |-| bayse | the id that reads the most (1,613,380 rows; M38-002's case) | 1/1 (2 rows) |-| website-8103 | no `sessions` rows on this box; unknown id | 0 rows = 0 rows |-| **e2e-sessions, unmerged** | **every id with a −1 row (21 ids, 21 −1 rows)** | **21/21** |-| e2e-sessions | 50 sampled ids with >1 `version` | 50/50 |--Controls on the 21 unmerged ids, which show that this probe can detect a wrong answer:-- **No `FINAL`** differs on **21/21**: 2 rows instead of 1, because the stale +1 is returned.-- **`FINAL PREWHERE id, project_id, sign = 1`** also differs on **21/21**, with the same hashes as- no `FINAL`.--## Cost--Each variant was run 4 times on each project's top id (ordered by row count, then by id). The-bayse row uses the widest id instead. Each cell shows `read_rows`, then MiB read, the four run-times in ms, and `memory_usage` in MiB.--| project | old (`FINAL WHERE`) | new (`FINAL PREWHERE`) |-|---|---|---|-| **bayse (widest id)** | 1,613,380 · 364 MiB · **858/808/820/819 ms** · 432–475 MiB | 1,613,380 · 39 MiB · **35/32/42/28 ms** · 26 MiB |-| bayse (top id) | 90,109 · 21 · 87/106/81/88 · 66–70 | 90,109 · 4 · 17/16/15/16 · 17 |-| chatpaper | 5,913,071 · 1,308 · 3124/2912/2900/3072 · 438–450 | 5,913,071 · 148 · 75/55/55/56 · 34–38 |-| verdict | 146,882 · 28 · 99/113/114/104 · 82–94 | 146,882 · 4 · 17/20/26/20 · 17 |-| earlysalary-production | 545,014 · 149 · 314/308/339/328 · 265–299 | 545,014 · 15 · 28/25/28/26 · 25 |-| e2e-sessions | 141,898 · 35 · 108/96/96/99 · 96–120 | 141,898 · 5 · 16/17/18/16 · 17 |--M38-002 measured bayse at 846–994 ms → 32–36 ms and 363 → 38 MiB. This run reproduces those-figures: 808–858 ms → 28–42 ms and 364 → 39 MiB. `read_rows` does not change, because `FINAL`-still widens the ranges. Only the `id`/key columns are read for rows that the PREWHERE rejects.--# session/src/sql.ts — `sessionListQuery` without `FINAL` (M39-004)--`sessionListQuery` no longer reads `sessions FINAL`. It keeps `+1` rows only, and drops any row-whose `(id, version)` has a `−1` in the same window:--```sql-FROM sessions-LEFT JOIN (SELECT DISTINCT session_id FROM session_replay_chunks …) AS src ON src.session_id = id-WHERE project_id = … <lookback / cursor / calendar-day window>- AND sign = 1- AND (id, version) GLOBAL NOT IN (- SELECT id, version FROM sessions- WHERE project_id = … <the same window> AND sign = -1- )- <profile_id / search / compiled filters, unchanged>-ORDER BY created_at DESC-LIMIT …-```--This is rank 2 of `docs/FINAL_USAGE.md` §7 (M38-002).--**Why the subquery only repeats the window.** A `−1` is a full copy of its `+1`-(`buffers/session-buffer.ts`), so the two rows share `created_at` and fall in the same window.-The profile, search and filter predicates are applied to the `+1` in the outer query, so repeating-them in the subquery would not change the result.--**Cluster.** `sessions` and `session_replay_chunks` are `Distributed` on Cloud. `GLOBAL NOT IN`-builds the `−1` set once, on the initiator, and ships it to the shards. It is correct under any-`distributed_product_mode`. A plain `NOT IN` under the client's `'allow'` would run the subquery-against the Distributed table from every shard, which is also correct but costs N× more. It is-correct only because a `−1` and its `+1` share `created_at`, and so they share a shard: the shard-key is `cityHash64(project_id, toStartOfHour(created_at))`. On this single node the two spellings-cost the same (see the table below). Neither the replay `LEFT JOIN` nor its-`distributed_product_mode` behaviour changed.--## Setup--- **When and where:** 2026-09-16, 22:23–22:26 UTC, on the local prod-copy ClickHouse- (`127.0.0.1:8123`, database `openpanel`, **single-node**). Load average was 0.1–1.2 at the start.-- **Access:** SELECT only.-- **How the statements were built:** both statements were rendered by the real builders, the- HEAD `sql.ts` and the new one, with bound `{pN:Type}` params. The requests used the client's- settings (`distributed_product_mode=allow`, `query_plan_convert_any_join_to_semi_or_anti_join=0`),- plus `wait_end_of_query=1`, `use_query_cache=0` and `use_query_condition_cache=0`.-- **Where the numbers come from:** `read_rows`, `read_bytes`, `elapsed_ns` and `memory_usage` are- read off `X-ClickHouse-Summary`, from `FORMAT Null` runs. `memory_usage` is the summary figure,- not a sampled peak.-- **Caching:** page cache was not controlled, so **every number is warm**.-- **The replay join on this box:** `session_replay_chunks` holds 250 rows, all of them in- `e2e-sessions`. For every real anchor, the join's right-hand side is therefore **empty**. The- "all-replay" rows below replace it with *every* chatpaper session id, to bound the opposite- case.--## Result-set equality--Each check runs `SELECT count(), sum(h), cityHash64(groupArray(h)) FROM (SELECT-sipHash64(formatRow('TSV', *)) h FROM (<statement>))`. The value compared is `(count, sum(h))`.-"FULL" means `take = 1e8`, so the whole window is returned. The top-N cases were also re-checked-with `ORDER BY created_at DESC, id`. The "control" column is the plain drop (`sign = 1`, no-anti-join); it shows whether a case can detect a wrong answer at all.--| project | cases (each: old = new?) | control = old? |-|---|---|---|-| chatpaper, verdict, bayse, earlysalary-production, website-8103 | cursor page (2026-08-30 12:00, 30 d) top 50 and FULL; first page anchored at now (30 d) top 50; date range 2026-08-01 → 08-15 top 50; cursor page + `search='a'` + filter `device='desktop'` top 50. **25/25 equal, plus 20/20 with the `id` tie-break.** (website-8103 has no sessions: 0 = 0. verdict search+filter: 0 = 0.) | equal everywhere, because the anchors hold no `−1` rows (§3 of FINAL_USAGE) |-| chatpaper, all-replay join | cursor page top 50: **equal** | — |-| **e2e-sessions (unmerged, 21 `−1` rows)** | cursor 2026-09-05 02:22:46 with 1 d lookback, top 50 and **top 500**; cursor 2026-09-15 23:59:59 with 30 d lookback, top 50 and **FULL** (647,079 rows); first page at now, **FULL**; date range September, **FULL**. **6/6 equal, plus 3/3 with the tie-break.** | **differs on top 500 and on all three FULL sets** (647,100 rows: the 21 stale `+1`) |--Mismatches between old and new: **0**.--## Cost: the whole statement, replay join included--Each cell shows `read_rows`, then MiB read, three runs in ms, and `memory_usage` in MiB. All pages-are cursor pages (2026-08-30 12:00, 30 d, top 50) unless the row says otherwise.--| project | old: `FINAL` + join | **new: anti-join + join** | new, local `NOT IN` | old, no join | new, no join | plain drop + join (unsafe) |-|---|---|---|---|---|---|---|-| chatpaper | 3,816,602 · 637 · **1147/1138/1124** · 210–241 | 7,289,150 · 586 · **453/473/473** · 73–81 | 464/485/455 | 1111/1148/1134 | 7,297,342 · 212 · 154/156/149 · 4 | 3,644,575 · 555 · 417/379/386 |-| chatpaper, range Aug 1–15 | 1,924,894 · 319 · **581/560/562** · 146–150 | 3,751,502 · 311 · **245/262/253** · 69–73 | 261/265/251 | 552/555/545 | 113 MiB · 88/87/94 | 212/204/209 |-| chatpaper, search + filter | 637 MiB · **1261/1240/1238** · 209–223 | 588 MiB · **561/577/579** · 77–82 | 590/571/583 | 1237/1212/1207 | 372 MiB · 351/330/344 | 485/510/490 |-| chatpaper, **all-replay join** | 9,844,399 · 896 · **2094/2550/2928** · 2208–2959 | 13,316,947 · 845 · **1933/1887/1644** · 2409–2806 | — | — | — | — |-| verdict | 1,006,503 · 121 · **292/304/299** · 174–186 | 1,673,436 · 83 · **96/98/98** · 61 | 95/89/86 | 279/281/296 | 44 MiB · 58/44/48 | 71/65/69 |-| bayse | 712,572 · 112 · **218/258/224** · 179–192 | 1,081,090 · 61 · **67/65/66** · 52–57 | 73/83/92 | 246/228/208 | 25 MiB · 34/30/31 | 52/47/50 |-| earlysalary-production | 745,388 · 163 · **246/255/278** · 207–246 | 1,146,732 · 96 · **97/76/75** · 65 | 83/85/95 | 251/245/254 | 34 MiB · 51/34/43 | 76/68/73 |-| website-8103 (0 sessions) | 55,634 · 11 · 57/54/46 | 111,268 · 3 · 19/23/15 | 16/16/16 | 42/41/41 | 16/15/16 | 10/11/11 |-| e2e-sessions, 1 d top 50 | 102,622 · 15 · 36/31/29 | 178,444 · 6 · 24/35/39 | 45/24/27 | 25/25/24 | 15/14/17 | 27/19/26 |-| e2e-sessions, FULL (647,079 rows) | 738,931 · 125 · 259/233/233 · 321–331 | 1,360,036 · 111 · 142/133/117 · 261–276 | 132/141/128 | 231/218/218 | 111/120/124 | 121/115/100 |--**The replay join changes the picture.** Without the join, this run reproduces M38-002:-chatpaper 1,111–1,148 → 149–156 ms, and 637 → 212 MiB. **With the join, the new statement costs-453–473 ms and reads 586 MiB.** The `LEFT JOIN` blocks the read-in-order / lazy-materialisation-top-N path, even with an empty right-hand side, so all 21 columns are read for the whole window-again. The plain (unsafe) drop is capped the same way (379–417 ms). The change is still worth-shipping:-- 2.4× on chatpaper, 3× on verdict, bayse and earlysalary, and 2.2× on ranges and search.-- `memory_usage` falls 2.5–3.5× (210–241 → 73–81 MiB on chatpaper).-- The result is identical, including on unmerged data.--With every session carrying a replay, both statements cost seconds and ≈2.2–3 GiB: old-2.1–2.9 s, new 1.6–1.9 s.--**Not shipped: the headroom.** A join-after-`LIMIT` form of the new statement returned the same-`(count, sum(h))`. It selects the top N in a subquery without the join, then `LEFT JOIN`s the-replay set onto those N rows. On chatpaper it ran in **150/147/152 ms and read 212 MiB**, measured-at 22:25 UTC. Moving the join is a further rewrite that M38-002 did not endorse. It is left as a-follow-up.--## Where the anti-join can differ from `FINAL` (FINAL_USAGE §6.2)--1. **One `(id, version)` with two `+1` rows and one `−1`.** `FINAL` collapses one pair and still- shows the stale `+1` next to version V+1. The anti-join hides both copies of version V, until- the merge. After the merge the `−1` is gone and the two forms agree again. **Reachable in- production:** same-`(id, version)` `+1` duplicates exist on real projects on this box- (chatpaper 69, verdict 3, tiptip-main-app-prod 5, …; e2e-sessions 1,043). If such a session is- updated, the buffer writes one `−1`. On this box no `(id, version)` has both a `−1` and two- `+1` rows (0), so this case could not be exercised. The visible effect is transient, only- during the merge window: a stale duplicate row that `FINAL` would show is not shown.-2. **Cross-session cancel.** `FINAL` collapses on the sort key plus the version, and the sort key- has no `id`. A `−1` whose own `+1` is missing could therefore cancel another session's `+1`- with the same `created_at` and version. The anti-join matches on `id` and never does this.- Reachable only if a `+1` is lost while its `−1` is written. That was not observed here (the one- such group cancels cleanly).-3. **Unpaired `−1` rows.** The shipped statement had no `sign` filter, so `FINAL` would return a- `−1` whose `+1` is absent. The new statement returns only `+1`. Reachable under the same- condition as (2). On this box every `−1` has its `+1`: 0 of 21 unpaired.-4. **The `NOT IN` set lives in memory.** It holds the unmerged `−1` backlog of the window: 21 rows- here. On live production its size is unknown (FINAL_USAGE open question 2).diff --git a/packages/core/src/modules/session/src/sql.ts b/packages/core/src/modules/session/src/sql.tsindex 14a549593..a3a13e0b2 100644--- a/packages/core/src/modules/session/src/sql.ts+++ b/packages/core/src/modules/session/src/sql.ts@@ -133,8 +133,8 @@ function sessionListWindow(query: SessionListQuery): SqlFragment {)}`;}-// No `FINAL`: it read every column of the whole window and blocked read-in-order-// (chatpaper 1.1 s → 0.15 s, M38-002 / M39-004, see sql.proof.md). A +1 whose+// No `FINAL`: it reads every column of the whole window and blocks+// read-in-order (measured 1.1 s → 0.15 s on a large project). A +1 whose// `(id, version)` has a −1 is a pending collapse, which `FINAL` would have// removed. Plain `sign = 1` alone returns those stale rows, and `LIMIT 1 BY id`// drops the orphan +1 duplicates `FINAL` keeps. `GLOBAL` builds the −1 set oncediff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.tsindex d157ad822..31125ec73 100644--- a/packages/core/src/modules/widget/widget.rpc.ts+++ b/packages/core/src/modules/widget/widget.rpc.ts@@ -1,36 +1,15 @@-// Ported from packages/trpc/src/routers/widget.ts (M7-006, ADR-008's module-// map: widget is R only — its zod schemas (zWidgetType/zWidgetOptions) are-// chart/report vocabulary owned by ./report/report.constants.ts, so this-// module carries no `widget.constants.ts` of its own).+// Widgets are read-only chart embeds. Their zod schemas (`zWidgetType` /+// `zWidgetOptions`) are chart/report vocabulary and live in+// ./report/report.constants.ts, so this module carries no constants file of+// its own, and there is no widget.service.ts — the queries are small enough to+// stay in the procedures.//-// V1's `protectedProcedure`/`publicProcedure` split lands in core with auth-// (rpc/base.ts), so `get`/`toggle`/`updateOptions` do their own "is anyone-// logged in" check and `counter`/`badge`/`realtimeData` stay open, matching-// V1's split exactly. There is no `widget.service.ts` (same shape as-// email.rpc.ts's "R + C only" module): V1's own router keeps its own-// ClickHouse/Postgres calls rather than delegating to a shared service —-// the one genuinely shared piece is the report module's widget zod schemas.+// `get`/`toggle`/`updateOptions` require a login; `counter`/`badge`/+// `realtimeData` are deliberately open, because a widget is embedded on a+// public page.//-// M10-009: Postgres and ClickHouse come from `ctx` (`ctx.db` / `ctx.ch`), so-// the requestId minted at the edge reaches the query (ADR-018); the `loadDb`/-// `loadChClient` lazy loaders are gone, and M15-202 made `getCache` a plain-// static import too (ADR-022 R6) — the spelling subscription.service.ts,-// modules/ingest/src/client-auth.ts and modules/mcp/src/auth.ts already use.-//-// M12-008: the five ClickHouse statements moved off clix onto the ADR-013-// `sql` tag. The conversion changes how values reach the server and nothing-// else — each statement renders byte-identically to the clix output it-// replaces, with `projectId` bound as a `{pN:String}` param and the two-// `LIMIT`s as `{pN:UInt64}`. The `now() - INTERVAL ...` windows were-// `clix.exp()` raw expressions and stay raw SQL text, parentheses included-// (clix wrapped an Expression comparand in `(...)`, query-builder.ts:134).-// clix sent its constructor timezone as `clickhouse_settings.session_timezone`-// (`:562`); every statement here was built with the project's timezone, so-// `chQuery` is given the same value. The V1-vs-V2 result-set proof is-// `widget.sql.proof.md` beside this file.-//-// `sql` is a value import and stays one: it is a compile-time template tag-// holding no client and no request scope (see ch-query.ts).+// Every statement is built with the project's timezone, so `chQuery` is given+// the same value as `clickhouse_settings.session_timezone`.import { sql } from '@openpanel/db/src/clickhouse/sql';import { getCache } from '@openpanel/redis';diff --git a/packages/core/src/modules/widget/widget.sql.proof.md b/packages/core/src/modules/widget/widget.sql.proof.mddeleted file mode 100644index 3bb2d6993..000000000--- a/packages/core/src/modules/widget/widget.sql.proof.md+++ /dev/null@@ -1,326 +0,0 @@-# widget.rpc.ts — V1 → V2 result-set proof (M12-008)--Every ClickHouse statement `packages/core/src/modules/widget/widget.rpc.ts`-runs — one in `badge`, five in `realtimeData` — executed V1 against V2 on the-local prod-copy `openpanel`. V1 is the file at commit `68fea1a7`-(`git show HEAD:packages/core/src/modules/widget/widget.rpc.ts`), which builds-all six with `clix`; V2 is the converted file, `projectId` and both `LIMIT`s-bound as `{pN:Type}` params.--**Both routers were imported into one Bun process and driven through-`createCaller`** — the real tRPC procedures, `badge({shareId})` and-`realtimeData({shareId})`, over one stubbed `ctx` (a `shareWidget.findUnique`-returning a public widget, a `project.findUniqueOrThrow` giving-`getSettingsForProject` its organisation timezone, and a `deps.ch.query` stub-that captures `{query, query_params, clickhouse_settings}`). `@openpanel/redis`-was replaced so `getCache` runs its producer instead of answering from cache;-nothing else was mocked, and no statement below was retyped by hand. Each-captured statement was then executed through one HTTP call to `127.0.0.1:8123`-at `format: 'JSON'` with the settings its own side asked for; `data` was-compared row-for-row and `meta` column-for-column.--- **Date**: 2026-09-07.-- **Data**: local prod-copy `openpanel`, 319,851,025 events at the time of the- run. Project `pincali-production` (14,047,591 events). Nothing is empty here.-- **Reference time**: five of the six statements window on `now()`, and the- prod copy's application data ends on **2026-08-25 08:49:53**, so the live- 30-minute window is empty by construction. Every statement is therefore run- **twice**: once exactly as rendered, and once with `now()` textually replaced- by `toDateTime('2026-08-25 08:49:53')` **on both sides** — the "(frozen now)"- rows, which are the row-bearing ones (10, 10, 10, 1, 151 rows). The- as-rendered `minuteCounts` still returns 30 rows because its `WITH FILL`- synthesises the empty buckets, and the as-rendered `badge` returns a real- 804,374 because its window is 30 **days**. The four as-rendered zero-row- results are recorded, not counted as evidence.-- **`session_timezone`**: `Europe/Stockholm` on all twelve runs, both sides.- clix carried its constructor timezone into `clickhouse_settings`- (`query-builder.ts:562`) and every statement here was built as- `clix(ch, timezone)` with the project's organisation timezone, so `chQuery`- is handed the same value. The value itself came from the one stubbed- `getSettingsForProject`, shared by both sides — what the comparison needs is- that both sides send the *same* setting, and the capture shows they do.-- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are- directional only; production is 2 shards × 2 replicas- (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either- direction**: `git show HEAD:packages/core/src/modules/widget/widget.rpc.ts |- grep -c GLOBAL` is `0`, `grep -c GLOBAL` on the converted file is `0`, and- neither version emits an `IN` at all — so no `IN (subquery)` on a- `Distributed` table arises here.-- **Verdict**: **12 statement pairs, all IDENTICAL.**--## What binds and what does not--- **`projectId` binds** — `{p1:String}` in all six statements. It is the only- runtime value in the module.-- **`LIMIT 10` binds** — `{p2:UInt64}` on the three top-lists, from the named- `REALTIME_TOP_LIST_LIMIT`.-- **The `now()` windows stay raw SQL text.** V1 passed them as- `clix.exp('now() - INTERVAL 30 MINUTE')`, and clix wrapped an `Expression`- comparand in parentheses (`query-builder.ts:134`), so V2 writes- `created_at >= (now() - INTERVAL 30 MINUTE)` — parentheses included — into the- template. A `SETTINGS`/interval operand cannot be a bound param anyway- (the identifier matrix, `sql.clickhouse.test.ts:241-269`), and there is no- value here to protect.-- **`!= ''` and `IS NOT NULL` stay literal**, as `referrer-spikes.ts` renders- them after its own conversion. `''` is a constant in the source, not input.-- **The `WITH FILL FROM … TO … STEP …` clause** is the same raw text clix built- from three `clix.exp()` arguments (`query-builder.ts:488-491`).-- `clix.toStartOf('created_at','minute')` (`query-builder.ts:719`) is- `toStartOfMinute(created_at)`, written out.--## Tests--There is no test in the tree that touches the widget module — no-`widget*.test.ts` exists, and nothing else references `widgetRouter` except-`rpc.router.ts`. So no text-comparing test needed retargeting here. The router's-shape, its procedure names, its `protectedProcedure`/`publicProcedure` split and-every response field are untouched by this diff.--## Grep gate--```-$ bash tooling/gates/p12-grep-gates.sh --report-```--| | sqlstring | clix | sql-builder |-|---|---|---|---|-| `widget/widget.rpc.ts` before | 0 | 7 | 0 |-| `widget/widget.rpc.ts` after | **absent from the report (0/0/0)** | | |-| TOTAL before | 16 | 21 | 1 |-| TOTAL after | **16** | **1** | **1** |--The leftovers under `packages/core` are enumerated in-`insight/src/legacy-scan.sql.proof.md` § *still non-zero*; the last `clix` and-`sql-builder` lines in the tree are both `packages/db/index.ts`'s re-exports of-the definer files.--## Reading the case blocks, and reproducing them--`rows V1:` / `rows V2:` are the **first 300 characters** of each side's JSON-`data`, as an eyeball check. The comparison itself was made on the full arrays:-`JSON.stringify(v1.data) === JSON.stringify(v2.data)` and the same on `meta`,-which is what the `IDENTICAL` verdict on each block reports.--Either side of any block is reproducible with one `curl`. V1 goes as the body;-V2 goes as the body with its params as `param_pN`:--```bash-curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=<tz>&default_format=JSON' \- --data-binary '<the -- V1 statement>'--curl -s -G 'http://127.0.0.1:8123/' \- --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=<tz>' \- --data-urlencode 'default_format=JSON' \- --data-urlencode 'param_p1=<value>' [--data-urlencode 'param_p2=<value>' ...] \- --data-urlencode 'query=<the -- V2 statement>'-```--An `Array(String)` param is written in ClickHouse's own form, not JSON —-`param_p4=['Google','Bing']` — which is how the harness encoded it.--## Cases--### widget/badge/uniqueVisitors--_as rendered — window is now(), the prod copy ends 2026-08-25_--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 8115324/8115324; wall V1/V2 = 193 ms / 195 ms; `meta` V1/V2 = identical `[{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT uniq(profile_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (now() - INTERVAL 30 DAY)--- V2-SELECT uniq(profile_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (now() - INTERVAL 30 DAY)--- V2 params: {"p1":"pincali-production"}-```--rows V1: `[{"count":804374}]`-rows V2: `[{"count":804374}]`--### widget/badge/uniqueVisitors (frozen now)--_now() -> toDateTime('2026-08-25 08:49:53') on both sides_--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 14187522/14187522; wall V1/V2 = 324 ms / 328 ms; `meta` V1/V2 = identical `[{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT uniq(profile_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 DAY)--- V2-SELECT uniq(profile_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 DAY)--- V2 params: {"p1":"pincali-production"}-```--rows V1: `[{"count":1569024}]`-rows V2: `[{"count":1569024}]`--### widget/realtimeData/countries--_as rendered — window is now(), the prod copy ends 2026-08-25_--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 156/156; wall V1/V2 = 5 ms / 4 ms; `meta` V1/V2 = identical `[{"name":"country","type":"LowCardinality(FixedString(2))"},{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT country, uniq(session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (now() - INTERVAL 30 MINUTE) AND country != '' AND country IS NOT NULL GROUP BY country ORDER BY count DESC LIMIT 10--- V2-SELECT country, uniq(session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (now() - INTERVAL 30 MINUTE) AND country != '' AND country IS NOT NULL GROUP BY country ORDER BY count DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"pincali-production","p2":10}-```--rows V1: `[]`-rows V2: `[]`--### widget/realtimeData/countries (frozen now)--_now() -> toDateTime('2026-08-25 08:49:53') on both sides_--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 73541/73541; wall V1/V2 = 6 ms / 7 ms; `meta` V1/V2 = identical `[{"name":"country","type":"LowCardinality(FixedString(2))"},{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT country, uniq(session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) AND country != '' AND country IS NOT NULL GROUP BY country ORDER BY count DESC LIMIT 10--- V2-SELECT country, uniq(session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) AND country != '' AND country IS NOT NULL GROUP BY country ORDER BY count DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"pincali-production","p2":10}-```--rows V1: `[{"country":"MX","count":1049},{"country":"US","count":397},{"country":"IN","count":346},{"country":"VN","count":202},{"country":"MY","count":88},{"country":"JP","count":87},{"country":"TH","count":87},{"country":"BR","count":81},{"country":"ID","count":81},{"country":"CA","count":79}]`-rows V2: `[{"country":"MX","count":1049},{"country":"US","count":397},{"country":"IN","count":346},{"country":"VN","count":202},{"country":"MY","count":88},{"country":"JP","count":87},{"country":"TH","count":87},{"country":"BR","count":81},{"country":"ID","count":81},{"country":"CA","count":79}]`--### widget/realtimeData/referrers--_as rendered — window is now(), the prod copy ends 2026-08-25_--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 156/156; wall V1/V2 = 5 ms / 6 ms; `meta` V1/V2 = identical `[{"name":"referrer","type":"String"},{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT referrer_name as referrer, uniq(session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (now() - INTERVAL 30 MINUTE) AND referrer_name != '' AND referrer_name IS NOT NULL GROUP BY referrer_name ORDER BY count DESC LIMIT 10--- V2-SELECT referrer_name as referrer, uniq(session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (now() - INTERVAL 30 MINUTE) AND referrer_name != '' AND referrer_name IS NOT NULL GROUP BY referrer_name ORDER BY count DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"pincali-production","p2":10}-```--rows V1: `[]`-rows V2: `[]`--### widget/realtimeData/referrers (frozen now)--_now() -> toDateTime('2026-08-25 08:49:53') on both sides_--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 65349/65349; wall V1/V2 = 11 ms / 9 ms; `meta` V1/V2 = identical `[{"name":"referrer","type":"String"},{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT referrer_name as referrer, uniq(session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) AND referrer_name != '' AND referrer_name IS NOT NULL GROUP BY referrer_name ORDER BY count DESC LIMIT 10--- V2-SELECT referrer_name as referrer, uniq(session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) AND referrer_name != '' AND referrer_name IS NOT NULL GROUP BY referrer_name ORDER BY count DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"pincali-production","p2":10}-```--rows V1: `[{"referrer":"Google","count":351},{"referrer":"easybroker.com","count":100},{"referrer":"ChatGPT","count":85},{"referrer":"transactional","count":17},{"referrer":"Instagram","count":9},{"referrer":"ig","count":6},{"referrer":"Facebook","count":4},{"referrer":"https://monopolio.com.mx","count":3},{"`-rows V2: `[{"referrer":"Google","count":351},{"referrer":"easybroker.com","count":100},{"referrer":"ChatGPT","count":85},{"referrer":"transactional","count":17},{"referrer":"Instagram","count":9},{"referrer":"ig","count":6},{"referrer":"Facebook","count":4},{"referrer":"https://monopolio.com.mx","count":3},{"`--### widget/realtimeData/paths--_as rendered — window is now(), the prod copy ends 2026-08-25_--**statement** — IDENTICAL; rows V1/V2 = 0/0; rows_read V1/V2 = 156/156; wall V1/V2 = 5 ms / 7 ms; `meta` V1/V2 = identical `[{"name":"path","type":"String"},{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT path, uniq(session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (now() - INTERVAL 30 MINUTE) AND path != '' AND path IS NOT NULL GROUP BY path ORDER BY count DESC LIMIT 10--- V2-SELECT path, uniq(session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (now() - INTERVAL 30 MINUTE) AND path != '' AND path IS NOT NULL GROUP BY path ORDER BY count DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"pincali-production","p2":10}-```--rows V1: `[]`-rows V2: `[]`--### widget/realtimeData/paths (frozen now)--_now() -> toDateTime('2026-08-25 08:49:53') on both sides_--**statement** — IDENTICAL; rows V1/V2 = 10/10; rows_read V1/V2 = 65349/65349; wall V1/V2 = 10 ms / 11 ms; `meta` V1/V2 = identical `[{"name":"path","type":"String"},{"name":"count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT path, uniq(session_id) as count FROM events WHERE project_id = 'pincali-production' AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) AND path != '' AND path IS NOT NULL GROUP BY path ORDER BY count DESC LIMIT 10--- V2-SELECT path, uniq(session_id) as count FROM events WHERE project_id = {p1:String} AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) AND path != '' AND path IS NOT NULL GROUP BY path ORDER BY count DESC LIMIT {p2:UInt64}--- V2 params: {"p1":"pincali-production","p2":10}-```--rows V1: `[{"path":"/","count":123},{"path":"/inmuebles/departamentos-en-renta","count":37},{"path":"/inmuebles/casas-en-renta-en-zapopan-jalisco","count":23},{"path":"/inmuebles/departamentos-en-renta-en-guadalajara-jalisco","count":22},{"path":"/inmuebles/departamentos-en-renta-en-coyoacan-ciudad-de-mexico"`-rows V2: `[{"path":"/","count":123},{"path":"/inmuebles/departamentos-en-renta","count":37},{"path":"/inmuebles/casas-en-renta-en-zapopan-jalisco","count":23},{"path":"/inmuebles/departamentos-en-renta-en-guadalajara-jalisco","count":22},{"path":"/inmuebles/departamentos-en-renta-en-coyoacan-ciudad-de-mexico"`--### widget/realtimeData/totalSessions--_as rendered — window is now(), the prod copy ends 2026-08-25_--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 156/156; wall V1/V2 = 5 ms / 4 ms; `meta` V1/V2 = identical `[{"name":"total_sessions","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT uniq(session_id) as total_sessions FROM events WHERE project_id = 'pincali-production' AND created_at >= (now() - INTERVAL 30 MINUTE)--- V2-SELECT uniq(session_id) as total_sessions FROM events WHERE project_id = {p1:String} AND created_at >= (now() - INTERVAL 30 MINUTE)--- V2 params: {"p1":"pincali-production"}-```--rows V1: `[{"total_sessions":0}]`-rows V2: `[{"total_sessions":0}]`--### widget/realtimeData/totalSessions (frozen now)--_now() -> toDateTime('2026-08-25 08:49:53') on both sides_--**statement** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 65349/65349; wall V1/V2 = 8 ms / 8 ms; `meta` V1/V2 = identical `[{"name":"total_sessions","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT uniq(session_id) as total_sessions FROM events WHERE project_id = 'pincali-production' AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE)--- V2-SELECT uniq(session_id) as total_sessions FROM events WHERE project_id = {p1:String} AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE)--- V2 params: {"p1":"pincali-production"}-```--rows V1: `[{"total_sessions":3686}]`-rows V2: `[{"total_sessions":3686}]`--### widget/realtimeData/minuteCounts--_as rendered — window is now(), the prod copy ends 2026-08-25_--**statement** — IDENTICAL; rows V1/V2 = 30/30; rows_read V1/V2 = 156/156; wall V1/V2 = 5 ms / 4 ms; `meta` V1/V2 = identical `[{"name":"minute","type":"DateTime"},{"name":"session_count","type":"UInt64"},{"name":"visitor_count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT toStartOfMinute(created_at) as minute, uniq(session_id) as session_count, uniq(profile_id) as visitor_count FROM events WHERE project_id = 'pincali-production' AND created_at >= (now() - INTERVAL 30 MINUTE) GROUP BY minute ORDER BY minute ASC WITH FILL FROM toStartOfMinute(now() - INTERVAL 30 MINUTE) TO toStartOfMinute(now()) STEP INTERVAL 1 MINUTE--- V2-SELECT toStartOfMinute(created_at) as minute, uniq(session_id) as session_count, uniq(profile_id) as visitor_count FROM events WHERE project_id = {p1:String} AND created_at >= (now() - INTERVAL 30 MINUTE) GROUP BY minute ORDER BY minute ASC WITH FILL FROM toStartOfMinute(now() - INTERVAL 30 MINUTE) TO toStartOfMinute(now()) STEP INTERVAL 1 MINUTE--- V2 params: {"p1":"pincali-production"}-```--rows V1: `[{"minute":"2026-09-07 10:12:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 10:13:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 10:14:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 10:15:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 1`-rows V2: `[{"minute":"2026-09-07 10:12:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 10:13:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 10:14:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 10:15:00","session_count":0,"visitor_count":0},{"minute":"2026-09-07 1`--### widget/realtimeData/minuteCounts (frozen now)--_now() -> toDateTime('2026-08-25 08:49:53') on both sides_--**statement** — IDENTICAL; rows V1/V2 = 151/151; rows_read V1/V2 = 65349/65349; wall V1/V2 = 7 ms / 10 ms; `meta` V1/V2 = identical `[{"name":"minute","type":"DateTime"},{"name":"session_count","type":"UInt64"},{"name":"visitor_count","type":"UInt64"}]`; clickhouse_settings: session_timezone=Europe/Stockholm/Europe/Stockholm.--```sql--- V1-SELECT toStartOfMinute(created_at) as minute, uniq(session_id) as session_count, uniq(profile_id) as visitor_count FROM events WHERE project_id = 'pincali-production' AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) GROUP BY minute ORDER BY minute ASC WITH FILL FROM toStartOfMinute(toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) TO toStartOfMinute(toDateTime('2026-08-25 08:49:53')) STEP INTERVAL 1 MINUTE--- V2-SELECT toStartOfMinute(created_at) as minute, uniq(session_id) as session_count, uniq(profile_id) as visitor_count FROM events WHERE project_id = {p1:String} AND created_at >= (toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) GROUP BY minute ORDER BY minute ASC WITH FILL FROM toStartOfMinute(toDateTime('2026-08-25 08:49:53') - INTERVAL 30 MINUTE) TO toStartOfMinute(toDateTime('2026-08-25 08:49:53')) STEP INTERVAL 1 MINUTE--- V2 params: {"p1":"pincali-production"}-```--rows V1: `[{"minute":"2026-08-25 08:19:00","session_count":16,"visitor_count":16},{"minute":"2026-08-25 08:20:00","session_count":49,"visitor_count":48},{"minute":"2026-08-25 08:21:00","session_count":61,"visitor_count":62},{"minute":"2026-08-25 08:22:00","session_count":55,"visitor_count":54},{"minute":"2026`-rows V2: `[{"minute":"2026-08-25 08:19:00","session_count":16,"visitor_count":16},{"minute":"2026-08-25 08:20:00","session_count":49,"visitor_count":48},{"minute":"2026-08-25 08:21:00","session_count":61,"visitor_count":62},{"minute":"2026-08-25 08:22:00","session_count":55,"visitor_count":54},{"minute":"2026`-diff --git a/packages/db/scripts/scripts.sql.proof.md b/packages/db/scripts/scripts.sql.proof.mddeleted file mode 100644index 24c3bfbfe..000000000--- a/packages/db/scripts/scripts.sql.proof.md+++ /dev/null@@ -1,119 +0,0 @@-# `packages/db/scripts` off `clix` / `sqlstring` — result-set proof (M12-009)--M12-009 deletes `query-builder.ts`, `sql-builder.ts` and the `sqlstring`-dependency. Two operator scripts in this directory were the last things in-`packages/db` importing either, so they move onto the `sql` tag in the same-commit. (The gate `tooling/gates/p12-grep-gates.sh` does not scan `scripts/`;-these two had to convert anyway because removing `sqlstring` from-`packages/db/package.json` removes the module they imported.)--V1 is each script's text at `30d236fa`; V2 is the tagged statement in this-commit. Both were rendered in one Bun process and executed through the same-`@clickhouse/client` — V1 as `query`, V2 as `query` + `query_params` — and the-result sets (or, for the writes, the table read back afterwards) compared field-for field.--- **Date**: 2026-09-07, run by ralph on this box.-- **Database**: a throwaway `m12009_scratch`, seeded per case and dropped after- the run. Both scripts are writers (`ALTER TABLE … UPDATE`, `INSERT … SELECT`),- so neither could be pointed at the prod-copy `openpanel` or at- `openpanel_test`.-- **Machine**: single-node ClickHouse 26.1.3.52, 4 vCPU. Timings directional- only; production is 2 shards × 2 replicas (`docs/ENVIRONMENT.md`).-- **Verdict**: **4 statements, all IDENTICAL.**--| # | Script | Statement | Rows | old → new |-|---|---|---|---:|---|-| 1 | `ch-update-sessions-with-revenue.ts:45` | `SELECT id FROM sessions … LIMIT {n}` | 2 | 5ms → 5ms |-| 2 | `ch-update-sessions-with-revenue.ts:79` | `ALTER TABLE … UPDATE revenue = multiIf(…)` | 4 read back | 11ms → 14ms |-| 3 | `ch-copy-from-remote.ts:95` | `SELECT * FROM remote(…)` | 2 | 7ms → 9ms |-| 4 | `ch-copy-from-remote.ts:97` | `INSERT INTO db.table SELECT * FROM remote(…)` | 3 → 5 | 9ms → 9ms |--## What binding buys here, concretely--`remote()` accepts bound parameters in every argument position — `{p:String}`-for the host, user and password, `{p:Identifier}` for the database and table.-That was verified before the conversion was written (case 3 above) and it is-the whole point: `ch-copy-from-remote.ts` **logs the query it is about to run**,-and V1's text carried the remote password in it. It no longer does — the-`--- params ---` line in the run below is the only place the credential-appears, and the script never prints it.--The `INSERT INTO <db>.<table>` target is the one position a `{x:Identifier}`-param is not accepted, so it goes through `sql.id()`, which throws on anything-that is not a bare identifier rather than falling back to interpolation-(ADR-013 R3).--## Type choices--- `revenue` is `Float64` (`system.columns`), so the `multiIf` branches bind as- `sql.float64` — the type ClickHouse infers for V1's bare integer literal in- that expression, not a wider guess.-- `LIMIT` takes `sql.uint64`.-- The two date bounds bind as `String`, exactly the form V1 quoted, so- `date_time_input_format: 'best_effort'` parses them identically.--## IN / GLOBAL IN--`WHERE id IN ('a','b')` became `WHERE id IN {p:Array(String)}`. Both are a-**literal set**, not a subquery, so they evaluate identically on every shard and-`docs/ENVIRONMENT.md`'s `IN` vs `GLOBAL IN` trap does not apply. No `IN` was-converted in either direction. `remote()` is a table function evaluated on the-initiator, unchanged by the rewrite.--## Run output--```-==============================================================================-CASE: ch-update-sessions-with-revenue: SELECT id FROM sessions [db=m12009_scratch]---- OLD ----SELECT id FROM sessions WHERE created_at >= '2025-11-10 00:00:00' AND created_at < '2025-11-10 01:00:00' AND project_id = 'public-web' LIMIT 2---- NEW ----SELECT id- FROM sessions- WHERE created_at >= {p1:String}- AND created_at < {p2:String}- AND project_id = {p3:String}- LIMIT {p4:UInt64}---- params ----{"p1":"2025-11-10 00:00:00","p2":"2025-11-10 01:00:00","p3":"public-web","p4":2}-old: ok=true 5ms-new: ok=true 5ms-old: {"meta":[{"name":"id","type":"String"}],"data":[["sess-a"],["sess-b"]]}-new: {"meta":[{"name":"id","type":"String"}],"data":[["sess-a"],["sess-b"]]}-RESULT SETS: IDENTICAL-==============================================================================-CASE: ch-update-sessions-with-revenue: ALTER TABLE ... UPDATE multiIf [db=m12009_scratch]---- OLD ----ALTER TABLE sessions UPDATE revenue = multiIf(id = 'sess-a', 1500, id = 'sess-b', 20000, revenue) WHERE id IN ('sess-a', 'sess-b')---- NEW ----ALTER TABLE sessions UPDATE revenue = multiIf(id = {p1:String}, {p2:Float64}, id = {p3:String}, {p4:Float64}, revenue) WHERE id IN {p5:Array(String)}---- params ----{"p1":"sess-a","p2":1500,"p3":"sess-b","p4":20000,"p5":["sess-a","sess-b"]}-old: ok=true 11ms-new: ok=true 14ms-old rows after: {"meta":[{"name":"id","type":"String"},{"name":"revenue","type":"Float64"}],"data":[["sess-a",1500],["sess-b",20000],["sess-c",0],["sess-d",0]]}-new rows after: {"meta":[{"name":"id","type":"String"},{"name":"revenue","type":"Float64"}],"data":[["sess-a",1500],["sess-b",20000],["sess-c",0],["sess-d",0]]}-RESULT SETS: IDENTICAL-==============================================================================-CASE: ch-copy-from-remote: INSERT INTO <db>.<table> SELECT * FROM remote(...) [db=m12009_scratch]---- OLD SELECT ----SELECT * FROM remote('127.0.0.1:9000', 'm12009_scratch', 'copy_target', 'default', '') WHERE created_at BETWEEN '2025-11-10 00:00:00' AND '2025-11-11 00:00:00' AND project_id IN ('p1', 'p2')---- NEW SELECT ----SELECT * FROM remote({p1:String}, {p2:Identifier}, {p3:Identifier}, {p4:String}, {p5:String}) WHERE created_at BETWEEN {p6:String} AND {p7:String} AND project_id IN {p8:Array(String)}---- params (note: credentials are NOT in the text) ----{"p1":"127.0.0.1:9000","p2":"m12009_scratch","p3":"copy_target","p4":"default","p5":"","p6":"2025-11-10 00:00:00","p7":"2025-11-11 00:00:00","p8":["p1","p2"]}-old: ok=true 7ms-new: ok=true 9ms-old: {"meta":[{"name":"project_id","type":"String"},{"name":"created_at","type":"DateTime64(3)"},{"name":"name","type":"String"}],"data":[["p1","2025-11-10 00:05:00.000","a"],["p2","2025-11-10 00:06:00.000","b"]]}-new: {"meta":[{"name":"project_id","type":"String"},{"name":"created_at","type":"DateTime64(3)"},{"name":"name","type":"String"}],"data":[["p1","2025-11-10 00:05:00.000","a"],["p2","2025-11-10 00:06:00.000","b"]]}-SELECT RESULT SETS: IDENTICAL---- OLD INSERT ----INSERT INTO m12009_scratch.copy_target SELECT * FROM remote('127.0.0.1:9000', 'm12009_scratch', 'copy_target', 'default', '') WHERE created_at BETWEEN '2025-11-10 00:00:00' AND '2025-11-11 00:00:00' AND project_id IN ('p1', 'p2')---- NEW INSERT ----INSERT INTO m12009_scratch.copy_target SELECT * FROM remote({p1:String}, {p2:Identifier}, {p3:Identifier}, {p4:String}, {p5:String}) WHERE created_at BETWEEN {p6:String} AND {p7:String} AND project_id IN {p8:Array(String)}-old INSERT: ok=true 9ms-new INSERT: ok=true 9ms-count before: {"meta":[{"name":"count()","type":"UInt64"}],"data":[[3]]} after old: {"meta":[{"name":"count()","type":"UInt64"}],"data":[[5]]} after new: {"meta":[{"name":"count()","type":"UInt64"}],"data":[[5]]}-INSERT EFFECT: IDENTICAL-```