OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M12-003): chart/src/field-resolution.ts + table-filter-where.ts onto the sql tag; compiled.ts deleted when its last caller goes; proof; goldens 137/137
ralph54c4fe7af3c5
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 69f3cbf11..7819f4e72 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -453,9 +453,9 @@ export { emailCategories } from './modules/email/email.constants';// assistant/mcp tools call these directly, the same way V1 reaches every// other dissolved service here. `packages/db`'s re-export shims for these// three files are gone (M9-CLEANUP-001) — every caller now imports this-// barrel directly, and `profileSearchSql` (cohort.service's one addition atop-// the shim) moved to profile/src/profile.sql.ts alongside its sibling-// `profileSearchCondition`.+// barrel directly. `profileSearchSql` (cohort.service's one addition atop the+// shim) died with M12-003: its only caller now composes a `sql` fragment and+// uses `profileSearchCondition`.export type {EventListSelect,GetEventListOptions,diff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.tsindex 22014b847..168321540 100644--- a/packages/core/src/modules/chart/chart.service.ts+++ b/packages/core/src/modules/chart/chart.service.ts@@ -105,6 +105,7 @@ export {getAggregateChartSql,getChartSql,} from './src/chart-statement';+export { rewriteProfilePropertyRefs } from './src/compiled';export { executeAggregateChart, executeChart } from './src/engine/execute';export {evaluateFormula,@@ -139,7 +140,6 @@ export {isNumericColumn,normalizeEventField,profilePropertiesCteSelect,- rewriteProfilePropertyRefs,transformPropertyKey,} from './src/field-resolution';export {diff --git a/packages/core/src/modules/chart/conversion.service.ts b/packages/core/src/modules/chart/conversion.service.tsindex 0216f6d6b..adc12e7dc 100644--- a/packages/core/src/modules/chart/conversion.service.ts+++ b/packages/core/src/modules/chart/conversion.service.ts@@ -3,12 +3,14 @@// 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 } from '../../services';import type { IReportInput } from '../report/report.constants';import { NOT_SET_VALUE } from '../report/report.constants';import { mergeGlobalFilters, onlyReportEvents } from '../report/src/series';import { fetchCohortsMetadata } from './src/chart-statement';+import { compiledText } from './src/compiled';import { type ConversionGroup, conversionQuery } from './src/conversion.sql';import {buildInlineCohortJoin,@@ -132,7 +134,7 @@ export async function getConversion();});const breakdownSelects = breakdownExpressions.map(- (expression, index) => `${expression} as b_${index}`+ (expression, index) => sql`${expression} as ${compiledText(`b_${index}`)}`);const events = onlyReportEvents(mergedSeries);diff --git a/packages/core/src/modules/chart/src/chart.sql.test.ts b/packages/core/src/modules/chart/src/chart.sql.test.tsindex bbd81f038..bb645cd40 100644--- a/packages/core/src/modules/chart/src/chart.sql.test.ts+++ b/packages/core/src/modules/chart/src/chart.sql.test.ts@@ -76,11 +76,36 @@ async function getAggregateChartSql(input: LooseAggregateInput) {interface Rendered {sql: string;params: Record<string, unknown>;+ /**+ * `sql` with every `{pN:Type}` substituted back to the literal V1 emitted.+ * Since M12-003 the field resolver binds `properties[<key>]` keys too, so+ * an assertion about the SHAPE of a map access reads this; an assertion+ * about what is bound reads `sql`/`params`.+ */+ text: string;+}++const PLACEHOLDER = /\{(p\d+):[^}]+\}/g;++function literal(value: unknown): string {+ if (Array.isArray(value)) {+ return `(${value.map(literal).join(', ')})`;+ }+ if (typeof value === 'string') {+ return `'${value.replace(/'/g, "\\'")}'`;+ }+ return String(value);}function render(fragment: SqlFragment): Rendered {const { query, query_params } = fragment.toStatement();- return { sql: query, params: query_params };+ return {+ sql: query,+ params: query_params,+ text: query.replace(PLACEHOLDER, (_match, name: string) =>+ literal(query_params[name])+ ),+ };}async function explain({ sql, params }: Rendered): Promise<void> {@@ -147,8 +172,8 @@ describe('getChartSql', () => {// Every map access on the events table must be aliased — the `_g` join// also exposes a `properties` column, so the bare form is ambiguous.- expect(rendered.sql).not.toMatch(/(?<![._\w])properties\[/);- expect(rendered.sql).toContain("e.properties['__query.utm_source']");+ expect(rendered.text).not.toMatch(/(?<![._\w])properties\[/);+ expect(rendered.text).toContain("e.properties['__query.utm_source']");await explain(rendered);});@@ -236,7 +261,7 @@ describe('getChartSql', () => {breakdowns: [],...base,});- expect(rendered.sql).toContain("e.properties['revenue_amount']");+ expect(rendered.text).toContain("e.properties['revenue_amount']");await explain(rendered);});@@ -328,9 +353,9 @@ describe('getChartSql', () => {breakdowns: [],...base,});- expect(rendered.sql).toContain("properties['__query.utm_source']");+ expect(rendered.text).toContain("properties['__query.utm_source']");// The unqualified `utm_source = …` form would fail with UNKNOWN_IDENTIFIER.- expect(rendered.sql).not.toMatch(/(?<![._\w])utm_source\s*=/);+ expect(rendered.text).not.toMatch(/(?<![._\w])utm_source\s*=/);await explain(rendered);});@@ -401,7 +426,7 @@ describe('getAggregateChartSql', () => {breakdowns: [breakdown('properties.__query.utm_source')],...base,});- expect(rendered.sql).toContain("e.properties['__query.utm_source']");+ expect(rendered.text).toContain("e.properties['__query.utm_source']");await explain(rendered);});});@@ -415,26 +440,26 @@ describe('profile-property narrowing', () => {};it('projects only the referenced keys as scalar columns in the profile CTE', async () => {- const { sql } = await getChartSql({+ const { text } = await getChartSql({event: event({ filters: [profileFilter] }),breakdowns: [breakdown('profile.properties.experiment')],...base,});// The CTE selects one scalar column per referenced key...- expect(sql).toContain("properties['plan'] as `profile.properties.plan`");- expect(sql).toContain(+ expect(text).toContain("properties['plan'] as `profile.properties.plan`");+ expect(text).toContain("properties['experiment'] as `profile.properties.experiment`");// ...instead of every profile's whole Map...- expect(sql).not.toContain('properties as "profile.properties"');+ expect(text).not.toContain('properties as "profile.properties"');// ...and every ref in the query is rewritten to the scalar alias.- expect(sql).not.toContain("profile.properties['plan']");- expect(sql).not.toContain("profile.properties['experiment']");+ expect(text).not.toContain("profile.properties['plan']");+ expect(text).not.toContain("profile.properties['experiment']");});it('falls back to the full Map for wildcard refs', async () => {- const { sql } = await getChartSql({+ const { text } = await getChartSql({event: event({filters: [{@@ -450,11 +475,11 @@ describe('profile-property narrowing', () => {});// mapExtractKeyLike needs the whole Map, so it must stay selected.- expect(sql).toContain('properties as "profile.properties"');+ expect(text).toContain('properties as "profile.properties"');});it('never narrows identifier-unsafe keys (backtick falls back to the Map)', async () => {- const { sql } = await getChartSql({+ const { text } = await getChartSql({event: event({filters: [{@@ -471,12 +496,12 @@ describe('profile-property narrowing', () => {// The unsafe key keeps its original Map access against the full Map —// it must never be embedded in a backtick-quoted alias.- expect(sql).toContain('properties as "profile.properties"');- expect(sql).not.toContain('as `profile.properties.plan`tier`');+ expect(text).toContain('properties as "profile.properties"');+ expect(text).not.toContain('as `profile.properties.plan`tier`');});it('collects the math-metric property too', async () => {- const { sql } = await getChartSql({+ const { text } = await getChartSql({event: event({segment: 'property_average',property: 'profile.properties.age',@@ -488,14 +513,14 @@ describe('profile-property narrowing', () => {// The metric's key must be narrowed alongside the filter's — otherwise// the metric keeps reading the Map that narrowing just removed.- expect(sql).toContain("properties['age'] as `profile.properties.age`");- expect(sql).not.toContain("profile.properties['age']");+ expect(text).toContain("properties['age'] as `profile.properties.age`");+ expect(text).not.toContain("profile.properties['age']");});it('creates the profile join for a metric-only profile property', async () => {// No profile filter or breakdown — the metric alone must still create// the CTE and join, or its scalar alias resolves against nothing.- const { sql } = await getChartSql({+ const { text } = await getChartSql({event: event({segment: 'property_average',property: 'profile.properties.age',@@ -505,8 +530,8 @@ describe('profile-property narrowing', () => {...base,});- expect(sql).toContain('LEFT ANY JOIN profile ON profile.id = profile_id');- expect(sql).toContain("properties['age'] as `profile.properties.age`");+ expect(text).toContain('LEFT ANY JOIN profile ON profile.id = profile_id');+ expect(text).toContain("properties['age'] as `profile.properties.age`");});it('metric-only profile property parses and resolves', async () => {diff --git a/packages/core/src/modules/chart/src/chart.sql.ts b/packages/core/src/modules/chart/src/chart.sql.tsindex 52fc29391..f0ffe638f 100644--- a/packages/core/src/modules/chart/src/chart.sql.ts+++ b/packages/core/src/modules/chart/src/chart.sql.ts@@ -29,11 +29,7 @@ import type {IChartEvent,IInterval,} from '../../report/report.constants';-import {- compiledText,- compiledTextWithProfileRefs,- fragmentWithProfileRefs,-} from './compiled';+import { compiledText, fragmentWithProfileRefs } from './compiled';import { formatClickhouseDate } from './dates';import {CHART_TABLE,@@ -47,6 +43,7 @@ import {isAllCohortsBreakdown,isKnownEventField,isNumericColumn,+ PROFILE_CTE_FIELDS,profilePropertiesCteSelect,} from './field-resolution';import { getEventFiltersWhereClause } from './filter-where';@@ -268,18 +265,20 @@ function profileCteSelectField(field: string,profileKeys: string[],needsFullMap: boolean-): string {- if (field === 'id') {- return 'id as "profile.id"';- }+): SqlFragment {if (field === 'properties') {return profilePropertiesCteSelect(profileKeys, needsFullMap);}- return `${field} as "profile.${field}"`;+ // The alias is `"profile.<field>"` — two dots, so text, not `sql.id`.+ // `collectProfileCteFields` only ever yields a name from its own closed set.+ return sql`${sql.id(field, PROFILE_CTE_FIELDS)} as ${compiledText(`"profile.${field}"`)}`;}-function profileCte(selectFields: string[], projectId: string): SqlFragment {- return sql`SELECT ${compiledText(selectFields.join(', '))}+function profileCte(+ selectFields: SqlFragment[],+ projectId: string+): SqlFragment {+ return sql`SELECT ${sql.join(selectFields, ', ')}FROM ${sql.id(CHART_TABLE.profiles)} FINALWHERE project_id = ${sql.string(projectId)}`;}@@ -294,8 +293,6 @@ interface ChartBody {where: Parts;select: Parts;profileKeys: string[];- /** Compiled (text) expressions go through this so V1's profile-ref rewrite still applies. */- spliced: (text: string) => SqlFragment;}/**@@ -326,11 +323,6 @@ function chartBody({...breakdowns,...metricRef,]);- // field-resolution.ts still renders text (M12-003); filter-where.ts no- // longer does, so its clauses take the fragment-level rewrite instead.- const spliced = (text: string) =>- compiledTextWithProfileRefs(text, profileProps.keys);-const ctes: Parts = {};const joins: Parts = {};@@ -392,7 +384,6 @@ function chartBody({where,select,profileKeys: profileProps.keys,- spliced,};}@@ -402,12 +393,12 @@ function breakdownLabel(allCohorts,cohortMetadata,projectId,- spliced,+ profileKeys,}: Pick<ChartSeriesQueryInput,'allCohorts' | 'cohortMetadata' | 'projectId'> &- Pick<ChartBody, 'spliced'>+ Pick<ChartBody, 'profileKeys'>): SqlFragment {if (isAllCohortsBreakdown(breakdown.name)) {return allCohortsLabelExpr(allCohorts);@@ -416,14 +407,15 @@ function breakdownLabel(if (cohortId) {return cohortBreakdownLabel(cohortId, cohortMetadata.get(cohortId)?.name);}- return spliced(+ return fragmentWithProfileRefs(getSelectPropertyKey(breakdown.name,projectId,undefined,undefined,EVENTS_ALIAS- )+ ),+ profileKeys);}@@ -437,7 +429,7 @@ function addBreakdownLabels(const key = `label_${index + 1}`;const label = breakdownLabel(breakdown, {...input,- spliced: body.spliced,+ profileKeys: body.profileKeys,});body.select[key] = sql`${label} as ${compiledText(key)}`;groupBy[key] = compiledText(key);@@ -464,14 +456,15 @@ function countExpression(}const mathFunction = MATH_FUNCTION_BY_SEGMENT[event.segment];if (mathFunction && event.property) {- const propertyKey = body.spliced(+ const propertyKey = fragmentWithProfileRefs(getSelectPropertyKey(event.property,metricProjectId,undefined,undefined,EVENTS_ALIAS- )+ ),+ body.profileKeys);const aggregate = compiledText(mathFunction);if (isNumericColumn(event.property)) {@@ -686,31 +679,29 @@ export function eventPropertyValuesQuery(/** Distinct values of a `profile.*` field straight off the profiles table. */export function profilePropertyValuesQuery(projectId: string,- selectExpression: string+ expression: SqlFragment): SqlFragment {- const expression = compiledText(selectExpression);return sql`SELECT distinct ${expression} as values FROM ${sql.id(CHART_TABLE.profiles)} FINAL WHERE project_id = ${sql.string(projectId)} AND ${expression} != '' AND ${expression} IS NOT NULL ORDER BY created_at DESC LIMIT ${sql.uint64(PROPERTY_VALUES_LIMIT)}`;}/** Distinct values of a `group.*` field straight off the groups table. */export function groupPropertyValuesQuery(projectId: string,- selectExpression: string+ expression: SqlFragment): SqlFragment {- const expression = compiledText(selectExpression);return sql`SELECT distinct ${expression} as values FROM ${sql.id(CHART_TABLE.groups)} FINAL WHERE project_id = ${sql.string(projectId)} AND deleted = 0 AND ${expression} != '' AND ${expression} IS NOT NULL ORDER BY created_at DESC LIMIT ${sql.uint64(PROPERTY_VALUES_LIMIT)}`;}/** Distinct values of an events column / property over the last six months. */export function eventFieldValuesQuery(projectId: string,- selectExpression: string,+ selectExpression: SqlFragment,event: string): SqlFragment {// V1 only skipped the name clause for `*` — an empty event name filters on ''.const eventName =event !== '*' ? sql` AND name = ${sql.string(event)}` : sql.empty;- return sql`SELECT distinct ${compiledText(selectExpression)} as values FROM ${sql.id(CHART_TABLE.events)} WHERE project_id = ${sql.string(projectId)} AND created_at > (now() - INTERVAL 6 MONTH)${eventName} ORDER BY created_at DESC LIMIT ${sql.uint64(PROPERTY_VALUES_LIMIT)}`;+ return sql`SELECT distinct ${selectExpression} as values FROM ${sql.id(CHART_TABLE.events)} WHERE project_id = ${sql.string(projectId)} AND created_at > (now() - INTERVAL 6 MONTH)${eventName} ORDER BY created_at DESC LIMIT ${sql.uint64(PROPERTY_VALUES_LIMIT)}`;}// --- getProfiles ------------------------------------------------------------@@ -794,7 +785,7 @@ export function chartBucketProfilesQuery(}for (const [key, value] of Object.entries(breakdowns)) {- const propertyKey = compiledText(getSelectPropertyKey(key, projectId));+ const propertyKey = getSelectPropertyKey(key, projectId);where[`breakdown_${key}`] = sql`${propertyKey} = ${sql.string(value)}`;}diff --git a/packages/core/src/modules/chart/src/compiled.ts b/packages/core/src/modules/chart/src/compiled.tsindex f539f753e..49af85639 100644--- a/packages/core/src/modules/chart/src/compiled.ts+++ b/packages/core/src/modules/chart/src/compiled.ts@@ -1,42 +1,100 @@-// The ONE place the chart module splices pre-compiled SQL text.+// The ONE place the chart module splices pre-compiled SQL text, and the home+// of V1's profile-property-ref rewrite.//-// field-resolution.ts is V1's field resolver, still rendering sqlstring-escaped-// text: ADR-013 leaves it as it is until its own conversion (M12-003). Every-// chart-level value is bound in chart.sql.ts and every filter value is bound by-// filter-where.ts (M12-002); only the field resolver's output still crosses-// here, through the same `SqlFragment` constructor `sql.id` uses — one grep away-// from deletion, not a `sql.raw()`.+// Both filter compilers (./filter-where.ts, ./table-filter-where.ts) and the+// field resolver (./field-resolution.ts) return `SqlFragment`s now, so nothing+// crosses `compiledText` from them any more. What is left are the places the+// chart builders splice a name they generated themselves — CTE names, `b_<n>`+// / `label_<n>` aliases, a `toStartOf*` keyword, the backtick-quoted+// `profile.properties.<key>` CTE alias — none of which is a value and none of+// which `sql.id` can express. It stays a named export in one file, not a+// `sql.raw()`, so the census is a grep.import {isSqlFragment,SqlFragment,type SqlSlot,} from '@openpanel/db/src/clickhouse/sql';-import { rewriteProfilePropertyRefs } from './field-resolution';++const PROFILE_PROPERTY_MAP_OPEN = 'profile.properties[';+const PROFILE_PROPERTY_MAP_CLOSE = ']';export function compiledText(text: string): SqlFragment {return new SqlFragment([text], []);}+/** `` `profile.properties.<key>` `` — the narrowed CTE column for `key`. */+function narrowedProfileColumn(key: string): string {+ return `\`profile.properties.${key}\``;+}+/**- * V1 ran `rewriteProfilePropertyRefs` over the finished query text. Bound- * params never matched it (an escaped literal cannot contain `['`), so- * applying it to each compiled piece before splicing is the same rewrite.+ * Rewrite `profile.properties['<key>']` -> `` `profile.properties.<key>` ``+ * for the narrowed keys. V1 ran this over the finished query TEXT; it never+ * matched a value, because an escaped literal cannot contain `['`.*/-export function compiledTextWithProfileRefs(- text: string,- profilePropertyKeys: readonly string[]-): SqlFragment {- return compiledText(- rewriteProfilePropertyRefs(text, profilePropertyKeys as string[])- );+export function rewriteProfilePropertyRefs(+ sql: string,+ keys: string[]+): string {+ let out = sql;+ for (const k of keys) {+ out = out+ .split(`${PROFILE_PROPERTY_MAP_OPEN}'${k}'${PROFILE_PROPERTY_MAP_CLOSE}`)+ .join(narrowedProfileColumn(k));+ }+ return out;+}++/** The key a narrowable `properties[<key>]` param carries, or null. */+function narrowableKey(slot: SqlSlot, keys: string[]): string | null {+ if (isSqlFragment(slot) || slot.type !== 'String') {+ return null;+ }+ const { value } = slot;+ return typeof value === 'string' && keys.includes(value) ? value : null;+}++/**+ * Splice nested fragments into one flat (literals, params) interleaving. The+ * rendered statement is unchanged — this only makes "the literal immediately+ * before this param" a question with an answer, which is what the rewrite+ * below needs now that `sql.id` contributes a nested fragment of its own.+ */+function flatten(+ fragment: SqlFragment,+ strings: string[],+ slots: SqlSlot[]+): void {+ if (strings.length === 0) {+ strings.push('');+ }+ for (const [index, literal] of fragment.strings.entries()) {+ strings[strings.length - 1] += literal;+ const slot = fragment.slots[index];+ if (!slot) {+ continue;+ }+ if (isSqlFragment(slot)) {+ flatten(slot, strings, slots);+ continue;+ }+ slots.push(slot);+ strings.push('');+ }}/**- * The same rewrite over a fragment: it runs on the literal parts only and- * never on a slot, so a bound value can no longer be rewritten even in- * principle. That is the property `compiledTextWithProfileRefs` relied on- * being true by accident of escaping; here it is true by construction.+ * The same rewrite over a fragment. It runs on the literal parts, and on the+ * one shape the field resolver now emits instead of text — the literal+ * `profile.properties[` followed by the key as a bound `String` param and a+ * closing `]`. Collapsing those three pieces is what keeps a narrowed+ * `profile.properties.<key>` ref pointing at the CTE's scalar column once the+ * key stopped being part of the SQL text (M12-003).+ *+ * A value can no longer be rewritten even in principle: only a param the+ * resolver placed in that exact position is eligible, and it is replaced by+ * an identifier rather than edited.*/export function fragmentWithProfileRefs(fragment: SqlFragment,@@ -46,11 +104,33 @@ export function fragmentWithProfileRefs(return fragment;}const keys = profilePropertyKeys as string[];- const strings = fragment.strings.map((literal) =>- rewriteProfilePropertyRefs(literal, keys)- );- const slots: SqlSlot[] = fragment.slots.map((slot) =>- isSqlFragment(slot) ? fragmentWithProfileRefs(slot, keys) : slot- );+ const flatStrings: string[] = [];+ const flatSlots: SqlSlot[] = [];+ flatten(fragment, flatStrings, flatSlots);++ const strings: string[] = [];+ const slots: SqlSlot[] = [];+ let pending = rewriteProfilePropertyRefs(flatStrings[0] ?? '', keys);++ for (const [index, slot] of flatSlots.entries()) {+ const next = rewriteProfilePropertyRefs(flatStrings[index + 1] ?? '', keys);+ const key = narrowableKey(slot, keys);+ if (+ key !== null &&+ pending.endsWith(PROFILE_PROPERTY_MAP_OPEN) &&+ next.startsWith(PROFILE_PROPERTY_MAP_CLOSE)+ ) {+ pending =+ pending.slice(0, -PROFILE_PROPERTY_MAP_OPEN.length) ++ narrowedProfileColumn(key) ++ next.slice(PROFILE_PROPERTY_MAP_CLOSE.length);+ continue;+ }+ strings.push(pending);+ slots.push(slot);+ pending = next;+ }++ strings.push(pending);return new SqlFragment(strings, slots);}diff --git a/packages/core/src/modules/chart/src/conversion.sql.ts b/packages/core/src/modules/chart/src/conversion.sql.tsindex 58ecf4a39..3fb1d035a 100644--- a/packages/core/src/modules/chart/src/conversion.sql.ts+++ b/packages/core/src/modules/chart/src/conversion.sql.ts@@ -4,9 +4,10 @@// window and the interval bucket bound as `{pN:Type}` parameters instead of// inlined literals. Result-set proof: conversion.sql.proof.md.//-// The field resolver and filter compiler still render text (see compiled.ts);-// their output — breakdown expressions, per-step filter clauses and the-// cohort joins — is spliced, everything else is bound.+// The field resolver and both filter compilers return fragments (M12-002,+// M12-003); 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@@ -57,14 +58,14 @@ export interface ConversionQueryInput {firstEventWhere: SqlFragment | null;secondEventWhere: SqlFragment | null;/** Compiled `<expr> as b_<index>` breakdown selects. */- breakdownSelects: string[];+ breakdownSelects: SqlFragment[];/** Compiled breakdown expressions, as written in the inner GROUP BY. */- breakdownExpressions: string[];+ breakdownExpressions: SqlFragment[];/** Profile columns to select in the LEFT ANY JOIN, or [] for no join. */profileJoinFields: string[];needsGroupArrayJoin: boolean;/** Compiled cohort join clauses. */- cohortJoins: string[];+ cohortJoins: SqlFragment[];}function stepCondition(name: string, where: SqlFragment | null): SqlFragment {@@ -128,11 +129,11 @@ export function conversionQuery(input: ConversionQueryInput): SqlFragment {const innerBreakdownSelects =breakdownSelects.length > 0- ? sql`${sql.join(breakdownSelects.map(compiledText))},`+ ? sql`${sql.join(breakdownSelects)},`: sql.empty;const innerBreakdownGroupBy =breakdownExpressions.length > 0- ? sql`, ${sql.join(breakdownExpressions.map(compiledText))}`+ ? sql`, ${sql.join(breakdownExpressions)}`: sql.empty;return sql`SELECT ${outerSelect} FROM (@@ -148,7 +149,7 @@ export function conversionQuery(input: ConversionQueryInput): SqlFragment {FROM ${sql.id(CHART_TABLE.events)}${profileJoin(profileJoinFields, projectId)}${groupJoin(needsGroupArrayJoin, projectId)}- ${sql.join(cohortJoins.map(compiledText), ' ')}+ ${sql.join(cohortJoins, ' ')}WHERE project_id = ${sql.string(projectId)}AND events.name IN ${sql.array('String', [firstEventName, secondEventName])}AND created_at BETWEEN toDateTime(${sql.string(startDate)}) AND toDateTime(${sql.string(endDate)})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.mdnew file mode 100644index 000000000..a1a7b11c8--- /dev/null+++ b/packages/core/src/modules/chart/src/field-resolution.sql.proof.md@@ -0,0 +1,2150 @@+# 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 `chart.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/chart.sql.ts:175` — the CTE name in+ `WITH <name> AS (...)`.+- `packages/core/src/modules/chart/src/chart.sql.ts:274` — the double-quoted+ `"profile.<field>"` CTE alias.+- `packages/core/src/modules/chart/src/chart.sql.ts:340` — the+ `` `cohort-<id>` `` CTE name in a JOIN.+- `packages/core/src/modules/chart/src/chart.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). `chart.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 |+|---|---|---|+| `chart.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` |+| `chart.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` |+| `chart.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` |+| `chart.sql.test.ts` › `getAggregateChartSql` › `properties + group breakdown is unambiguous` | `expect(rendered.sql).toContain("e.properties['__query.utm_source']")` | same on `rendered.text` |+| `chart.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/field-resolution.ts b/packages/core/src/modules/chart/src/field-resolution.tsindex 6463a39b9..ca5f51cc3 100644--- a/packages/core/src/modules/chart/src/field-resolution.ts+++ b/packages/core/src/modules/chart/src/field-resolution.ts@@ -5,16 +5,21 @@// `group.name`, `cohort:<id>`, `has_profile`) becomes a ClickHouse// expression, plus the profile-CTE narrowing helpers.//-// These render TEXT with sqlstring on purpose. They are the SELECT/JOIN half-// of the filter compiler that funnel, conversion, sankey, retention and-// overview (M7-004/M7-005) still splice into their own builders, and ADR-013-// leaves the shared compilers as they are until their last consumer converts-// ("two behaviours, not two builders"). chart.sql.ts splices their output-// through compiled.ts — the one bridge — and binds every chart-level value-// (project id, event name, dates, timezone, cohort ids/names, limits) itself.--import sqlstring from 'sqlstring';+// M12-003 converted every resolver onto the `sql` tag: each one returns a+// `SqlFragment` whose values — cohort ids, cohort labels, project ids and the+// `properties[...]` map keys — bind as `{pN:Type}` params, and whose+// identifiers go through `sql.id`. Callers interpolate the fragment directly;+// nothing wraps it in `compiledText` any more.+//+// The one piece of text this file still builds is the backtick-quoted CTE+// alias `` `profile.properties.<key>` `` (see `profilePropertiesCteSelect`),+// which is an identifier `sql.id` cannot express — three dot-separated parts —+// and which `collectProfilePropertyKeys` already guards. It goes through+// `compiled.ts`, the module's one text seam.++import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IChartBreakdown } from '../../report/report.constants';+import { compiledText } from './compiled';export const CHART_TABLE = {events: 'events',@@ -94,6 +99,14 @@ const EVENT_UTM_BARE_COLUMNS = new Set<string>([const NUMERIC_EVENT_COLUMNS = ['duration', 'revenue', 'longitude', 'latitude'];+/** The all-cohorts breakdown's JOIN alias and its fallback label. */+const ALL_COHORTS_DEFAULT_ALIAS = '_all_cohorts';+const ALL_COHORTS_UNKNOWN_LABEL = 'Unknown';++/** Labels a single-cohort breakdown falls back to when the cohort has no name. */+const IN_COHORT_LABEL = 'In Cohort';+const NOT_IN_COHORT_LABEL = 'Not In Cohort';+const PROFILE_CTE_SCALAR_FIELDS = ['email','first_name',@@ -102,6 +115,26 @@ const PROFILE_CTE_SCALAR_FIELDS = ['last_seen_at',];+/** Everything `collectProfileCteFields` can return — `sql.id`'s closed set. */+export const PROFILE_CTE_FIELDS = [+ 'id',+ 'properties',+ ...PROFILE_CTE_SCALAR_FIELDS,+];++// Top-level profiles columns `profile.<field>` may select, in V1's order. Same+// set as PROFILE_COLUMNS in ./table-filter-where.ts, which resolves the filter+// side; keep the two in sync.+const PROFILE_SELECT_COLUMNS = [+ 'id',+ 'first_name',+ 'last_name',+ 'email',+ 'avatar',+ 'created_at',+ 'last_seen_at',+];+// Normalize an incoming field name into its canonical form. Returns a string// suitable for `getSelectPropertyKey` / `getEventFiltersWhereClause` — i.e.// either a top-level column name (`referrer_name`), a `properties.foo` /@@ -160,8 +193,14 @@ export interface CohortMetadata {name: string;}-export function getCohortCteName(cohortId: string): string {- return `\`cohort-${cohortId}\``;+/**+ * The CTE name a single-cohort breakdown declares. Backtick-quoted because the+ * id contains dashes, which `sql.id` rejects, so it goes through the module's+ * one text seam. Callers must validate the id first — chart.sql.ts builds the+ * same name behind `assertCohortId`.+ */+export function getCohortCteName(cohortId: string): SqlFragment {+ return compiledText(`\`cohort-${cohortId}\``);}export function getCohortAlias(cohortId: string): string {@@ -171,12 +210,12 @@ export function getCohortAlias(cohortId: string): string {export function buildCohortMembershipQuery(cohortId: string,projectId: string-): string {- return `+): SqlFragment {+ return sql`SELECT profile_id- FROM ${CHART_TABLE.cohortMembers} FINAL- WHERE cohort_id = ${sqlstring.escape(cohortId)}- AND project_id = ${sqlstring.escape(projectId)}+ FROM ${sql.id(CHART_TABLE.cohortMembers)} FINAL+ WHERE cohort_id = ${sql.string(cohortId)}+ AND project_id = ${sql.string(projectId)}`;}@@ -184,10 +223,10 @@ export function buildInlineCohortJoin(cohortId: string,projectId: string,tableAlias: string-): string {+): SqlFragment {const cohortAlias = getCohortAlias(cohortId);const cohortQuery = buildCohortMembershipQuery(cohortId, projectId);- return `LEFT ANY JOIN (${cohortQuery}) AS ${cohortAlias} ON ${cohortAlias}.profile_id = ${tableAlias}.profile_id`;+ return sql`LEFT ANY JOIN (${cohortQuery}) AS ${sql.id(cohortAlias)} ON ${sql.id(`${cohortAlias}.profile_id`)} = ${sql.id(`${tableAlias}.profile_id`)}`;}export function extractCohortId(breakdownName: string): string | null {@@ -201,24 +240,30 @@ export function isAllCohortsBreakdown(breakdownName: string): boolean {return breakdownName === 'cohort';}-export function buildAllCohortsMembershipQuery(projectId: string): string {- return `+export function buildAllCohortsMembershipQuery(projectId: string): SqlFragment {+ return sql`SELECT profile_id, cohort_id- FROM ${CHART_TABLE.cohortMembers} FINAL- WHERE project_id = ${sqlstring.escape(projectId)}+ FROM ${sql.id(CHART_TABLE.cohortMembers)} FINAL+ WHERE project_id = ${sql.string(projectId)}`;}export function buildAllCohortsLabelExpr(cohorts: CohortMetadata[],- alias = '_all_cohorts'-): string {+ alias = ALL_COHORTS_DEFAULT_ALIAS+): SqlFragment {if (cohorts.length === 0) {- return "'Unknown'";+ return sql`${sql.string(ALL_COHORTS_UNKNOWN_LABEL)}`;}- const ids = cohorts.map((c) => sqlstring.escape(c.id)).join(', ');- const names = cohorts.map((c) => sqlstring.escape(c.name)).join(', ');- return `transform(${alias}.cohort_id, [${ids}], [${names}], 'Unknown')`;+ const ids = sql.array(+ 'String',+ cohorts.map((c) => c.id)+ );+ const names = sql.array(+ 'String',+ cohorts.map((c) => c.name)+ );+ return sql`transform(${sql.id(`${alias}.cohort_id`)}, ${ids}, ${names}, ${sql.string(ALL_COHORTS_UNKNOWN_LABEL)})`;}/**@@ -263,73 +308,84 @@ export function transformPropertyKey(property: string) {// Returns a SQL expression for a group property via the _g JOIN alias// property format: "group.name", "group.type", "group.properties.plan"-export function getGroupPropertySql(property: string): string {+export function getGroupPropertySql(property: string): SqlFragment {const withoutPrefix = property.replace(/^group\./, '');if (withoutPrefix === 'name') {- return '_g.name';+ return sql`_g.name`;}if (withoutPrefix === 'type') {- return '_g.type';+ return sql`_g.type`;}if (withoutPrefix.startsWith('properties.')) {const propKey = withoutPrefix.replace(/^properties\./, '');- return `_g.properties[${sqlstring.escape(propKey)}]`;+ return sql`_g.properties[${sql.string(propKey)}]`;}- return '_group_id';+ return sql`_group_id`;}// Returns the SELECT expression when querying the groups table directly (no join alias).// Use for fetching distinct values for group.* properties.-export function getGroupPropertySelect(property: string): string {+export function getGroupPropertySelect(property: string): SqlFragment {const withoutPrefix = property.replace(/^group\./, '');if (withoutPrefix === 'name') {- return 'name';+ return sql`name`;}if (withoutPrefix === 'type') {- return 'type';+ return sql`type`;}if (withoutPrefix === 'id') {- return 'id';+ return sql`id`;}if (withoutPrefix.startsWith('properties.')) {const propKey = withoutPrefix.replace(/^properties\./, '');- return `properties[${sqlstring.escape(propKey)}]`;+ return sql`properties[${sql.string(propKey)}]`;}- return 'id';+ return sql`id`;}// Returns the SELECT expression when querying the profiles table directly (no join alias).// Use for fetching distinct values for profile.* properties.// Lists the same profiles columns as PROFILE_COLUMNS in filter-where.service.ts,// which resolves profile.* on the filter side; keep the two in sync.-export function getProfilePropertySelect(property: string): string {+export function getProfilePropertySelect(property: string): SqlFragment {const withoutPrefix = property.replace(/^profile\./, '');- if (withoutPrefix === 'id') {- return 'id';- }- if (withoutPrefix === 'first_name') {- return 'first_name';- }- if (withoutPrefix === 'last_name') {- return 'last_name';- }- if (withoutPrefix === 'email') {- return 'email';- }- if (withoutPrefix === 'avatar') {- return 'avatar';- }- if (withoutPrefix === 'created_at') {- return 'created_at';- }- if (withoutPrefix === 'last_seen_at') {- return 'last_seen_at';+ if (PROFILE_SELECT_COLUMNS.includes(withoutPrefix)) {+ return sql.id(withoutPrefix, PROFILE_SELECT_COLUMNS);}if (withoutPrefix.startsWith('properties.')) {const propKey = withoutPrefix.replace(/^properties\./, '');- return `properties[${sqlstring.escape(propKey)}]`;+ return sql`properties[${sql.string(propKey)}]`;+ }+ return sql`id`;+}++/** The `properties` / `profile.properties` map prefixes, longest match wins. */+const PROPERTY_MAP_PREFIXES = ['properties', 'profile.properties'];++function matchPropertyMapPrefix(property: string): string | undefined {+ return PROPERTY_MAP_PREFIXES.find((pattern) =>+ property.startsWith(`${pattern}.`)+ );+}++/**+ * True when `getSelectPropertyKey` renders an ARRAY expression rather than a+ * scalar. V1 decided this by testing the rendered TEXT for a `%`, which is+ * reachable two ways: the wildcard branch emits `transformPropertyKey`'s+ * pattern, and a NON-wildcard key containing a literal `%` also matched. Both+ * are reproduced here — including the second, which is a V1 defect+ * (`properties.a%b` is treated as an array and fails at ClickHouse).+ */+export function isWildcardPropertyKey(rawProperty: string): boolean {+ const property = normalizeEventField(rawProperty);+ const match = matchPropertyMapPrefix(property);+ if (!match) {+ return false;+ }+ if (property.includes('*')) {+ return transformPropertyKey(property).includes('%');}- return 'id';+ return property.replace(new RegExp(`^${match}.`), '').includes('%');}export function getSelectPropertyKey(@@ -344,7 +400,7 @@ export function getSelectPropertyKey(* `_g` join), otherwise ClickHouse rejects with "ambiguous identifier".*/eventsAlias?: string-) {+): SqlFragment {// Map camelCase aliases (`referrerName` → `referrer_name`) and bare UTM// names (`utm_source` → `properties.__query.utm_source`) into their// canonical form before doing any pattern matching. The fallback at the@@ -356,15 +412,15 @@ export function getSelectPropertyKey(if (extractedCohortId && projectId) {const cohortAlias = getCohortAlias(extractedCohortId);- const inLabel = cohortName ? sqlstring.escape(cohortName) : "'In Cohort'";- const notInLabel = cohortName- ? sqlstring.escape(`Not ${cohortName}`)- : "'Not In Cohort'";- return `if(notEmpty(${cohortAlias}.profile_id), ${inLabel}, ${notInLabel})`;+ const inLabel = sql.string(cohortName ?? IN_COHORT_LABEL);+ const notInLabel = sql.string(+ cohortName ? `Not ${cohortName}` : NOT_IN_COHORT_LABEL+ );+ return sql`if(notEmpty(${sql.id(`${cohortAlias}.profile_id`)}), ${inLabel}, ${notInLabel})`;}if (property === 'has_profile') {- return "if(profile_id != device_id, 'true', 'false')";+ return sql`if(profile_id != device_id, 'true', 'false')`;}// Handle group properties — requires ARRAY JOIN + _g JOIN to be present in query@@ -372,27 +428,27 @@ export function getSelectPropertyKey(return getGroupPropertySql(property);}- const propertyPatterns = ['properties', 'profile.properties'];-- const match = propertyPatterns.find((pattern) =>- property.startsWith(`${pattern}.`)- );+ const match = matchPropertyMapPrefix(property);if (!match) {- return property;+ // Not a map access: a top-level column, or a name the caller has already+ // vetted with `isKnownEventField`. `sql.id` throws on anything else+ // rather than inlining it (ADR-013 R3).+ return sql.id(property);}// Only the events table's bare `properties` map needs aliasing —// `profile.properties` already routes through the profile join alias.- const aliasPrefix =- match === 'properties' && eventsAlias ? `${eventsAlias}.` : '';+ const map = sql.id(+ match === 'properties' && eventsAlias ? `${eventsAlias}.${match}` : match+ );if (property.includes('*')) {- return `arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(${aliasPrefix}${match}, ${sqlstring.escape(+ return sql`arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(${map}, ${sql.string(transformPropertyKey(property))})))`;}- return `${aliasPrefix}${match}['${property.replace(new RegExp(`^${match}.`), '')}']`;+ return sql`${map}[${sql.string(property.replace(new RegExp(`^${match}.`), ''))}]`;}// --- profile-property CTE narrowing (perf) ---------------------------------@@ -440,31 +496,18 @@ export function collectProfilePropertyKeys(refs: { name: string }[]): {export function profilePropertiesCteSelect(keys: string[],needsFullMap: boolean-): string {+): SqlFragment {+ // The alias has three dot-separated parts, so it is text, not `sql.id`.+ // `collectProfilePropertyKeys` already rejects the two characters that+ // could break out of the backticks.const cols = keys.map(- (k) => `properties[${sqlstring.escape(k)}] as \`profile.properties.${k}\``+ (k) =>+ sql`properties[${sql.string(k)}] as ${compiledText(`\`profile.properties.${k}\``)}`);if (needsFullMap || cols.length === 0) {- cols.push('properties as "profile.properties"');+ cols.push(sql`properties as "profile.properties"`);}- return cols.join(', ');-}--// Rewrite `profile.properties['<key>']` -> `` `profile.properties.<key>` ``-// for the narrowed keys. Matches the raw render from getSelectPropertyKey /-// the filter builders; never matches the CTE's own `properties['<key>']`,-// which has no `profile.` prefix. No-op when keys is empty.-export function rewriteProfilePropertyRefs(- sql: string,- keys: string[]-): string {- let out = sql;- for (const k of keys) {- out = out- .split(`profile.properties['${k}']`)- .join(`\`profile.properties.${k}\``);- }- return out;+ return sql.join(cols, ', ');}/**diff --git a/packages/core/src/modules/chart/src/filter-cast.ts b/packages/core/src/modules/chart/src/filter-cast.tsindex b218ade98..be03880b0 100644--- a/packages/core/src/modules/chart/src/filter-cast.ts+++ b/packages/core/src/modules/chart/src/filter-cast.ts@@ -3,54 +3,22 @@// half of `buildFilterWhere` (./table-filter-where.ts) and of// `./filter-where.ts` (the event-property compiler).//-// Two twins live here for the length of the P12 conversion: the `*Fragment`-// pair binds every value as a `{name:Type}` param and is what `filter-where.ts`-// calls (M12-002); `castSql` / `buildTypedClause` still render sqlstring-escaped-// TEXT for `table-filter-where.ts` and die with it (M12-003). The cast-// expressions must stay byte-identical between the two.+// Both filter compilers call the same pair now: `castFragment` and+// `buildTypedClauseFragment` bind every value as a `{name:Type}` param. The+// sqlstring-escaped text twins (`castSql` / `buildTypedClause`) died with+// `table-filter-where.ts`'s conversion in M12-003.import {type SqlFragment,type SqlSlot,sql,} from '@openpanel/db/src/clickhouse/sql';-import sqlstring from 'sqlstring';import type {IChartEventFilterOperator,IChartEventFilterValue,IChartFilterValueType,} from '../../report/report.constants';-/**- * Wrap a SQL expression (a column accessor or an already-escaped value literal)- * in the ClickHouse cast matching the filter's declared value type.- *- * `toString(...)` first so the helper works uniformly on String properties- * (`properties['x']`) and already-numeric columns (`duration`, `revenue`).- * The `*OrNull` variants mean an unparseable value becomes NULL (no match)- * instead of throwing and crashing the whole query — e.g. `toFloat64('abc')`- * would error, `toFloat64OrNull('abc')` yields NULL.- */-export function castSql(expr: string, type?: IChartFilterValueType): string {- switch (type) {- case 'number':- return `toFloat64OrNull(toString(${expr}))`;- case 'date':- // Parse with best-effort first, then truncate to a date. `toDateOrNull`- // is strict — it rejects loose formats like 'YYYY-MM-DD HH:MM' (no- // seconds) and returns NULL, which silently drops every row. Best-effort- // handles those, and toDate(NULL) stays NULL so bad values still no-match.- return `toDate(parseDateTimeBestEffortOrNull(toString(${expr})))`;- case 'datetime':- return `parseDateTimeBestEffortOrNull(toString(${expr}))`;- case 'boolean':- return `if(lower(trim(toString(${expr}))) IN ('true', '1', 'yes'), 1, 0)`;- case 'string':- case undefined:- return expr;- }-}-/*** True when a non-string cast should be applied. `string` and `undefined`* (legacy filters with no declared type) fall through to the existing raw@@ -64,35 +32,32 @@ export function hasTypedCast(// Equality + comparison operators where a declared cast type changes the SQL.// String-only operators (contains/startsWith/regex/…) and null checks are-// unaffected and keep their existing handling.-const TYPED_SQL_OPERATOR: Partial<Record<IChartEventFilterOperator, string>> = {- is: '=',- isNot: '!=',- gt: '>',- gte: '>=',- lt: '<',- lte: '<=',-};--// The same six operators as fragments. `sql`'s slots reject a bare string, so-// the operator has to arrive as SQL, not as text — and a closed literal map is-// the only place it can come from.-const TYPED_SQL_OPERATOR_FRAGMENT: Partial<- Record<IChartEventFilterOperator, SqlSlot>-> = {- is: sql`=`,- isNot: sql`!=`,- gt: sql`>`,- gte: sql`>=`,- lt: sql`<`,- lte: sql`<=`,-};+// unaffected and keep their existing handling. `sql`'s slots reject a bare+// string, so the operator arrives as SQL, from a closed literal map.+const TYPED_SQL_OPERATOR: Partial<Record<IChartEventFilterOperator, SqlSlot>> =+ {+ is: sql`=`,+ isNot: sql`!=`,+ gt: sql`>`,+ gte: sql`>=`,+ lt: sql`<`,+ lte: sql`<=`,+ };export function isTypedOperator(operator: IChartEventFilterOperator): boolean {return operator in TYPED_SQL_OPERATOR;}-/** {@link castSql} as a fragment. Keep the emitted expressions identical. */+/**+ * Wrap a SQL expression (a column accessor or a bound value) in the ClickHouse+ * cast matching the filter's declared value type.+ *+ * `toString(...)` first so the helper works uniformly on String properties+ * (`properties['x']`) and already-numeric columns (`duration`, `revenue`).+ * The `*OrNull` variants mean an unparseable value becomes NULL (no match)+ * instead of throwing and crashing the whole query — e.g. `toFloat64('abc')`+ * would error, `toFloat64OrNull('abc')` yields NULL.+ */export function castFragment(expr: SqlSlot,type?: IChartFilterValueType@@ -133,41 +98,21 @@ function typedValueParam(value: IChartEventFilterValue): SqlSlot {/*** Build a parenthesized comparison clause where both the column expression and- * every value are cast to `type`. `leftExpr` is the raw column accessor (e.g.+ * every value are cast to `type`. `leftExpr` is the column accessor (e.g.* `e.properties['cook']`, a bare column name, or `x` inside an arrayExists- * lambda). Values are escaped here.+ * lambda). Values are bound here.** `is`/`gt`/`gte`/`lt`/`lte` OR the per-value predicates together (match any);* `isNot` ANDs them (must differ from all), matching the NOT-IN semantics of* the untyped path.*/-export function buildTypedClause(- leftExpr: string,- operator: IChartEventFilterOperator,- value: IChartEventFilterValue[],- type: IChartFilterValueType-): string {- const sqlOp = TYPED_SQL_OPERATOR[operator] ?? '=';- const left = castSql(leftExpr, type);- const joiner = operator === 'isNot' ? ' AND ' : ' OR ';- return `(${value- .map((val) => {- const escaped = sqlstring.escape(- typeof val === 'string' ? val.trim() : val- );- return `${left} ${sqlOp} ${castSql(escaped, type)}`;- })- .join(joiner)})`;-}--/** {@link buildTypedClause} with every value bound instead of escaped. */export function buildTypedClauseFragment(leftExpr: SqlSlot,operator: IChartEventFilterOperator,value: IChartEventFilterValue[],type: IChartFilterValueType): SqlFragment {- const sqlOp = TYPED_SQL_OPERATOR_FRAGMENT[operator] ?? sql`=`;+ const sqlOp = TYPED_SQL_OPERATOR[operator] ?? sql`=`;const left = castFragment(leftExpr, type);const joiner = operator === 'isNot' ? ' AND ' : ' OR ';return sql`(${sql.join(diff --git a/packages/core/src/modules/chart/src/filter-where.ts b/packages/core/src/modules/chart/src/filter-where.tsindex 98e2ee69a..ec4087513 100644--- a/packages/core/src/modules/chart/src/filter-where.ts+++ b/packages/core/src/modules/chart/src/filter-where.ts@@ -2,9 +2,8 @@// V1's event filter compiler (`getEventFiltersWhereClause`), converted onto the// `sql` tag (M12-002): every VALUE binds as a `{name:Type}` param and every// identifier goes through `sql.id` or a static fragment. The column expression-// for a `properties.*` / `group.*` filter still comes from field-resolution.ts,-// which renders text until M12-003 converts it — that is the only thing left-// crossing `compiled.ts`.+// for a `properties.*` / `group.*` filter comes from field-resolution.ts, which+// returns a fragment of its own since M12-003 and is interpolated directly.import {type SqlFragment,@@ -14,7 +13,6 @@ import {import { stripLeadingAndTrailingSlashes } from '../../../shared/string';import type { IChartEventFilter } from '../../report/report.constants';import { getCohortIds } from '../../report/report.constants';-import { compiledText } from './compiled';import {CHART_TABLE,EVENT_FIELD_ALIASES,@@ -22,6 +20,7 @@ import {getGroupPropertySql,getSelectPropertyKey,isNumericColumn,+ isWildcardPropertyKey,normalizeEventField,} from './field-resolution';import {@@ -141,7 +140,7 @@ export function getEventFiltersWhereClause(// Handle group. prefixed filters (requires ARRAY JOIN + _g JOIN in query)if (name.startsWith('group.') && projectId) {- const whereFrom = compiledText(getGroupPropertySql(name));+ const whereFrom = getGroupPropertySql(name);if (hasTypedCast(filter.type) && isTypedOperator(operator)) {where[id] = buildTypedClauseFragment(whereFrom,@@ -232,15 +231,14 @@ export function getEventFiltersWhereClause(name.startsWith('properties.') ||name.startsWith('profile.properties.')) {- const propertyKey = getSelectPropertyKey(+ const whereFrom = getSelectPropertyKey(name,undefined,undefined,undefined,eventsAlias);- const isWildcard = propertyKey.includes('%');- const whereFrom = compiledText(propertyKey);+ const isWildcard = isWildcardPropertyKey(name);// Typed cast (number/date/datetime/boolean) short-circuit. Casts both the// column and each value so e.g. `>= '2019-01-01'` compares as datesdiff --git a/packages/core/src/modules/chart/src/funnel.sql.test.ts b/packages/core/src/modules/chart/src/funnel.sql.test.tsindex 78754b722..db975396b 100644--- a/packages/core/src/modules/chart/src/funnel.sql.test.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.test.ts@@ -91,11 +91,35 @@ function normalize(query: string): string {interface Rendered {sql: string;params: Record<string, unknown>;+ /**+ * `sql` with every placeholder substituted back to the literal V1 emitted.+ * Since M12-003 the field resolver binds `properties[<key>]` keys and cohort+ * labels too, so an assertion about the SHAPE of the expression reads this.+ */+ text: string;+}++const PLACEHOLDER = /\{(p\d+):[^}]+\}/g;++function literal(value: unknown): string {+ if (Array.isArray(value)) {+ return `(${value.map(literal).join(', ')})`;+ }+ if (typeof value === 'string') {+ return `'${value.replace(/'/g, "\\'")}'`;+ }+ return String(value);}function render(fragment: SqlFragment): Rendered {const { query, query_params } = fragment.toStatement();- return { sql: normalize(query), params: query_params };+ return {+ sql: normalize(query),+ params: query_params,+ text: query.replace(PLACEHOLDER, (_match, name: string) =>+ literal(query_params[name])+ ),+ };}async function explain(fragment: SqlFragment): Promise<void> {@@ -142,6 +166,9 @@ async function chartStatement(overrides: BaseOverrides = {}) {const chartSql = async (breakdowns: IChartBreakdown[]) =>render(await chartStatement({ breakdowns })).sql;+const chartText = async (breakdowns: IChartBreakdown[]) =>+ render(await chartStatement({ breakdowns })).text;+const originalNonStrict = process.env.FUNNEL_NON_STRICT_ORDERING;function setNonStrictOrdering(value: string | undefined) {if (value === undefined) {@@ -167,11 +194,11 @@ describe('funnel.sql / buildFunnelBase — profile breakdowns', () => {const statement = await profilesStatement({breakdowns: [breakdown('profile.properties.plan')],});- const { sql } = render(statement);+ const { sql, text } = render(statement);// The breakdown is narrowed to a scalar alias selected by the profile// join, so both the join and the aliased column must exist.- expect(sql).toContain("properties['plan'] as `profile.properties.plan`");+ expect(text).toContain("properties['plan'] as `profile.properties.plan`");expect(sql).toMatch(/as profile/);expect(sql).toContain('profile.id = events.profile_id');await explain(statement);@@ -221,13 +248,14 @@ describe('funnel.sql / buildFunnelBase — cohort breakdowns', () => {const statement = await profilesStatement({breakdowns: [breakdown(`cohort:${COHORT_ID}`)],});- const { sql } = render(statement);+ const { sql, text } = render(statement);// The breakdown renders `cohort_<id>.profile_id`, so its join must exist.const alias = `cohort_${COHORT_ID.replace(/-/g, '_')}`;expect(sql).toContain(`${alias}.profile_id`);expect(sql).toContain(`AS ${alias}`);- expect(sql).toContain('Power users');+ // The cohort label is a bound value now.+ expect(text).toContain('Power users');await explain(statement);});});@@ -331,7 +359,9 @@ describe('funnel.sql / buildFunnelBase — breakdown attribution', () => {// sequence never connects and downstream steps show 0.it('attributes event-property breakdowns at the entry step', async () => {const sql = await chartSql([breakdown('properties.experiment')]);- expect(sql).toContain("argMinIf(properties['experiment'], created_at,");+ expect(await chartText([breakdown('properties.experiment')])).toContain(+ "argMinIf(properties['experiment'], created_at,"+ );// The windowFunnel aggregation groups by the primary key only; b_0 is an// aggregate, not a grouping key. (The outer chart GROUP BY level, b_0 is// unaffected.)@@ -419,17 +449,17 @@ describe('funnel.sql / profile-property narrowing', () => {series: seriesWithProfileFilter,breakdowns: [breakdown('profile.properties.experiment')],});- const { sql } = render(statement);+ const { text } = render(statement);- expect(sql).toContain("properties['plan'] as `profile.properties.plan`");- expect(sql).toContain(+ expect(text).toContain("properties['plan'] as `profile.properties.plan`");+ expect(text).toContain("properties['experiment'] as `profile.properties.experiment`");- expect(sql).not.toContain('properties as "profile.properties"');+ expect(text).not.toContain('properties as "profile.properties"');// Conditions (windowFunnel + pre-filter) and the breakdown expression are// rewritten to the scalar aliases.- expect(sql).not.toContain("profile.properties['plan']");- expect(sql).not.toContain("profile.properties['experiment']");+ expect(text).not.toContain("profile.properties['plan']");+ expect(text).not.toContain("profile.properties['experiment']");});it('leaves funnels without profile-property refs untouched', async () => {diff --git a/packages/core/src/modules/chart/src/funnel.sql.ts b/packages/core/src/modules/chart/src/funnel.sql.tsindex 29aa3105f..b1306ec34 100644--- a/packages/core/src/modules/chart/src/funnel.sql.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.ts@@ -27,11 +27,7 @@ import type {IChartBreakdown,IChartEvent,} from '../../report/report.constants';-import {- compiledText,- compiledTextWithProfileRefs,- fragmentWithProfileRefs,-} from './compiled';+import { compiledText, fragmentWithProfileRefs } from './compiled';import {buildInlineCohortJoin,CHART_TABLE,@@ -53,6 +49,9 @@ export type FunnelGroup = (typeof FUNNEL_GROUPS)[number];/** Display label for null/empty breakdown values (e.g. property not set). */export const EMPTY_BREAKDOWN_LABEL = 'Not set';+/** The funnel CTE's events alias — `getSelectPropertyKey` needs the same one. */+const EVENTS_ALIAS = 'events';+/** Profile columns the funnel's profiles CTE may expose beyond `properties`. */const JOINABLE_PROFILE_COLUMNS = ['email',@@ -177,7 +176,7 @@ function breakdownSelects(const cohortName = cohortId? input.cohortMetadata.get(cohortId)?.name: undefined;- const expression = compiledTextWithProfileRefs(+ const expression = fragmentWithProfileRefs(getSelectPropertyKey(breakdown.name,input.projectId,@@ -207,7 +206,7 @@ function profileCteColumns(input: FunnelBaseInput,profileFilters: string[],profileKeys: { keys: string[]; needsFullMap: boolean }-): string[] {+): SqlFragment[] {const profileBreakdowns = input.breakdowns.filter((breakdown) =>breakdown.name.startsWith('profile.'));@@ -229,7 +228,12 @@ function profileCteColumns(}}- const columns = Array.from(fields);+ // ADR-013 R3: the breakdown-derived names are vetted above, the+ // filter-derived ones are not — V1 spliced both unchecked, `sql.id`+ // validates the shape and throws instead of inlining.+ const columns: SqlFragment[] = Array.from(fields).map((field) =>+ sql.id(field)+ );const referencesProperties =profileFilters.some((filter) => filter.startsWith('properties')) ||profileBreakdowns.some((breakdown) =>@@ -307,7 +311,7 @@ export function funnelBase(input: FunnelBaseInput): FunnelBase {const columns = profileCteColumns(input, profileFilters, profileKeys);const profileJoin =columns.length > 0- ? sql` LEFT JOIN (SELECT ${compiledText(columns.join(', '))} FROM ${sql.id(CHART_TABLE.profiles)} FINAL+ ? sql` LEFT JOIN (SELECT ${sql.join(columns, ', ')} FROM ${sql.id(CHART_TABLE.profiles)} FINALWHERE project_id = ${sql.string(projectId)}) as profile ON profile.id = events.profile_id`: sql.empty;const groupJoin = needsGroupArrayJoin@@ -320,7 +324,7 @@ export function funnelBase(input: FunnelBaseInput): FunnelBase {cohortIds.length > 0? sql` ${sql.join(cohortIds.map((cohortId) =>- compiledText(buildInlineCohortJoin(cohortId, projectId, 'events'))+ buildInlineCohortJoin(cohortId, projectId, EVENTS_ALIAS)),' ')}`diff --git a/packages/core/src/modules/chart/src/table-filter-where.test.ts b/packages/core/src/modules/chart/src/table-filter-where.test.tsindex 31f22e7cf..28f0052aa 100644--- a/packages/core/src/modules/chart/src/table-filter-where.test.ts+++ b/packages/core/src/modules/chart/src/table-filter-where.test.ts@@ -1,7 +1,11 @@/*** Unit tests for `buildFilterWhere`.*- * These are pure string tests — no ClickHouse needed. The interesting part is+ * No ClickHouse needed. Since M12-003 the compiler returns bound+ * `SqlFragment`s, so each clause is rendered through `toStatement()` and its+ * params substituted back in: what the assertions say is unchanged, a value+ * that used to appear as an escaped literal now appears in `query_params`.+ * The interesting part is* the `profile.*` branch: the field name arrives from the caller (saved* report, URL state, raw API call) and used to be concatenated into the SQL* text as-is, so a name that was not a column produced whatever SQL the caller@@ -12,6 +16,7 @@import { describe, expect, it } from 'bun:test';import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';+import type { SqlParamValue } from '@openpanel/db/src/clickhouse/sql';import type { IChartEventFilter } from '../../report/report.constants';import {buildFilterWhere,@@ -50,11 +55,55 @@ const filter = (...overrides,}) as IChartEventFilter;+const compile = (table: keyof typeof CONTEXTS, filters: IChartEventFilter[]) =>+ buildFilterWhere(filters, PROJECT_ID, CONTEXTS[table]!);++/**+ * Render every compiled clause with its params substituted back in, so the+ * expectations below stay the SQL a reader can paste into ClickHouse.+ */const build = (table: keyof typeof CONTEXTS,filters: IChartEventFilter[]-): Record<string, string> =>- buildFilterWhere(filters, PROJECT_ID, CONTEXTS[table]!);+): Record<string, string> => {+ const rendered: Record<string, string> = {};+ for (const [key, fragment] of Object.entries(compile(table, filters))) {+ rendered[key] = substitute(fragment.toStatement());+ }+ return rendered;+};++const paramsOf = (+ table: keyof typeof CONTEXTS,+ filters: IChartEventFilter[]+): Record<string, SqlParamValue>[] =>+ Object.values(compile(table, filters)).map(+ (fragment) => fragment.toStatement().query_params+ );++const PLACEHOLDER = /\{(p\d+):[^}]+\}/g;++function substitute({+ query,+ query_params,+}: {+ query: string;+ query_params: Record<string, SqlParamValue>;+}): string {+ return query.replace(PLACEHOLDER, (_match, name: string) =>+ literal(query_params[name])+ );+}++function literal(value: SqlParamValue | undefined): string {+ if (Array.isArray(value)) {+ return `(${value.map((item) => literal(item as SqlParamValue)).join(', ')})`;+ }+ if (typeof value === 'string') {+ return `'${value.replace(/'/g, "\\'")}'`;+ }+ return String(value);+}/** What `buildProfileClause` wraps `inner` in for a given table. */const profileWrap = (table: keyof typeof CONTEXTS, inner: string): string =>@@ -111,10 +160,13 @@ describe.each(TABLES)('buildFilterWhere on %s', (table) => {});it('escapes a quote in a properties key', () => {- const where = build(table, [+ const filters = [filter({ name: "profile.properties.pl'an", value: ['pro'] }),- ]);+ ];+ const where = build(table, filters);expect(where.f0).toBe(profileWrap(table, "properties['pl\\'an'] = 'pro'"));+ // The key is a bound param now, so the quote never reaches the SQL text.+ expect(Object.values(paramsOf(table, filters)[0]!)).toContain("pl'an");});it.each(REJECTED_NAMES)('drops the unknown profile field %j', (name) => {diff --git a/packages/core/src/modules/chart/src/table-filter-where.ts b/packages/core/src/modules/chart/src/table-filter-where.tsindex da48ccb9d..a2df18cc9 100644--- a/packages/core/src/modules/chart/src/table-filter-where.ts+++ b/packages/core/src/modules/chart/src/table-filter-where.ts@@ -1,26 +1,31 @@/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */-// Moved from packages/db/src/services/filter-where.service.ts (M8-005).-// V1's filter compiler for the sessions/profiles/events tables — distinct-// from `./filter-where.ts`'s `getEventFiltersWhereClause` (event-property-// filters). Still sqlstring-escaped text, not the `sql` tag: ADR-013 keeps-// the two filter compilers as they are ("two behaviours, not two builders")-// until every caller that splices their output stops using text builders.-// M10-003: the two symbols this file used to take from-// `@openpanel/db/src/clickhouse/client` (a module that constructs a-// ClickHouse client and a pino logger at import time) are now local — the-// module's own `./dates.formatClickhouseDate`, byte-identical to-// packages/db's non-`skipTime` branch, and `./field-resolution.CHART_TABLE`,-// which already carried all four physical table names used below.--import sqlstring from 'sqlstring';+// 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.+//+// 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.++import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import {getCohortIds,type IChartEventFilter,+ type IChartEventFilterValue,type IChartFilterValueType,} from '../../report/report.constants';import { formatClickhouseDate } from './dates';import { CHART_TABLE } from './field-resolution';-import { buildTypedClause, hasTypedCast, isTypedOperator } from './filter-cast';+import {+ buildTypedClauseFragment,+ hasTypedCast,+ isTypedOperator,+} from './filter-cast';export interface FilterTableContext {/** Outer query's primary table. */@@ -45,6 +50,9 @@ export interface FilterTableContext {endDate?: Date;}+/** One clause per surviving filter, keyed `f<index>` as V1 keyed them. */+export type CompiledTableFilters = Record<string, SqlFragment>;+/** Sentinel sessions columns that the UI may filter on directly. */const SESSION_NUMERIC_COLUMNS = new Set(['screen_view_count',@@ -53,25 +61,110 @@ const SESSION_NUMERIC_COLUMNS = new Set(['revenue',]);-function escape(value: string | number | boolean | null): string {- return sqlstring.escape(typeof value === 'string' ? value.trim() : value);+/** What `sessionColumnName` can return — `sql.id`'s closed set. */+const SESSION_FILTER_COLUMNS = ['is_bounce', ...SESSION_NUMERIC_COLUMNS];++/**+ * The type ClickHouse infers for an integer literal, narrowest first: `5` is+ * UInt8, `300` UInt16, `-5` Int8. Ordered so the first row whose range+ * contains the value wins; a negative value never matches an unsigned row and+ * vice versa.+ */+const INTEGER_LITERAL_TYPES = [+ { min: 0n, limit: 2n ** 8n, type: 'UInt8' },+ { min: 0n, limit: 2n ** 16n, type: 'UInt16' },+ { min: 0n, limit: 2n ** 32n, type: 'UInt32' },+ { min: 0n, limit: 2n ** 64n, type: 'UInt64' },+ { min: -(2n ** 7n), limit: 0n, type: 'Int8' },+ { min: -(2n ** 15n), limit: 0n, type: 'Int16' },+ { min: -(2n ** 31n), limit: 0n, type: 'Int32' },+ { min: -(2n ** 63n), limit: 0n, type: 'Int64' },+] as const;++/** Everything the table above does not cover — fractions and huge magnitudes. */+const NON_INTEGER_LITERAL_TYPE = 'Float64';++const INTEGER_LITERAL_TEXT = /^-?\d+$/;++/**+ * The integer ClickHouse would parse out of the text V1 emitted, or null when+ * that text is not an integer literal — a fraction, or a magnitude large+ * enough that `String` switches to exponent notation.+ */+function integerLiteralDigits(value: number): bigint | null {+ const text = String(value);+ return INTEGER_LITERAL_TEXT.test(text) ? BigInt(text) : null;+}++/**+ * V1 inlined a numeric filter value and let ClickHouse infer the literal's+ * type; a bound param has to declare one, so declare the one V1's literal+ * had. Declaring `Float64` for every number would bind a *different constant*+ * — visible wherever the comparand's type takes part in type resolution, and+ * in the `NO_COMMON_TYPE` message when a numeric filter lands on a String+ * property (the proof's two error cases).+ *+ * `filter-cast.ts`'s twin needs none of this: there every value is wrapped in+ * `toFloat64OrNull(toString(…))` or a sibling cast, which erases the declared+ * type before anything else can observe it.+ */+function numericLiteralType(value: number): string {+ const digits = integerLiteralDigits(value);+ const fit =+ digits === null+ ? undefined+ : INTEGER_LITERAL_TYPES.find(+ ({ min, limit }) => digits >= min && digits < limit+ );+ return fit?.type ?? NON_INTEGER_LITERAL_TYPE;+}++/**+ * Bind one filter value the way `sqlstring.escape` rendered it: a string is a+ * trimmed quoted literal, a number a numeric literal of the type ClickHouse+ * would have inferred for it, a boolean `true`/`false` and `null` the SQL+ * keyword NULL — which only `Nullable` reproduces, since a `String` param+ * bound to null arrives as the empty string.+ */+function valueParam(value: IChartEventFilterValue) {+ if (value === null) {+ return sql.nullable('String', null);+ }+ if (typeof value === 'number') {+ return sql.param(numericLiteralType(value), value);+ }+ if (typeof value === 'boolean') {+ return sql.bool(value);+ }+ return sql.string(value.trim());}-function trimVal(value: string | number | boolean | null): string {+/** V1's `trimVal` — what a LIKE pattern is built from. */+function trimVal(value: IChartEventFilterValue): string {return typeof value === 'string' ? value.trim() : String(value);}+/** Every value as one `Array(String)`, for the `IN` / `NOT IN` branches. */+function valueArray(value: IChartEventFilterValue[]) {+ return sql.array('String', value.map(trimVal));+}++/** V1's `(<a> OR <b>)` / `(<a> AND <b>)` — the parenthesised join. */+function joined(clauses: SqlFragment[], separator: ' OR ' | ' AND ') {+ return sql`(${sql.join(clauses, separator)})`;+}+/*** Build a WHERE-clause fragment for a single non-array column. Mirrors the* operator set used by `getEventFiltersWhereClause` so behaviour stays* consistent across surfaces.*/function compileScalarClause(- column: string,+ column: SqlFragment,operator: IChartEventFilter['operator'],value: IChartEventFilter['value'],options: { numeric?: boolean; type?: IChartFilterValueType } = {}-): string | null {+): SqlFragment | null {if (value.length === 0 && operator !== 'isNull' && operator !== 'isNotNull') {return null;}@@ -79,97 +172,97 @@ function compileScalarClause(// Explicit cast type wins over the column-name `numeric` auto-detect. Casts// both the column and each value consistently (see filter-cast.ts).if (hasTypedCast(options.type) && isTypedOperator(operator)) {- return buildTypedClause(column, operator, value, options.type!);+ return buildTypedClauseFragment(column, operator, value, options.type!);}const numeric = options.numeric === true;+ // V1 wrapped BOTH sides in toFloat64 on a numeric column; the quoted+ // comparand fed to toFloat64 is the behaviour, so the value stays a String.+ const left = numeric ? sql`toFloat64(${column})` : column;+ const right = (val: IChartEventFilterValue) =>+ numeric ? sql`toFloat64(${valueParam(val)})` : valueParam(val);switch (operator) {case 'is': {if (numeric) {- return `(${value- .map((v) => `toFloat64(${column}) = toFloat64(${escape(v)})`)- .join(' OR ')})`;+ return joined(+ value.map((v) => sql`${left} = ${right(v)}`),+ ' OR '+ );}if (value.length === 1) {- return `${column} = ${escape(value[0]!)}`;+ return sql`${column} = ${valueParam(value[0]!)}`;}- return `${column} IN (${value.map(escape).join(', ')})`;+ return sql`${column} IN ${valueArray(value)}`;}case 'isNot': {if (numeric) {- return `(${value- .map((v) => `toFloat64(${column}) != toFloat64(${escape(v)})`)- .join(' OR ')})`;+ return joined(+ value.map((v) => sql`${left} != ${right(v)}`),+ ' OR '+ );}if (value.length === 1) {- return `${column} != ${escape(value[0]!)}`;+ return sql`${column} != ${valueParam(value[0]!)}`;}- return `${column} NOT IN (${value.map(escape).join(', ')})`;+ return sql`${column} NOT IN ${valueArray(value)}`;}case 'contains': {- return `(${value- .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`)- .join(' OR ')})`;+ return joined(+ value.map((v) => sql`${column} ILIKE ${sql.string(`%${trimVal(v)}%`)}`),+ ' OR '+ );}case 'doesNotContain': {- return `(${value- .map(- (v) => `${column} NOT ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`- )- .join(' AND ')})`;+ return joined(+ value.map(+ (v) => sql`${column} NOT ILIKE ${sql.string(`%${trimVal(v)}%`)}`+ ),+ ' AND '+ );}case 'startsWith': {- return `(${value- .map((v) => `${column} ILIKE ${sqlstring.escape(`${trimVal(v)}%`)}`)- .join(' OR ')})`;+ return joined(+ value.map((v) => sql`${column} ILIKE ${sql.string(`${trimVal(v)}%`)}`),+ ' OR '+ );}case 'endsWith': {- return `(${value- .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}`)}`)- .join(' OR ')})`;+ return joined(+ value.map((v) => sql`${column} ILIKE ${sql.string(`%${trimVal(v)}`)}`),+ ' OR '+ );}case 'regex': {- return `(${value- .map((v) => `match(${column}, ${escape(v)})`)- .join(' OR ')})`;+ return joined(+ value.map((v) => sql`match(${column}, ${valueParam(v)})`),+ ' OR '+ );}case 'isNull':- return `(${column} = '' OR ${column} IS NULL)`;+ return sql`(${column} = '' OR ${column} IS NULL)`;case 'isNotNull':- return `(${column} != '' AND ${column} IS NOT NULL)`;- case 'gt': {- return `(${value- .map(- (v) =>- `${numeric ? `toFloat64(${column})` : column} > ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`- )- .join(' OR ')})`;- }- case 'lt': {- return `(${value- .map(- (v) =>- `${numeric ? `toFloat64(${column})` : column} < ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`- )- .join(' OR ')})`;- }- case 'gte': {- return `(${value- .map(- (v) =>- `${numeric ? `toFloat64(${column})` : column} >= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`- )- .join(' OR ')})`;- }- case 'lte': {- return `(${value- .map(- (v) =>- `${numeric ? `toFloat64(${column})` : column} <= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`- )- .join(' OR ')})`;- }+ return sql`(${column} != '' AND ${column} IS NOT NULL)`;+ case 'gt':+ return joined(+ value.map((v) => sql`${left} > ${right(v)}`),+ ' OR '+ );+ case 'lt':+ return joined(+ value.map((v) => sql`${left} < ${right(v)}`),+ ' OR '+ );+ case 'gte':+ return joined(+ value.map((v) => sql`${left} >= ${right(v)}`),+ ' OR '+ );+ case 'lte':+ return joined(+ value.map((v) => sql`${left} <= ${right(v)}`),+ ' OR '+ );}return null;@@ -178,10 +271,10 @@ function compileScalarClause(/*** Profiles columns a `profile.<field>` filter may resolve to. Anything else is* not a column name and must not reach the SQL text. Kept in sync with- * `getProfilePropertySelect` in chart.service.ts, which lists the same set for- * the SELECT side.+ * `getProfilePropertySelect` in field-resolution.ts, which lists the same set+ * for the SELECT side.*/-const PROFILE_COLUMNS = new Set([+const PROFILE_COLUMNS = ['id','first_name','last_name',@@ -189,7 +282,10 @@ const PROFILE_COLUMNS = new Set(['avatar','created_at','last_seen_at',-]);+];++/** Group fields that are columns rather than a `properties` lookup. */+const GROUP_COLUMNS = ['name', 'type', 'id'];/*** Translate `profile.<field>` into the SQL accessor used when querying the@@ -197,14 +293,14 @@ const PROFILE_COLUMNS = new Set([* `profile.properties.<key>` maps to the JSON `properties[key]` lookup.* Returns null for a field that is neither, so the caller can drop the filter.*/-function profileColumnSql(name: string): string | null {+function profileColumnSql(name: string): SqlFragment | null {const withoutPrefix = name.replace(/^profile\./, '');if (withoutPrefix.startsWith('properties.')) {const key = withoutPrefix.replace(/^properties\./, '');- return `properties[${sqlstring.escape(key)}]`;+ return sql`properties[${sql.string(key)}]`;}- if (PROFILE_COLUMNS.has(withoutPrefix)) {- return withoutPrefix;+ if (PROFILE_COLUMNS.includes(withoutPrefix)) {+ return sql.id(withoutPrefix, PROFILE_COLUMNS);}return null;}@@ -213,24 +309,20 @@ function profileColumnSql(name: string): string | null {* Translate `group.<field>` into the SQL accessor used when querying the* groups table directly (no join alias).*/-function groupColumnSql(name: string): string {+function groupColumnSql(name: string): SqlFragment {const withoutPrefix = name.replace(/^group\./, '');- if (- withoutPrefix === 'name' ||- withoutPrefix === 'type' ||- withoutPrefix === 'id'- ) {- return withoutPrefix;+ if (GROUP_COLUMNS.includes(withoutPrefix)) {+ return sql.id(withoutPrefix, GROUP_COLUMNS);}if (withoutPrefix.startsWith('properties.')) {const key = withoutPrefix.replace(/^properties\./, '');- return `properties[${sqlstring.escape(key)}]`;+ return sql`properties[${sql.string(key)}]`;}- return 'id';+ return sql`id`;}/** Translate `session.<field>` to the underlying sessions column. */-function sessionColumnSql(name: string): string | null {+function sessionColumnName(name: string): string | null {const withoutPrefix = name.replace(/^session\./, '');if (withoutPrefix === 'is_bounce') {return 'is_bounce';@@ -246,7 +338,7 @@ function buildCohortClause(filter: IChartEventFilter,projectId: string,ctx: FilterTableContext-): string | null {+): SqlFragment | null {// `getCohortIds` normalizes the legacy single-value `cohortId` field and// the newer `cohortIds` array into one list. Falls back to extracting the// id from the `cohort:<id>` filter name when neither is set (older URL@@ -258,17 +350,18 @@ function buildCohortClause(if (cohortIds.length === 0) {return null;}- const negate = filter.operator === 'notInCohort';- const op = negate ? 'NOT IN' : 'IN';- const escapedIds = cohortIds.map((id) => sqlstring.escape(id)).join(', ');- return `${ctx.profileIdExpr} ${op} (SELECT profile_id FROM ${CHART_TABLE.cohortMembers} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;+ const profileId = sql.id(ctx.profileIdExpr);+ const members = sql`(SELECT profile_id FROM ${sql.id(CHART_TABLE.cohortMembers)} FINAL WHERE cohort_id IN ${sql.array('String', cohortIds)} AND project_id = ${sql.string(projectId)})`;+ return filter.operator === 'notInCohort'+ ? sql`${profileId} NOT IN ${members}`+ : sql`${profileId} IN ${members}`;}function buildGroupClause(filter: IChartEventFilter,projectId: string,ctx: FilterTableContext-): string | null {+): SqlFragment | null {if (!ctx.groupsExpr) {return null;}@@ -279,20 +372,20 @@ function buildGroupClause(if (!inner) {return null;}- const projectClause = `project_id = ${sqlstring.escape(projectId)}`;- return `arrayExists(g -> g IN (SELECT id FROM ${CHART_TABLE.groups} FINAL WHERE ${projectClause} AND ${inner}), ${ctx.groupsExpr})`;+ return sql`arrayExists(g -> g IN (SELECT id FROM ${sql.id(CHART_TABLE.groups)} FINAL WHERE project_id = ${sql.string(projectId)} AND ${inner}), ${sql.id(ctx.groupsExpr)})`;}function buildProfileClause(filter: IChartEventFilter,projectId: string,ctx: FilterTableContext-): string | null {+): SqlFragment | null {+ const name = filter.name.replace(/^profile\./, '');const column = profileColumnSql(filter.name);if (!column) {return null;}- const numeric = column === 'created_at' || column === 'last_seen_at';+ const numeric = name === 'created_at' || name === 'last_seen_at';const inner = compileScalarClause(column, filter.operator, filter.value, {numeric,type: filter.type,@@ -303,14 +396,14 @@ function buildProfileClause(if (ctx.selfTable === 'profiles') {return inner;}- return `${ctx.profileIdExpr} IN (SELECT id FROM ${CHART_TABLE.profiles} FINAL WHERE project_id = ${sqlstring.escape(projectId)} AND ${inner})`;+ return sql`${sql.id(ctx.profileIdExpr)} IN (SELECT id FROM ${sql.id(CHART_TABLE.profiles)} FINAL WHERE project_id = ${sql.string(projectId)} AND ${inner})`;}function buildSessionClause(filter: IChartEventFilter,projectId: string,ctx: FilterTableContext-): string | null {+): SqlFragment | null {if (ctx.selfTable !== 'sessions') {return null;}@@ -320,19 +413,18 @@ function buildSessionClause(if (filter.value.length === 0) {return null;}- const inClause =+ const nameClause =filter.value.length === 1- ? `= ${escape(filter.value[0]!)}`- : `IN (${filter.value.map(escape).join(', ')})`;- const op = filter.operator === 'isNot' ? 'NOT IN' : 'IN';- const dateScope: string[] = [];- if (ctx.startDate && ctx.endDate) {- dateScope.push(- `toDate(created_at) BETWEEN toDate('${formatClickhouseDate(ctx.startDate)}') AND toDate('${formatClickhouseDate(ctx.endDate)}')`- );- }- const scopeSql = dateScope.length ? `AND ${dateScope.join(' AND ')} ` : '';- return `id ${op} (SELECT DISTINCT session_id FROM ${CHART_TABLE.events} WHERE project_id = ${sqlstring.escape(projectId)} ${scopeSql}AND name ${inClause})`;+ ? sql`= ${valueParam(filter.value[0]!)}`+ : sql`IN ${valueArray(filter.value)}`;+ const dateScope =+ ctx.startDate && ctx.endDate+ ? sql`AND toDate(created_at) BETWEEN toDate(${sql.string(formatClickhouseDate(ctx.startDate))}) AND toDate(${sql.string(formatClickhouseDate(ctx.endDate))}) `+ : sql.empty;+ const members = sql`(SELECT DISTINCT session_id FROM ${sql.id(CHART_TABLE.events)} WHERE project_id = ${sql.string(projectId)} ${dateScope}AND name ${nameClause})`;+ return filter.operator === 'isNot'+ ? sql`id NOT IN ${members}`+ : sql`id IN ${members}`;}if (fieldName === 'is_bounce') {@@ -343,40 +435,45 @@ function buildSessionClause(typeof v === 'boolean' ? v : String(v).toLowerCase() === 'true');const truthy = filter.operator === 'isNot' ? !wants : wants;- return `is_bounce = ${truthy ? 1 : 0}`;+ return truthy ? sql`is_bounce = 1` : sql`is_bounce = 0`;}- const column = sessionColumnSql(filter.name);+ const column = sessionColumnName(filter.name);if (!column) {return null;}- return compileScalarClause(column, filter.operator, filter.value, {- numeric: SESSION_NUMERIC_COLUMNS.has(column),- type: filter.type,- });+ return compileScalarClause(+ sql.id(column, SESSION_FILTER_COLUMNS),+ filter.operator,+ filter.value,+ {+ numeric: SESSION_NUMERIC_COLUMNS.has(column),+ type: filter.type,+ }+ );}/**- * Translate `IChartEventFilter[]` into a WHERE-clause record suitable for- * merging into `createSqlBuilder().sb.where`. Handles cohort / group / profile- * / session prefixes. Event-property (`properties.*`) filters are ignored on- * non-events tables — they require a subquery on the events table that is- * better expressed as a cohort.+ * Translate `IChartEventFilter[]` into a WHERE-clause record of bound+ * fragments. Handles cohort / group / profile / session prefixes.+ * Event-property (`properties.*`) filters are ignored on non-events tables —+ * they require a subquery on the events table that is better expressed as a+ * cohort.*/export function buildFilterWhere(filters: IChartEventFilter[],projectId: string,ctx: FilterTableContext-): Record<string, string> {- const where: Record<string, string> = {};+): CompiledTableFilters {+ const where: CompiledTableFilters = {};filters.forEach((filter, index) => {const id = `f${index}`;// Callers concatenate these fragments with AND and no grouping, so each// fragment is parenthesized here to keep a top-level OR inside it from// rebinding the surrounding conditions.- const set = (clause: string | null) => {+ const set = (clause: SqlFragment | null) => {if (clause) {- where[id] = `(${clause})`;+ where[id] = sql`(${clause})`;}};diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.tsindex bb86bdab7..1bff02c63 100644--- a/packages/core/src/modules/cohort/cohort.service.ts+++ b/packages/core/src/modules/cohort/cohort.service.ts@@ -35,6 +35,7 @@// module's own rpc mutations and its cron fragment).import type { ClickHouseSettings } from '@clickhouse/client';+import { sql } from '@openpanel/db/src/clickhouse/sql';import sqlstring from 'sqlstring';import type { ServiceDeps } from '../../services';import { chQuery } from '../../shared/ch-query';@@ -809,15 +810,15 @@ export async function listCohortMemberProfiles(}): Promise<{ data: IServiceProfile[]; count: number }> {const { buildFilterWhere } = await import('../chart/src/table-filter-where');- const { profileSearchSql } = await import('../profile/profile.service');+ const { profileSearchCondition } = await import('../profile/profile.service');// M10-005: `getProfiles` takes `ServiceDeps` now and this function has none// — packages/trpc's cohort router still calls it bare — so it reaches the// v1-compat spelling. Converting this module is its own task.const { getProfiles } = await import('../../v1-compat');const offset = Math.max(0, (cursor ?? 0) * take);- const searchClause = profileSearchSql(search);- const searchCondition = searchClause ? `AND ${searchClause}` : '';+ const searchClause = profileSearchCondition(search);+ const searchCondition = searchClause ? sql`AND ${searchClause}` : sql.empty;const extraConditions = filters?.length? Object.values(@@ -829,24 +830,27 @@ export async function listCohortMemberProfiles(): [];const extraConditionSql = extraConditions.length- ? `AND ${extraConditions.join(' AND ')}`- : '';+ ? sql`AND ${sql.join(extraConditions, ' AND ')}`+ : sql.empty;+ // M12-003: converted with `buildFilterWhere`, which now returns fragments.+ // V1's plain `IN (subquery)` on the Distributed `cohort_members` is kept as+ // written (docs/ENVIRONMENT.md).const rows = await chQuery<{ id: string; total_count: number }>(deps,- `+ sql`SELECT id, count() OVER () AS total_count- FROM ${TABLE.profiles} FINAL- WHERE project_id = ${sqlstring.escape(projectId)}+ FROM ${sql.id(TABLE.profiles)} FINAL+ WHERE project_id = ${sql.string(projectId)}AND id IN (- SELECT profile_id FROM ${TABLE.cohortMembers} FINAL- WHERE cohort_id = ${sqlstring.escape(cohortId)}- AND project_id = ${sqlstring.escape(projectId)}+ SELECT profile_id FROM ${sql.id(TABLE.cohortMembers)} FINAL+ WHERE cohort_id = ${sql.string(cohortId)}+ AND project_id = ${sql.string(projectId)})${searchCondition}${extraConditionSql}ORDER BY created_at DESC- LIMIT ${take} OFFSET ${offset}+ LIMIT ${sql.uint64(take)} OFFSET ${sql.uint64(offset)}`);diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.tsindex 614cd45d3..696b7e28a 100644--- a/packages/core/src/modules/event/event.service.ts+++ b/packages/core/src/modules/event/event.service.ts@@ -65,10 +65,7 @@ import {topOriginsQuery,topPagesQuery,} from './src/event.sql';-import {- type CompiledFilterClauses,- compiledFilterClauses,-} from './src/filter-clauses';+import type { CompiledFilterClauses } from './src/filter-clauses';export {EVENT_LIST_COLUMNS,@@ -1092,12 +1089,10 @@ export async function queryEventsCore(let filterClauses: CompiledFilterClauses = {};if (input.filters?.length) {const { buildFilterWhere } = await loadFilterCompiler();- filterClauses = compiledFilterClauses(- buildFilterWhere(- input.filters,- input.projectId,- QUERY_EVENTS_FILTER_TARGET- )+ filterClauses = buildFilterWhere(+ input.filters,+ input.projectId,+ QUERY_EVENTS_FILTER_TARGET);}return chQuery<IClickhouseEvent>(diff --git a/packages/core/src/modules/event/src/event.sql.test.ts b/packages/core/src/modules/event/src/event.sql.test.tsindex 8e9d44ca5..e9ad8fa24 100644--- a/packages/core/src/modules/event/src/event.sql.test.ts+++ b/packages/core/src/modules/event/src/event.sql.test.ts@@ -5,6 +5,7 @@// (these run offline); it is recorded per query in event.sql.proof.md.import { describe, expect, test } from 'bun:test';+import { sql } from '@openpanel/db/src/clickhouse/sql';import {botEventsCountQuery,botEventsQuery,@@ -21,7 +22,6 @@ import {topOriginsQuery,topPagesQuery,} from './event.sql';-import { compiledFilterClauses } from './filter-clauses';const PROJECT_ID = 'proj-1';const HOSTILE = "x' OR 1=1 --";@@ -118,7 +118,7 @@ describe('eventListQuery', () => {startDate: START,endDate: END,events: ['a', HOSTILE],- filterClauses: compiledFilterClauses({ f0: "(path = '/')" }),+ filterClauses: { f0: sql`(path = '/')` },conversionNames: ['signup'],}).toStatement();@@ -182,7 +182,7 @@ describe('eventsCountQuery', () => {startDate: START,endDate: END,events: ['a'],- filterClauses: compiledFilterClauses({ f0: "(path = '/')" }),+ filterClauses: { f0: sql`(path = '/')` },joins: NO_FILTER_JOINS,}).toStatement();@@ -302,7 +302,7 @@ describe('queryEventsQuery', () => {equals: { browser: 'Firefox', path: HOSTILE, country: 'SE' },properties: { [HOSTILE]: 'v' },dateRange: { start: '2026-08-01 00:00:00', end: '2026-08-31 23:59:59' },- filterClauses: compiledFilterClauses({ f0: '(1 = 1)' }),+ filterClauses: { f0: sql`(1 = 1)` },limit: 10,}).toStatement();diff --git a/packages/core/src/modules/event/src/filter-clauses.ts b/packages/core/src/modules/event/src/filter-clauses.tsindex 3c6c0f28a..999840d48 100644--- a/packages/core/src/modules/event/src/filter-clauses.ts+++ b/packages/core/src/modules/event/src/filter-clauses.ts@@ -1,29 +1,15 @@// The ONE place this module splices pre-compiled filter SQL.//// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is V1's-// sessions/profiles/events-table filter compiler and still emits-// sqlstring-escaped SQL text; ADR-013 converts it in M12-003. Until then its-// output crosses into a fragment here — through the same `SqlFragment`-// constructor `sql.id` uses — so the bridge is one grep away from deletion-// when the compiler moves, rather than a `sql.raw()` that would outlive it.-// `getEventFiltersWhereClause` (../../chart/src/filter-where.ts) already-// returns fragments (M12-002) and needs no bridge.+// sessions/profiles/events-table filter compiler; it returns bound+// `SqlFragment`s since M12-003, as `getEventFiltersWhereClause`+// (../../chart/src/filter-where.ts) has since M12-002. Nothing is bridged any+// more — this file only assembles what the compiler already produced.-import { SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';export type CompiledFilterClauses = Record<string, SqlFragment>;-/** Bridge `buildFilterWhere`'s compiled TEXT into fragments. */-export function compiledFilterClauses(- clauses: Record<string, string>-): CompiledFilterClauses {- const compiled: CompiledFilterClauses = {};- for (const [key, clause] of Object.entries(clauses)) {- compiled[key] = new SqlFragment([clause], []);- }- return compiled;-}-/** Each compiled clause is already parenthesised by the compiler. */export function compiledFilterFragments(clauses: CompiledFilterClausesdiff --git a/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.tsindex a99a2bfc8..2b00202ab 100644--- a/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts+++ b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts@@ -81,9 +81,11 @@ describe('overview.service / getRawWhereClause (UTM remapping)', () => {{ name: 'utm_source', operator: 'is', value: ['awn'] },]));- expect(query).toContain("properties['__query.utm_source']");+ // M12-003: the map KEY binds too, so the shape is asserted on the+ // statement and the key on the params.+ expect(query).toContain('properties[{p1:String}]');expect(query).not.toMatch(/(?<![._\w])utm_source\s*=/);- expect(query_params).toEqual({ p1: 'awn' });+ expect(query_params).toEqual({ p1: '__query.utm_source', p2: 'awn' });});it('keeps utm_* as a top-level column for the sessions table', () => {@@ -93,7 +95,7 @@ describe('overview.service / getRawWhereClause (UTM remapping)', () => {]));expect(query).toMatch(/(?<![._\w])utm_source\s*=/);- expect(query).not.toContain("properties['__query.utm_source']");+ expect(query).not.toContain('properties[');expect(query_params).toEqual({ p1: 'awn' });});diff --git a/packages/core/src/modules/overview/src/overview.sql.ts b/packages/core/src/modules/overview/src/overview.sql.tsindex 61023dd5c..f4f909c0b 100644--- a/packages/core/src/modules/overview/src/overview.sql.ts+++ b/packages/core/src/modules/overview/src/overview.sql.ts@@ -6,12 +6,10 @@// 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.//-// The event filter compiler still renders text (chart module's-// filter-where.ts); its output is spliced through `compiledText`, same as-// chart/funnel/retention/sankey/conversion until this module stops needing it-// (ADR-013 leaves the compiler as-is "until funnel, conversion, sankey,-// retention and overview stop splicing its output into text builders" —-// unchanged by this task).+// Both filter compilers and the field resolver return fragments now (M12-002,+// M12-003) 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.//// `toStartOf`/`toInterval`/`datetime` reproduce V1's `clix` static helpers// verbatim (query-builder.ts) rather than chart.sql.ts's own `intervalBucket`:@@ -669,7 +667,7 @@ export interface TopLinkOutQueryInput {}export function topLinkOutQuery(input: TopLinkOutQueryInput): SqlFragment {- const hrefKey = compiledText(getSelectPropertyKey('properties.href'));+ const hrefKey = getSelectPropertyKey('properties.href');return sql`SELECT ${hrefKey} as href, count() as countFROM eventsdiff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.tsindex 92f33eb1b..971565fe8 100644--- a/packages/core/src/modules/profile/profile.service.ts+++ b/packages/core/src/modules/profile/profile.service.ts@@ -29,10 +29,7 @@ import {formatClickhouseDate,toNullIfDefaultMinDate,} from './src/dates';-import {- type CompiledFilterClauses,- compiledFilterClauses,-} from './src/filter-clauses';+import type { CompiledFilterClauses } from './src/filter-clauses';import {findProfilesQuery,powerUsersQuery,@@ -52,7 +49,7 @@ import {profileValuesQuery,} from './src/profile.sql';-export { profileSearchCondition, profileSearchSql } from './src/profile.sql';+export { profileSearchCondition } from './src/profile.sql';const PROFILES_CACHE_SECONDS = 60 * 5;const PROPERTY_KEYS_CACHE_SECONDS = 60;@@ -190,9 +187,7 @@ async function compileProfileFilters(return {};}const { buildFilterWhere } = await loadFilterCompiler();- return compiledFilterClauses(- buildFilterWhere(filters, projectId, PROFILE_FILTER_TARGET)- );+ return buildFilterWhere(filters, projectId, PROFILE_FILTER_TARGET);}export async function getProfileMetrics(diff --git a/packages/core/src/modules/profile/src/filter-clauses.ts b/packages/core/src/modules/profile/src/filter-clauses.tsindex 3c6c0f28a..999840d48 100644--- a/packages/core/src/modules/profile/src/filter-clauses.ts+++ b/packages/core/src/modules/profile/src/filter-clauses.ts@@ -1,29 +1,15 @@// The ONE place this module splices pre-compiled filter SQL.//// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is V1's-// sessions/profiles/events-table filter compiler and still emits-// sqlstring-escaped SQL text; ADR-013 converts it in M12-003. Until then its-// output crosses into a fragment here — through the same `SqlFragment`-// constructor `sql.id` uses — so the bridge is one grep away from deletion-// when the compiler moves, rather than a `sql.raw()` that would outlive it.-// `getEventFiltersWhereClause` (../../chart/src/filter-where.ts) already-// returns fragments (M12-002) and needs no bridge.+// sessions/profiles/events-table filter compiler; it returns bound+// `SqlFragment`s since M12-003, as `getEventFiltersWhereClause`+// (../../chart/src/filter-where.ts) has since M12-002. Nothing is bridged any+// more — this file only assembles what the compiler already produced.-import { SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';export type CompiledFilterClauses = Record<string, SqlFragment>;-/** Bridge `buildFilterWhere`'s compiled TEXT into fragments. */-export function compiledFilterClauses(- clauses: Record<string, string>-): CompiledFilterClauses {- const compiled: CompiledFilterClauses = {};- for (const [key, clause] of Object.entries(clauses)) {- compiled[key] = new SqlFragment([clause], []);- }- return compiled;-}-/** Each compiled clause is already parenthesised by the compiler. */export function compiledFilterFragments(clauses: CompiledFilterClausesdiff --git a/packages/core/src/modules/profile/src/profile.sql.test.ts b/packages/core/src/modules/profile/src/profile.sql.test.tsindex 34e4a87c2..24cb59e5b 100644--- a/packages/core/src/modules/profile/src/profile.sql.test.ts+++ b/packages/core/src/modules/profile/src/profile.sql.test.ts@@ -5,7 +5,7 @@// local prod-copy (M7-002 report), not here — these run offline.import { describe, expect, test } from 'bun:test';-import { compiledFilterClauses } from './filter-clauses';+import { sql } from '@openpanel/db/src/clickhouse/sql';import {findProfilesQuery,PROFILE_COLUMNS,@@ -158,9 +158,7 @@ describe('profileListQuery', () => {offset: 100,search: 'ann',isExternal: true,- filterClauses: compiledFilterClauses({- f0: "(properties['plan'] = 'pro')",- }),+ filterClauses: { f0: sql`(properties['plan'] = 'pro')` },}).toStatement();const text = collapse(query);@@ -181,7 +179,7 @@ describe('profileListQuery', () => {projectId: PROJECT_ID,search: 'ann',isExternal: false,- filterClauses: compiledFilterClauses({ f0: "(email != '')" }),+ filterClauses: { f0: sql`(email != '')` },};const page = collapse(profileListQuery({ ...list, take: 1, offset: 0 }).toStatement().query@@ -229,7 +227,7 @@ describe('findProfilesQuery', () => {inactiveDays: 7,minSessions: 3,performedEvent: HOSTILE,- filterClauses: compiledFilterClauses({ f0: '(1 = 1)' }),+ filterClauses: { f0: sql`(1 = 1)` },}).toStatement();const text = collapse(query);diff --git a/packages/core/src/modules/profile/src/profile.sql.ts b/packages/core/src/modules/profile/src/profile.sql.tsindex e442222d4..b44b6fc28 100644--- a/packages/core/src/modules/profile/src/profile.sql.ts+++ b/packages/core/src/modules/profile/src/profile.sql.ts@@ -14,7 +14,6 @@// binds as `Array(String)`, a literal list to the planner.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';-import sqlstring from 'sqlstring';import {type CompiledFilterClauses,compiledFilterFragments,@@ -79,29 +78,6 @@ export function profileSearchCondition(return sql`(${sql.join(perToken, ' AND ')})`;}-/**- * String-SQL twin of `profileSearchCondition`, for the one caller- * (cohort.service.ts's `getCohortProfiles`) that still composes a V1 text- * query rather than a `sql` fragment. Ported from- * packages/db/src/services/profile.service.ts (M9-CLEANUP-001) — goes with- * that query when it moves onto the `sql` tag.- */-export function profileSearchSql(search: string | null | undefined): string | null {- const tokens = (search ?? '')- .trim()- .split(SEARCH_TOKEN_SEPARATOR)- .filter(Boolean)- .slice(0, SEARCH_MAX_TOKENS);- if (tokens.length === 0) {- return null;- }- const perToken = tokens.map((token) => {- const like = sqlstring.escape(`%${token}%`);- return `(id ILIKE ${like} OR email ILIKE ${like} OR first_name ILIKE ${like} OR last_name ILIKE ${like} OR concat(first_name, ' ', last_name) ILIKE ${like})`;- });- return `(${perToken.join(' AND ')})`;-}-export function profileMetricsQuery(query: {profileId: string;projectId: string;diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.tsindex 1a58698e3..6f078c4d0 100644--- a/packages/core/src/modules/session/session.service.ts+++ b/packages/core/src/modules/session/session.service.ts@@ -24,10 +24,7 @@ import { getSafeJson } from '../../shared/json';import type { IServiceProfile } from '../profile/profile.service';import type { IChartEventFilter } from '../report/report.constants';import { convertClickhouseDateToJs } from './src/dates';-import {- type CompiledFilterClauses,- compiledFilterClauses,-} from './src/filter-clauses';+import type { CompiledFilterClauses } from './src/filter-clauses';import {hasSessionListLookback,querySessionsQuery,@@ -235,12 +232,10 @@ async function compileSessionFilters(return {};}const { buildFilterWhere } = await loadFilterCompiler();- return compiledFilterClauses(- buildFilterWhere(filters, projectId, {- ...SESSION_FILTER_TABLE,- ...range,- })- );+ return buildFilterWhere(filters, projectId, {+ ...SESSION_FILTER_TABLE,+ ...range,+ });}function emptyProfile(profileId: string, projectId: string): IServiceProfile {diff --git a/packages/core/src/modules/session/src/filter-clauses.ts b/packages/core/src/modules/session/src/filter-clauses.tsindex 2ad287d63..3518e7770 100644--- a/packages/core/src/modules/session/src/filter-clauses.ts+++ b/packages/core/src/modules/session/src/filter-clauses.ts@@ -1,29 +1,15 @@// The ONE place this module splices pre-compiled filter SQL.//// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is V1's-// sessions/profiles/events-table filter compiler and still emits-// sqlstring-escaped SQL text; ADR-013 converts it in M12-003. Until then its-// output crosses into a fragment here — through the same `SqlFragment`-// constructor `sql.id` uses — so the bridge is one grep away from deletion-// when the compiler moves, rather than a `sql.raw()` that would outlive it.-// `getEventFiltersWhereClause` (../../chart/src/filter-where.ts) already-// returns fragments (M12-002) and needs no bridge.+// sessions/profiles/events-table filter compiler; it returns bound+// `SqlFragment`s since M12-003, as `getEventFiltersWhereClause`+// (../../chart/src/filter-where.ts) has since M12-002. Nothing is bridged any+// more — this file only assembles what the compiler already produced.-import { SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';export type CompiledFilterClauses = Record<string, SqlFragment>;-/** Bridge `buildFilterWhere`'s compiled TEXT into fragments. */-export function compiledFilterClauses(- clauses: Record<string, string>-): CompiledFilterClauses {- const compiled: CompiledFilterClauses = {};- for (const [key, clause] of Object.entries(clauses)) {- compiled[key] = new SqlFragment([clause], []);- }- return compiled;-}-export function spliceCompiledFilters(clauses: CompiledFilterClauses): SqlFragment {diff --git a/packages/core/src/modules/session/src/session.sql.test.ts b/packages/core/src/modules/session/src/session.sql.test.tsindex 5bb4acf38..ca261668f 100644--- a/packages/core/src/modules/session/src/session.sql.test.ts+++ b/packages/core/src/modules/session/src/session.sql.test.ts@@ -5,7 +5,7 @@// local prod-copy (M7-001 report), not here — these tests run offline.import { describe, expect, test } from 'bun:test';-import { compiledFilterClauses } from './filter-clauses';+import { sql } from '@openpanel/db/src/clickhouse/sql';import {hasSessionListLookback,querySessionsQuery,@@ -80,10 +80,10 @@ describe('sessionListQuery', () => {endDate: new Date('2026-07-31T23:59:59Z'),profileId: 'user-1',search: 'checkout',- filterClauses: compiledFilterClauses({- f0: "country = 'SE'",- f1: "device = 'mobile'",- }),+ filterClauses: {+ f0: sql`country = 'SE'`,+ f1: sql`device = 'mobile'`,+ },}).toStatement();const text = collapse(query);