Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M12-002): chart/src/filter-where.ts onto the sql tag: the filter compiler returns bound SqlFragments, every consumer adapted, side-by-side proof over every operator branch, goldens 137/137

ralph4cd0d76b3d2b
diff --git a/packages/core/src/modules/chart/chart.service.ts b/packages/core/src/modules/chart/chart.service.ts
index 97365408f..22014b847 100644
--- a/packages/core/src/modules/chart/chart.service.ts
+++ b/packages/core/src/modules/chart/chart.service.ts
@@ -18,6 +18,7 @@
// ADR-013's `sql` tag, which ADR-007 keeps in `packages/db` by name: a
// compile-time template tag, no client and no request scope.
+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';
import { flatten, map, pipe, prop, sort, uniq } from 'ramda';
import type { ServiceDeps } from '../../services';
import {
@@ -808,7 +809,7 @@ export interface ChartService {
getRawWhereClause(
type: 'events' | 'sessions',
filters: IChartEventFilter[]
- ): string;
+ ): SqlFragment | null;
getSankeyChart(input: IReportInput): ReturnType<typeof getSankeyChart>;
getSankey(
input: Parameters<typeof getSankey>[1]
diff --git a/packages/core/src/modules/chart/conversion.service.ts b/packages/core/src/modules/chart/conversion.service.ts
index bd37781aa..0216f6d6b 100644
--- a/packages/core/src/modules/chart/conversion.service.ts
+++ b/packages/core/src/modules/chart/conversion.service.ts
@@ -17,7 +17,10 @@ import {
getSelectPropertyKey,
isKnownEventField,
} from './src/field-resolution';
-import { getEventFiltersWhereClause } from './src/filter-where';
+import {
+ getEventFiltersWhereClause,
+ joinFilterClauses,
+} from './src/filter-where';
import { runQuery } from './src/run-query';
/** Default funnel window, in hours, when the report does not set one. */
@@ -157,12 +160,12 @@ export async function getConversion(
// qualifier ClickHouse fails with "ambiguous identifier 'properties'"
// whenever a step filters on properties.X while a breakdown is on
// profile.properties.Y.
- const whereA = Object.values(
+ const whereA = joinFilterClauses(
getEventFiltersWhereClause(eventA.filters, projectId, 'events')
- ).join(' AND ');
- const whereB = Object.values(
+ );
+ const whereB = joinFilterClauses(
getEventFiltersWhereClause(eventB.filters, projectId, 'events')
- ).join(' AND ');
+ );
const results = await runQuery<ConversionRow>(
deps,
diff --git a/packages/core/src/modules/chart/sankey.service.ts b/packages/core/src/modules/chart/sankey.service.ts
index f814e6fe0..68f8657ae 100644
--- a/packages/core/src/modules/chart/sankey.service.ts
+++ b/packages/core/src/modules/chart/sankey.service.ts
@@ -3,6 +3,7 @@
// byte-equivalent to V1 in src/sankey.sql.proof.md; V1's sankey.service is a
// re-export shim onto this module (DELEGATE PATTERN).
+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';
import { z } from 'zod';
import type { ServiceDeps } from '../../services';
import { getSettingsForProject } from '../organization/organization.service';
@@ -11,7 +12,10 @@ import {
type IChartEventFilter,
zChartEvent,
} from '../report/report.constants';
-import { getEventFiltersWhereClause } from './src/filter-where';
+import {
+ getEventFiltersWhereClause,
+ joinFilterClauses,
+} from './src/filter-where';
import { runQuery } from './src/run-query';
import {
type SankeyEvent,
@@ -101,7 +105,7 @@ interface TopEntry {
export function getRawWhereClause(
type: 'events' | 'sessions',
filters: IChartEventFilter[]
-): string {
+): SqlFragment | null {
const where = getEventFiltersWhereClause(
filters.map((filter) => {
if (type !== 'sessions') {
@@ -123,7 +127,7 @@ export function getRawWhereClause(
})
);
- return Object.values(where).join(' AND ');
+ return joinFilterClauses(where);
}
function toSankeyEvent(
diff --git a/packages/core/src/modules/chart/src/chart.sql.ts b/packages/core/src/modules/chart/src/chart.sql.ts
index 1ebb30354..52fc29391 100644
--- a/packages/core/src/modules/chart/src/chart.sql.ts
+++ b/packages/core/src/modules/chart/src/chart.sql.ts
@@ -29,7 +29,11 @@ import type {
IChartEvent,
IInterval,
} from '../../report/report.constants';
-import { compiledText, compiledTextWithProfileRefs } from './compiled';
+import {
+ compiledText,
+ compiledTextWithProfileRefs,
+ fragmentWithProfileRefs,
+} from './compiled';
import { formatClickhouseDate } from './dates';
import {
CHART_TABLE,
@@ -322,6 +326,8 @@ 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);
@@ -349,7 +355,7 @@ function chartBody({
EVENTS_ALIAS
);
for (const [key, clause] of Object.entries(compiledFilters)) {
- where[key] = spliced(clause);
+ where[key] = fragmentWithProfileRefs(clause, profileProps.keys);
}
where.projectId = sql`project_id = ${sql.string(projectId)}`;
@@ -760,7 +766,7 @@ export function chartBucketProfilesQuery(
for (const [key, clause] of Object.entries(
getEventFiltersWhereClause(event.filters, projectId)
)) {
- where[key] = compiledText(clause);
+ where[key] = clause;
}
where.projectId = sql`project_id = ${sql.string(projectId)}`;
where.dateRange = bucketEquals(interval, bucketDate);
diff --git a/packages/core/src/modules/chart/src/compiled.ts b/packages/core/src/modules/chart/src/compiled.ts
index 93b50d6ad..f539f753e 100644
--- a/packages/core/src/modules/chart/src/compiled.ts
+++ b/packages/core/src/modules/chart/src/compiled.ts
@@ -1,14 +1,17 @@
// The ONE place the chart module splices pre-compiled SQL text.
//
-// field-resolution.ts and filter-where.ts are V1's field resolver and filter
-// compiler, still rendering sqlstring-escaped text: ADR-013 leaves the shared
-// compilers as they are ("two behaviours, not two builders") until funnel,
-// conversion, sankey, retention and overview (M7-004/M7-005) stop splicing
-// them into text builders. Every chart-level value is bound in chart.sql.ts;
-// only the compilers' output crosses here, through the same `SqlFragment`
-// constructor `sql.id` uses — one grep away from deletion, not a `sql.raw()`.
+// 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()`.
-import { SqlFragment } from '@openpanel/db/src/clickhouse/sql';
+import {
+ isSqlFragment,
+ SqlFragment,
+ type SqlSlot,
+} from '@openpanel/db/src/clickhouse/sql';
import { rewriteProfilePropertyRefs } from './field-resolution';
export function compiledText(text: string): SqlFragment {
@@ -28,3 +31,26 @@ export function compiledTextWithProfileRefs(
rewriteProfilePropertyRefs(text, profilePropertyKeys as string[])
);
}
+
+/**
+ * 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.
+ */
+export function fragmentWithProfileRefs(
+ fragment: SqlFragment,
+ profilePropertyKeys: readonly string[]
+): SqlFragment {
+ if (profilePropertyKeys.length === 0) {
+ 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
+ );
+ 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.ts
index e6f26b7b3..58ecf4a39 100644
--- a/packages/core/src/modules/chart/src/conversion.sql.ts
+++ b/packages/core/src/modules/chart/src/conversion.sql.ts
@@ -53,9 +53,9 @@ export interface ConversionQueryInput {
funnelWindowSeconds: number;
firstEventName: string;
secondEventName: string;
- /** Compiled filter text per step (`''` when the step has no filters). */
- firstEventWhere: string;
- secondEventWhere: string;
+ /** Compiled filters per step (`null` when the step has no filters). */
+ firstEventWhere: SqlFragment | null;
+ secondEventWhere: SqlFragment | null;
/** Compiled `<expr> as b_<index>` breakdown selects. */
breakdownSelects: string[];
/** Compiled breakdown expressions, as written in the inner GROUP BY. */
@@ -67,9 +67,9 @@ export interface ConversionQueryInput {
cohortJoins: string[];
}
-function stepCondition(name: string, where: string): SqlFragment {
+function stepCondition(name: string, where: SqlFragment | null): SqlFragment {
return where
- ? sql`(events.name = ${sql.string(name)} AND ${compiledText(where)})`
+ ? sql`(events.name = ${sql.string(name)} AND ${where})`
: sql`events.name = ${sql.string(name)}`;
}
diff --git a/packages/core/src/modules/chart/src/filter-cast.ts b/packages/core/src/modules/chart/src/filter-cast.ts
index 27707a7f8..b218ade98 100644
--- a/packages/core/src/modules/chart/src/filter-cast.ts
+++ b/packages/core/src/modules/chart/src/filter-cast.ts
@@ -1,8 +1,19 @@
/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */
// Moved from packages/db/src/services/filter-cast.ts (M8-005) — the typed-cast
-// half of `buildFilterWhere` (./table-filter-where.ts), which is the only
-// caller. `./filter-where.ts` (the event-property compiler) imports it too.
+// 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.
+import {
+ type SqlFragment,
+ type SqlSlot,
+ sql,
+} from '@openpanel/db/src/clickhouse/sql';
import sqlstring from 'sqlstring';
import type {
IChartEventFilterOperator,
@@ -63,10 +74,63 @@ const TYPED_SQL_OPERATOR: Partial<Record<IChartEventFilterOperator, string>> = {
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`<=`,
+};
+
export function isTypedOperator(operator: IChartEventFilterOperator): boolean {
return operator in TYPED_SQL_OPERATOR;
}
+/** {@link castSql} as a fragment. Keep the emitted expressions identical. */
+export function castFragment(
+ expr: SqlSlot,
+ type?: IChartFilterValueType
+): SqlSlot {
+ switch (type) {
+ case 'number':
+ return sql`toFloat64OrNull(toString(${expr}))`;
+ case 'date':
+ return sql`toDate(parseDateTimeBestEffortOrNull(toString(${expr})))`;
+ case 'datetime':
+ return sql`parseDateTimeBestEffortOrNull(toString(${expr}))`;
+ case 'boolean':
+ return sql`if(lower(trim(toString(${expr}))) IN ('true', '1', 'yes'), 1, 0)`;
+ case 'string':
+ case undefined:
+ return expr;
+ }
+}
+
+/**
+ * Bind one filter value the way `sqlstring.escape` rendered it: a string is a
+ * quoted literal, a number a numeric literal, 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 typedValueParam(value: IChartEventFilterValue): SqlSlot {
+ if (value === null) {
+ return sql.nullable('String', null);
+ }
+ if (typeof value === 'number') {
+ return sql.float64(value);
+ }
+ if (typeof value === 'boolean') {
+ return sql.bool(value);
+ }
+ return sql.string(value.trim());
+}
+
/**
* 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.
@@ -95,3 +159,21 @@ export function buildTypedClause(
})
.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 left = castFragment(leftExpr, type);
+ const joiner = operator === 'isNot' ? ' AND ' : ' OR ';
+ return sql`(${sql.join(
+ value.map(
+ (val) => sql`${left} ${sqlOp} ${castFragment(typedValueParam(val), type)}`
+ ),
+ joiner
+ )})`;
+}
diff --git a/packages/core/src/modules/chart/src/filter-where.sql.proof.md b/packages/core/src/modules/chart/src/filter-where.sql.proof.md
new file mode 100644
index 000000000..03ba7ede6
--- /dev/null
+++ b/packages/core/src/modules/chart/src/filter-where.sql.proof.md
@@ -0,0 +1,707 @@
+# filter-where.ts — V1 → V2 result-set proof (M12-002)
+
+V1 is `packages/core/src/modules/chart/src/filter-where.ts` at `be029da1`
+(`git show HEAD:packages/core/src/modules/chart/src/filter-where.ts`,
+materialised as a sibling module so its relative imports resolve, deleted after
+the run). V2 is the converted file in this commit. Both compilers were imported
+into ONE Bun process, called with the SAME `IChartEventFilter[]`, `projectId`,
+`eventsAlias` and `tableScope`, and each compiled clause was spliced into the
+SAME surrounding count query and executed through ONE `@clickhouse/client` with
+`format: 'JSON'` and `session_timezone=UTC` on both sides — V1 as `query`, V2 as
+`query` + `query_params`. `data` and `meta` were compared field for field. Every
+statement here returns a single aggregate row, so no case needed set comparison.
+
+- **Date**: 2026-09-07.
+- **Data**: local prod-copy `openpanel`, 319,850,470 events. Project
+ `secure-privacy` (347 group rows, 345 distinct names, 31 of those reachable
+ from events in the window), window `2026-07-01 00:00:00` … `2026-07-08 00:00:00` (76,885 events, 22,983
+ distinct profiles), `session_timezone=UTC`. One case (`wildcard array /
+ isNull`) uses project `dd5f6d1c-fff9-43c9-8c89-e40ba06752c8` over the same
+ window, because it is the only project in the copy with an empty-valued
+ `__query.*` key there — on `secure-privacy` that case returns 0 rows and would
+ prove nothing. **`cohort_members` is empty in the prod copy** (`SELECT count()
+ FROM cohort_members` = 0), so the two `inCohort` cases are 0-row statement
+ equivalences; positive-row cohort coverage lives in `openpanel_test` (same
+ precedent as `chart.sql.proof.md`).
+- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are
+ directional only; production is 2 shards × 2 replicas
+ (`docs/ENVIRONMENT.md`). Two statements contain `IN (subquery)` on a
+ `Distributed` table (the two cohort branches); **no `IN` was converted to
+ `GLOBAL IN` or back** — see *IN / GLOBAL IN* below.
+- **Verdict**: **94 cases, all IDENTICAL** — 91 executed against ClickHouse
+ (3 of them IDENTICAL ERROR: V1 defects reproduced byte-for-byte, listed
+ below, not fixed here) and 3 compile-time equivalences where both compilers
+ emit no clause at all.
+
+## Per-case results
+
+Row counts are `count()` / `uniq(profile_id)` over the window, V1/V2. Three
+cases return 0 rows and say why in their row: the two `inCohort` cases
+(`cohort_members` is empty here) and `typed cast / number is with a null value`
+(a comparison against NULL is never true — the binding itself is proven by the
+probe under *The `null` binding*).
+
+| branch | case | verdict | rows V1/V2 | count V1/V2 | uniq V1/V2 | rows_read V1/V2 | wall ms V1/V2 |
+|---|---|---|---|---|---|---|---|
+| top-level column | is (single value) | IDENTICAL | 1/1 | 3066/3066 | 986/986 | 90057/90057 | 29/21 |
+| top-level column | is (multi value -> IN) | IDENTICAL | 1/1 | 3921/3921 | 1090/1090 | 90057/90057 | 21/20 |
+| top-level column | isNot (single value) | IDENTICAL | 1/1 | 73819/73819 | 22268/22268 | 90057/90057 | 37/18 |
+| top-level column | isNot (multi value -> NOT IN) | IDENTICAL | 1/1 | 72964/72964 | 22179/22179 | 90057/90057 | 24/23 |
+| top-level column | contains | IDENTICAL | 1/1 | 60795/60795 | 19723/19723 | 90057/90057 | 20/19 |
+| top-level column | doesNotContain | IDENTICAL | 1/1 | 16090/16090 | 3393/3393 | 90057/90057 | 20/23 |
+| top-level column | startsWith | IDENTICAL | 1/1 | 60089/60089 | 19504/19504 | 90057/90057 | 17/22 |
+| top-level column | endsWith | IDENTICAL | 1/1 | 6333/6333 | 1953/1953 | 90057/90057 | 16/19 |
+| top-level column | regex (slashes stripped) | IDENTICAL | 1/1 | 60089/60089 | 19504/19504 | 90057/90057 | 21/21 |
+| top-level column | isNull (empty value array) | IDENTICAL | 1/1 | 15591/15591 | 3420/3420 | 90057/90057 | 13/23 |
+| top-level column | isNotNull (empty value array) | IDENTICAL | 1/1 | 61294/61294 | 19631/19631 | 90057/90057 | 20/15 |
+| top-level column | gt on a numeric column (toFloat64 cast) | IDENTICAL | 1/1 | 868/868 | 702/702 | 90057/90057 | 20/14 |
+| top-level column | gte on a numeric column | IDENTICAL | 1/1 | 869/869 | 702/702 | 90057/90057 | 13/13 |
+| top-level column | lt on a numeric column | IDENTICAL | 1/1 | 76688/76688 | 22983/22983 | 90057/90057 | 15/15 |
+| top-level column | lte on a numeric column | IDENTICAL | 1/1 | 76688/76688 | 22983/22983 | 90057/90057 | 15/20 |
+| top-level column | gt on a non-numeric column (raw comparison) | IDENTICAL | 1/1 | 73522/73522 | 22243/22243 | 90057/90057 | 18/17 |
+| top-level column | lte on a non-numeric column | IDENTICAL | 1/1 | 7068/7068 | 2091/2091 | 90057/90057 | 22/20 |
+| top-level column | camelCase alias (referrerName -> referrer_name) | IDENTICAL | 1/1 | 58439/58439 | 18908/18908 | 90057/90057 | 28/31 |
+| top-level column | null in the value array (String(null) -> 'null') | IDENTICAL | 1/1 | 3066/3066 | 986/986 | 90057/90057 | 20/16 |
+| top-level column | unknown column is dropped | IDENTICAL (no clause emitted) | – | – | – | – | – |
+| top-level column | empty value array with a value operator is dropped | IDENTICAL (no clause emitted) | – | – | – | – | – |
+| properties.* | is (single value) | IDENTICAL | 1/1 | 1084/1084 | 360/360 | 81866/81866 | 18/18 |
+| properties.* | is (multi value -> IN) | IDENTICAL | 1/1 | 1084/1084 | 360/360 | 81866/81866 | 34/18 |
+| properties.* | isNot (single value) | IDENTICAL | 1/1 | 75801/75801 | 22949/22949 | 90057/90057 | 35/23 |
+| properties.* | isNot (multi value -> NOT IN) | IDENTICAL | 1/1 | 75801/75801 | 22949/22949 | 90057/90057 | 30/38 |
+| properties.* | contains | IDENTICAL | 1/1 | 52792/52792 | 22934/22934 | 90057/90057 | 29/22 |
+| properties.* | doesNotContain | IDENTICAL | 1/1 | 24093/24093 | 22891/22891 | 90057/90057 | 20/23 |
+| properties.* | startsWith | IDENTICAL | 1/1 | 3948/3948 | 1434/1434 | 90057/90057 | 23/26 |
+| properties.* | endsWith | IDENTICAL | 1/1 | 3039/3039 | 1120/1120 | 90057/90057 | 26/20 |
+| properties.* | regex (NOT slash-stripped, unlike the column branch) | IDENTICAL | 1/1 | 3948/3948 | 1434/1434 | 90057/90057 | 32/19 |
+| properties.* | isNull | IDENTICAL | 1/1 | 23963/23963 | 22890/22890 | 90057/90057 | 22/20 |
+| properties.* | isNotNull | IDENTICAL | 1/1 | 52922/52922 | 22973/22973 | 90057/90057 | 28/29 |
+| properties.* | gt (toFloat64OrZero) | IDENTICAL | 1/1 | 1157/1157 | 529/529 | 81866/81866 | 17/17 |
+| properties.* | gte (toFloat64OrZero) | IDENTICAL | 1/1 | 76885/76885 | 22983/22983 | 90057/90057 | 35/19 |
+| properties.* | lt (toFloat64OrZero) | IDENTICAL | 1/1 | 75728/75728 | 22983/22983 | 90057/90057 | 29/23 |
+| properties.* | lte (toFloat64OrZero) | IDENTICAL | 1/1 | 75728/75728 | 22983/22983 | 90057/90057 | 22/21 |
+| properties.* | eventsAlias qualifies the map (e.properties[...]) | IDENTICAL | 1/1 | 1084/1084 | 360/360 | 81866/81866 | 18/20 |
+| properties.__query.* | bare utm_source routed into the __query map | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 12/18 |
+| properties.__query.* | explicit properties.__query.utm_source contains | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 12/12 |
+| properties.__query.* | properties.__query.gclid isNotNull | IDENTICAL | 1/1 | 1292/1292 | 547/547 | 81866/81866 | 29/22 |
+| profile.properties.* | is (single value) | IDENTICAL | 1/1 | 42927/42927 | 13651/13651 | 401033/401033 | 109/82 |
+| profile.properties.* | is + rewriteProfilePropertyRefs narrows the ref | IDENTICAL | 1/1 | 42927/42927 | 13651/13651 | 401033/401033 | 75/76 |
+| profile.properties.* | contains + rewriteProfilePropertyRefs (the value keeps its own text) | IDENTICAL | 1/1 | 70431/70431 | 21700/21700 | 401033/401033 | 79/76 |
+| profile.properties.* | isNotNull | IDENTICAL | 1/1 | 75053/75053 | 22938/22938 | 401033/401033 | 79/82 |
+| profile.properties.* | multi value -> IN | IDENTICAL | 1/1 | 46413/46413 | 14783/14783 | 401033/401033 | 79/83 |
+| wildcard array | is | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 13/14 |
+| wildcard array | isNot | IDENTICAL | 1/1 | 2035/2035 | 802/802 | 81866/81866 | 21/30 |
+| wildcard array | contains | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 14/13 |
+| wildcard array | doesNotContain | IDENTICAL | 1/1 | 2035/2035 | 802/802 | 81866/81866 | 16/18 |
+| wildcard array | startsWith | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 17/14 |
+| wildcard array | endsWith | IDENTICAL | 1/1 | 109/109 | 49/49 | 81866/81866 | 17/18 |
+| wildcard array | regex | IDENTICAL | 1/1 | 41/41 | 20/20 | 49113/49113 | 14/13 |
+| wildcard array | isNull | IDENTICAL | 1/1 | 5/5 | 3/3 | 81897/16379 | 16/13 |
+| wildcard array | isNotNull | IDENTICAL | 1/1 | 2076/2076 | 822/822 | 81866/81866 | 17/19 |
+| wildcard array | gt | IDENTICAL | 1/1 | 1290/1290 | 587/587 | 81866/81866 | 23/25 |
+| wildcard array | gte | IDENTICAL | 1/1 | 2076/2076 | 822/822 | 81866/81866 | 19/23 |
+| wildcard array | lt | IDENTICAL | 1/1 | 2029/2029 | 807/807 | 81866/81866 | 32/25 |
+| wildcard array | lte | IDENTICAL | 1/1 | 2043/2043 | 814/814 | 81866/81866 | 36/19 |
+| wildcard array | nested .*. pattern (properties.__query.*.type) | IDENTICAL | 1/1 | 62/62 | 26/26 | 73674/73674 | 18/18 |
+| trailing .* wildcard | properties.__query.* is (V1 defect: not a wildcard) | **IDENTICAL ERROR** | – | – | – | – | 4/4 |
+| trailing .* wildcard | properties.__query.* isNotNull | **IDENTICAL ERROR** | – | – | – | – | 4/3 |
+| group.* | group.type is | IDENTICAL | 1/1 | 997/997 | 31/31 | 93416/93416 | 32/34 |
+| group.* | group.name contains | IDENTICAL | 1/1 | 733/733 | 24/24 | 93416/93416 | 31/27 |
+| group.* | group.name is (multi -> IN) | IDENTICAL | 1/1 | 198/198 | 3/3 | 93416/93416 | 26/28 |
+| group.* | group.name isNot (single) | IDENTICAL | 1/1 | 2715/2715 | 89/89 | 93416/93416 | 31/32 |
+| group.* | group.name isNot (multi -> NOT IN) | IDENTICAL | 1/1 | 2655/2655 | 88/88 | 93416/93416 | 29/28 |
+| group.* | group.properties.employees isNotNull | IDENTICAL | 1/1 | 929/929 | 29/29 | 93416/93416 | 32/33 |
+| group.* | group.properties.country isNull | IDENTICAL | 1/1 | 2295/2295 | 77/77 | 93416/93416 | 30/30 |
+| group.* | group.name startsWith | IDENTICAL | 1/1 | 138/138 | 2/2 | 93416/93416 | 27/33 |
+| group.* | group.name endsWith | IDENTICAL | 1/1 | 357/357 | 13/13 | 93416/93416 | 30/29 |
+| group.* | group.name doesNotContain | IDENTICAL | 1/1 | 2120/2120 | 68/68 | 93416/93416 | 32/28 |
+| group.* | group.name regex | IDENTICAL | 1/1 | 733/733 | 24/24 | 93416/93416 | 28/27 |
+| has_profile | has_profile true | IDENTICAL | 1/1 | 2841/2841 | 91/91 | 81866/81866 | 25/16 |
+| has_profile | has_profile false | IDENTICAL | 1/1 | 74044/74044 | 22892/22892 | 90057/90057 | 26/18 |
+| cohort | inCohort (cohort_members is empty in the prod copy) | IDENTICAL | 1/1 | 0/0 | 0/0 | 0/0 | 8/8 |
+| cohort | notInCohort | IDENTICAL | 1/1 | 76885/76885 | 22983/22983 | 229305/229305 | 15/23 |
+| cohort | inCohort with eventsAlias | IDENTICAL | 1/1 | 0/0 | 0/0 | 0/0 | 7/11 |
+| cohort | inCohort with no cohort ids is dropped | IDENTICAL (no clause emitted) | – | – | – | – | – |
+| typed cast | number is on a property | IDENTICAL | 1/1 | 8/8 | 4/4 | 16381/16381 | 17/15 |
+| typed cast | number gt on a property | IDENTICAL | 1/1 | 1157/1157 | 529/529 | 81866/81866 | 22/19 |
+| typed cast | number gte on a top-level column | IDENTICAL | 1/1 | 869/869 | 702/702 | 90057/90057 | 27/22 |
+| typed cast | number isNot on a property (AND joiner) | IDENTICAL | 1/1 | 1157/1157 | 529/529 | 81866/81866 | 22/23 |
+| typed cast | boolean is on a property | IDENTICAL | 1/1 | 54159/54159 | 22983/22983 | 90057/90057 | 29/27 |
+| typed cast | date gte on created_at | IDENTICAL | 1/1 | 64656/64656 | 20059/20059 | 73676/73676 | 31/18 |
+| typed cast | datetime lt on created_at | IDENTICAL | 1/1 | 12229/12229 | 2946/2946 | 24568/24568 | 10/9 |
+| typed cast | number is on a wildcard array | IDENTICAL | 1/1 | 62/62 | 26/26 | 73674/73674 | 22/19 |
+| typed cast | number is with a numeric (not string) value | IDENTICAL | 1/1 | 8/8 | 4/4 | 16381/16381 | 13/10 |
+| typed cast | boolean is with a real boolean value | IDENTICAL | 1/1 | 54159/54159 | 22983/22983 | 90057/90057 | 26/33 |
+| typed cast | number is with a null value (NULL keyword) | IDENTICAL | 1/1 | 0/0 | 0/0 | 0/0 | 7/5 |
+| typed cast | number gte on a group property | IDENTICAL | 1/1 | 929/929 | 29/29 | 93416/93416 | 29/35 |
+| sessions scope | bare entry_path is (no top-level allowlist) | **IDENTICAL ERROR** | – | – | – | – | 6/5 |
+| sessions scope | utm_source stays a top-level column | IDENTICAL | 1/1 | 19/19 | 19/19 | 65436/65436 | 24/18 |
+| sessions scope | camelCase alias on sessions | IDENTICAL | 1/1 | 19107/19107 | 18877/18877 | 65436/65436 | 16/13 |
+| multiple filters | three filters joined with AND | IDENTICAL | 1/1 | 24996/24996 | 12289/12289 | 90057/90057 | 23/24 |
+`rows_read` and wall time differ run to run and between an inline literal and
+a bound param — recorded, not chased (recipe, *Proof-file template*).
+
+## Rendered statements, one per branch
+
+Every compiled clause below was produced by CALLING the two compilers, not
+retyped. Each pair is reproducible with `curl` (see *Reproducing a case*).
+
+### top-level column
+
+**top-level column — is (single value)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **3066/3066**; uniq V1/V2 = **986/986**; rows_read V1/V2 = 90057/90057; wall V1/V2 = 29 ms / 21 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "path", "operator": "is", "value": ["/"]}]
+-- V1 clause
+path = '/'
+-- V2 clause
+path = {p1:String}
+-- V2 clause params: {"p1": "/"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (path = '/')
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (path = {p1:String})
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "/"}
+```
+
+### properties.*
+
+**properties.* — is (single value)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **1084/1084**; uniq V1/V2 = **360/360**; rows_read V1/V2 = 81866/81866; wall V1/V2 = 18 ms / 18 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "properties.__title", "operator": "is", "value": ["Secure Privacy Consent Management Platform"]}]
+-- V1 clause
+properties['__title'] = 'Secure Privacy Consent Management Platform'
+-- V2 clause
+properties['__title'] = {p1:String}
+-- V2 clause params: {"p1": "Secure Privacy Consent Management Platform"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (properties['__title'] = 'Secure Privacy Consent Management Platform')
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (properties['__title'] = {p1:String})
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "Secure Privacy Consent Management Platform"}
+```
+
+### properties.__query.*
+
+**properties.__query.* — bare utm_source routed into the __query map** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **41/41**; uniq V1/V2 = **20/20**; rows_read V1/V2 = 49113/49113; wall V1/V2 = 12 ms / 18 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "utm_source", "operator": "is", "value": ["chatgpt.com"]}]
+-- V1 clause
+properties['__query.utm_source'] = 'chatgpt.com'
+-- V2 clause
+properties['__query.utm_source'] = {p1:String}
+-- V2 clause params: {"p1": "chatgpt.com"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (properties['__query.utm_source'] = 'chatgpt.com')
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (properties['__query.utm_source'] = {p1:String})
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "chatgpt.com"}
+```
+
+### profile.properties.*
+
+**profile.properties.* — is (single value)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **42927/42927**; uniq V1/V2 = **13651/13651**; rows_read V1/V2 = 401033/401033; wall V1/V2 = 109 ms / 82 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "profile.properties.country", "operator": "is", "value": ["US"]}]
+-- V1 clause
+profile.properties['country'] = 'US'
+-- V2 clause
+profile.properties['country'] = {p1:String}
+-- V2 clause params: {"p1": "US"}
+-- V1 statement
+SELECT count() AS c, uniq(e.profile_id) AS u FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = 'secure-privacy') AS profile ON profile.id = e.profile_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') AND (profile.properties['country'] = 'US')
+-- V2 statement
+SELECT count() AS c, uniq(e.profile_id) AS u FROM events e LEFT ANY JOIN (SELECT id, properties FROM profiles FINAL WHERE project_id = {w1:String}) AS profile ON profile.id = e.profile_id WHERE e.project_id = {w1:String} AND e.created_at >= toDateTime({w2:String}) AND e.created_at < toDateTime({w3:String}) AND (profile.properties['country'] = {p1:String})
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "US"}
+```
+
+### wildcard array
+
+**wildcard array — is** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **41/41**; uniq V1/V2 = **20/20**; rows_read V1/V2 = 49113/49113; wall V1/V2 = 13 ms / 14 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "properties.__query[*]", "operator": "is", "value": ["chatgpt.com"]}]
+-- V1 clause
+arrayExists(x -> x = 'chatgpt.com', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%'))))
+-- V2 clause
+arrayExists(x -> x = {p1:String}, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%'))))
+-- V2 clause params: {"p1": "chatgpt.com"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayExists(x -> x = 'chatgpt.com', arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%')))))
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (arrayExists(x -> x = {p1:String}, arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.%')))))
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "chatgpt.com"}
+```
+
+### trailing .* wildcard
+
+**trailing .* wildcard — properties.__query.* is (V1 defect: not a wildcard)** — IDENTICAL ERROR; wall V1/V2 = 4 ms / 4 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "properties.__query.*", "operator": "is", "value": ["chatgpt.com"]}]
+-- V1 clause
+arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = 'chatgpt.com'
+-- V2 clause
+arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = {p1:String}
+-- V2 clause params: {"p1": "chatgpt.com"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = 'chatgpt.com')
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (arrayMap(x -> trim(x), mapValues(mapExtractKeyLike(properties, '__query.*'))) = {p1:String})
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "chatgpt.com"}
+```
+
+Both sides fail with the same ClickHouse error:
+
+```
+V1: Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim
+V2: Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim
+```
+
+### group.*
+
+**group.* — group.type is** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **997/997**; uniq V1/V2 = **31/31**; rows_read V1/V2 = 93416/93416; wall V1/V2 = 32 ms / 34 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "group.type", "operator": "is", "value": ["company"]}]
+-- V1 clause
+_g.type = 'company'
+-- V2 clause
+_g.type = {p1:String}
+-- V2 clause params: {"p1": "company"}
+-- V1 statement
+SELECT count() AS c, uniq(e.profile_id) AS u FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = 'secure-privacy') AS _g ON _g.id = _group_id WHERE e.project_id = 'secure-privacy' AND e.created_at >= toDateTime('2026-07-01 00:00:00') AND e.created_at < toDateTime('2026-07-08 00:00:00') AND (_g.type = 'company')
+-- V2 statement
+SELECT count() AS c, uniq(e.profile_id) AS u FROM events e ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM groups FINAL WHERE project_id = {w1:String}) AS _g ON _g.id = _group_id WHERE e.project_id = {w1:String} AND e.created_at >= toDateTime({w2:String}) AND e.created_at < toDateTime({w3:String}) AND (_g.type = {p1:String})
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "company"}
+```
+
+### has_profile
+
+**has_profile — has_profile true** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **2841/2841**; uniq V1/V2 = **91/91**; rows_read V1/V2 = 81866/81866; wall V1/V2 = 25 ms / 16 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "has_profile", "operator": "is", "value": ["true"]}]
+-- V1 clause
+profile_id != device_id
+-- V2 clause
+profile_id != device_id
+-- V2 clause params: {}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id != device_id)
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (profile_id != device_id)
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00"}
+```
+
+### cohort
+
+**cohort — inCohort (cohort_members is empty in the prod copy)** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **0/0**; uniq V1/V2 = **0/0**; rows_read V1/V2 = 0/0; wall V1/V2 = 8 ms / 8 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "profile", "operator": "inCohort", "value": [], "cohortIds": ["11111111-1111-1111-1111-111111111111"]}]
+-- V1 clause
+profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('11111111-1111-1111-1111-111111111111') AND project_id = 'secure-privacy')
+-- V2 clause
+profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p1:Array(String)} AND project_id = {p2:String})
+-- V2 clause params: {"p1": ["11111111-1111-1111-1111-111111111111"], "p2": "secure-privacy"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('11111111-1111-1111-1111-111111111111') AND project_id = 'secure-privacy'))
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p1:Array(String)} AND project_id = {p2:String}))
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": ["11111111-1111-1111-1111-111111111111"], "p2": "secure-privacy"}
+```
+
+### typed cast
+
+**typed cast — number is on a property** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **8/8**; uniq V1/V2 = **4/4**; rows_read V1/V2 = 16381/16381; wall V1/V2 = 17 ms / 15 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "properties.__query.adid", "operator": "is", "value": ["0"], "type": "number"}]
+-- V1 clause
+(toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString('0')))
+-- V2 clause
+(toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString({p1:String})))
+-- V2 clause params: {"p1": "0"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString('0'))))
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND ((toFloat64OrNull(toString(properties['__query.adid'])) = toFloat64OrNull(toString({p1:String}))))
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "0"}
+```
+
+### sessions scope
+
+**sessions scope — bare entry_path is (no top-level allowlist)** — IDENTICAL ERROR; wall V1/V2 = 6 ms / 5 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "path", "operator": "is", "value": ["/"]}]
+-- V1 clause
+path = '/'
+-- V2 clause
+path = {p1:String}
+-- V2 clause params: {"p1": "/"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (path = '/')
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (path = {p1:String})
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "/"}
+```
+
+Both sides fail with the same ClickHouse error:
+
+```
+V1: Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A
+V2: Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A
+```
+
+### multiple filters
+
+**multiple filters — three filters joined with AND** — IDENTICAL; rows V1/V2 = 1/1; count V1/V2 = **24996/24996**; uniq V1/V2 = **12289/12289**; rows_read V1/V2 = 90057/90057; wall V1/V2 = 23 ms / 24 ms; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- filter input: [{"name": "path", "operator": "startsWith", "value": ["/blog"]}, {"name": "country", "operator": "is", "value": ["US"]}, {"name": "properties.__title", "operator": "contains", "value": ["Privacy"]}]
+-- V1 clause
+(path LIKE '/blog%') AND country = 'US' AND (properties['__title'] LIKE '%Privacy%')
+-- V2 clause
+(path LIKE {p1:String}) AND country = {p2:String} AND (properties['__title'] LIKE {p3:String})
+-- V2 clause params: {"p1": "/blog%", "p2": "US", "p3": "%Privacy%"}
+-- V1 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND ((path LIKE '/blog%') AND country = 'US' AND (properties['__title'] LIKE '%Privacy%'))
+-- V2 statement
+SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND ((path LIKE {p1:String}) AND country = {p2:String} AND (properties['__title'] LIKE {p3:String}))
+-- V2 statement params: {"w1": "secure-privacy", "w2": "2026-07-01 00:00:00", "w3": "2026-07-08 00:00:00", "p1": "/blog%", "p2": "US", "p3": "%Privacy%"}
+```
+## The three compile-time equivalences
+
+These emit no clause on either side, so there is nothing to execute — the
+evidence is that both compilers return an empty record for the same input.
+
+| case | V1 keys | V2 keys |
+|---|---|---|
+| top-level column — unknown column is dropped | `[]` | `[]` |
+| top-level column — empty value array with a value operator is dropped | `[]` | `[]` |
+| cohort — inCohort with no cohort ids is dropped | `[]` | `[]` |
+
+## IDENTICAL ERROR cases — V1 defects reproduced, not fixed
+
+- **trailing .* wildcard — properties.__query.* is (V1 defect: not a wildcard)**
+ - V1: `Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim`
+ - V2: `Array does not start with '[' character: while converting 'chatgpt.com' to Array(String): while executing function equals on arguments arrayMap(x String -> trim`
+- **trailing .* wildcard — properties.__query.* isNotNull**
+ - V1: `Array does not start with '[' character: while converting '' to Array(String): while executing function notEquals on arguments arrayMap(x String -> trimBoth(x),`
+ - V2: `Array does not start with '[' character: while converting '' to Array(String): while executing function notEquals on arguments arrayMap(x String -> trimBoth(x),`
+- **sessions scope — bare entry_path is (no top-level allowlist)**
+ - V1: `Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A`
+ - V2: `Unknown expression or function identifier `path` in scope SELECT count() AS c, uniq(profile_id) AS u FROM sessions FINAL WHERE (project_id = 'secure-privacy') A`
+The first two are the trailing-`.*` branch: `getSelectPropertyKey` treats
+`properties.__query.*` as a literal map-key pattern rather than a wildcard, so
+the compiler emits an `Array(String)` expression compared against a scalar. The
+third is the sessions scope, where V1 skips the top-level-column allowlist —
+`path` is not a `sessions` column, so both sides reach ClickHouse and both are
+rejected. All three are pre-existing V1 behaviour and are reproduced, not fixed.
+
+## `rewriteProfilePropertyRefs` — where the rewrite happens now
+
+V1 ran the rewrite over finished TEXT: `chart.sql.ts` and `funnel.sql.ts` called
+`compiledTextWithProfileRefs(clause, keys)` on the compiler's string. With the
+compiler returning fragments there is no string to rewrite, so the rewrite moved
+to `compiled.ts`'s `fragmentWithProfileRefs(fragment, keys)`, which maps
+`rewriteProfilePropertyRefs` over `fragment.strings` — **the literal parts
+only** — and recurses into nested fragments, leaving every `SqlParam`
+untouched. **It never runs on params.**
+
+That is the same rewrite, and now it is the same rewrite *by construction*.
+`compiled.ts` recorded why the text version was safe: an escaped literal cannot
+contain `['`, so the rewrite never matched a value. A bound param is not in the
+text at all, so it cannot match even in principle — the accident became an
+invariant. Callers: `chart.sql.ts:358` and `funnel.sql.ts:149`.
+`compiledTextWithProfileRefs` survives for the ONE thing still rendering text,
+the field resolver (`chart.sql.ts:332`, `funnel.sql.ts:180`).
+
+Two proof cases exercise it end to end against the narrowed profile CTE — the
+wrapper selects ``properties['country'] as `profile.properties.country` `` and
+``properties['device'] as `profile.properties.device` `` exactly as
+`profilePropertiesCteSelect` does, so the rewritten ref has to resolve or the
+query fails with UNKNOWN_IDENTIFIER:
+
+- `profile.properties.* / is + rewriteProfilePropertyRefs narrows the ref` —
+ keys `['country']`, 42,927 rows on both sides.
+- `profile.properties.* / contains + rewriteProfilePropertyRefs (the value keeps
+ its own text)` — keys `['device']`, value `'deskto'`, 70,431 rows on both
+ sides. The value contains no `['`, but the point is structural: it is in
+ `query_params`, not in the statement, so the rewrite pass cannot reach it.
+
+The two un-narrowed `profile.properties.*` cases (`is (single value)`,
+`multi value -> IN`) run against the full-Map CTE with no rewrite, and are
+identical too — so both halves of the narrowing switch are covered.
+
+## IN / GLOBAL IN — unchanged in both directions
+
+The rule (recipe, *Traps 2*; `docs/ENVIRONMENT.md`): a conversion changes the
+binding of values and nothing about distribution semantics. The two places
+`filter-where.ts` emits `IN` against a `Distributed` table are the cohort
+branches, and both are still plain `IN`, as V1 wrote them.
+
+```
+$ git diff -U0 | grep -nE '^[+-].*(\bGLOBAL +IN\b|\bGLOBAL +JOIN\b)'
+310:+ // change IN/GLOBAL IN in either direction (docs/ENVIRONMENT.md).
+```
+
+The only line in the whole diff that mentions `GLOBAL IN` is the comment saying
+it was not touched. No `GLOBAL` was added and none was removed.
+
+The multi-value `IN (...)` list forms became `IN {pN:Array(String)}` (recipe
+idiom 9) — a value list, not a subquery, so it carries no distribution
+question. The cohort subselect kept its parentheses and its `IN`:
+
+```sql
+-- V1
+profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN ('1111...') AND project_id = 'secure-privacy')
+-- V2
+profile_id IN (SELECT profile_id FROM cohort_members FINAL WHERE cohort_id IN {p1:Array(String)} AND project_id = {p2:String})
+```
+
+## The `null` binding
+
+`sqlstring.escape(null)` produced the SQL keyword `NULL`. `sql.string(null)`
+would bind a `String` param, which ClickHouse parses as the **empty string** —
+so the typed-cast path binds through `sql.nullable('String', null)`
+(`filter-cast.ts`, `typedValueParam`). Measured against local ClickHouse
+26.1.3.52, 2026-09-07:
+
+```bash
+curl -s -G 'http://127.0.0.1:8123/' --data-urlencode 'database=openpanel' \
+ --data-urlencode 'default_format=JSONCompact' --data-urlencode 'param_p1=\N' \
+ --data-urlencode "query=SELECT toFloat64OrNull(toString({p1:Nullable(String)})) AS v2, isNull(toFloat64OrNull(toString({p1:Nullable(String)}))) AS v2_isnull, toFloat64OrNull(toString(NULL)) AS v1, isNull(toFloat64OrNull(toString(NULL))) AS v1_isnull"
+-- [[null,1,null,1]]
+
+curl -s -G 'http://127.0.0.1:8123/' --data-urlencode 'database=openpanel' \
+ --data-urlencode 'default_format=JSONCompact' --data-urlencode 'param_p1=\N' \
+ --data-urlencode "query=SELECT {p1:String} AS as_string, isNull({p1:Nullable(String)}) AS as_nullable_isnull"
+-- [["",1]]
+```
+
+V1's `NULL` and V2's `{p:Nullable(String)}` are both NULL; a plain `String` param
+would have been `''`. The `typed cast / number is with a null value` proof case
+returns 0 rows on both sides and always will — a comparison against NULL is
+never true — so the binding probe above is what actually proves that branch;
+the case proves the two statements agree.
+
+The untyped branches never see a raw `null`: V1 wrote `String(val).trim()`, so a
+`null` value becomes the four-character string `'null'`. The `top-level column /
+null in the value array` case pins that (`path IN ('null','/')` vs
+`path IN {p:Array(String)}` with `["null","/"]`, 3,066 rows both sides).
+
+## Consumer conversion: referrer-spikes.ts (clix → sql)
+
+Not in the task's consumer list, and forced by it: `getRawWhereClause` returns a
+fragment carrying params, and clix's `execute()` (`query-builder.ts:552`) has no
+`query_params` slot to carry them — it passes only `query` and
+`clickhouse_settings`. `packages/db` is outside this task's scope, so the three
+clix queries in `modules/insight/src/referrer-spikes.ts` moved onto the tag
+instead. clix always sent `session_timezone` (`query-builder.ts:562`); `chQuery`
+gets the same value, and `.transform({ date })` became the same per-row map in
+JS. clix's `toStartOf` ignores its timezone argument (`query-builder.ts:717-734`),
+so `bucketStart` emits the same expression.
+
+Both sides were run through the REAL functions — V1 materialised from HEAD with
+its `overviewService` import pointed at HEAD's `getRawWhereClause`, V2 as
+committed — behind a recording ClickHouse client that still executes and returns
+the real response, so no statement here was retyped. Filters:
+`[{name:'country',operator:'is',value:['US']}]`, project `secure-privacy`,
+window `2026-07-01` … `2026-07-08`, interval `day`, `session_timezone=UTC` on
+both sides. Queries 2 and 3 race inside `Promise.all`, so they are matched by
+shape, not by recording order. `getReferrerSpikes`'s own return value is
+byte-identical between the two (`JSON.stringify(v1) === JSON.stringify(v2)`).
+
+**topReferrers** — IDENTICAL; rows V1/V2 = 8/8; rows_read V1/V2 = 65436/65436; wall V1/V2 = 37 ms / 12 ms; `meta` identical ([{"name": "referrer_name", "type": "String"}, {"name": "total", "type": "Int64"}]); clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT referrer_name, sum(sign) AS total FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND referrer_name != '' AND referrer_name IS NOT NULL AND country = 'US' GROUP BY referrer_name HAVING sum(sign) >= 10 ORDER BY total DESC LIMIT 50
+-- V2
+SELECT referrer_name, sum(sign) AS total FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND referrer_name != '' AND referrer_name IS NOT NULL AND country = {p4:String} GROUP BY referrer_name HAVING sum(sign) >= {p5:UInt64} ORDER BY total DESC LIMIT {p6:UInt64}
+-- V2 params: {"p1": "secure-privacy", "p2": "2026-07-01 00:00:00", "p3": "2026-07-08 00:00:00", "p4": "US", "p5": 10, "p6": 50}
+```
+
+**perBucketSessions** — IDENTICAL; rows V1/V2 = 47/47; rows_read V1/V2 = 65436/65436; wall V1/V2 = 13 ms / 12 ms; `meta` identical ([{"name": "date", "type": "DateTime"}, {"name": "referrer_name", "type": "String"}, {"name": "sessions", "type": "Int64"}]); clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT toStartOfDay(created_at) AS date, referrer_name, sum(sign) AS sessions FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND referrer_name IN ('Google', 'https://www.bwtrailerhitches.com', 'https://www.kingandprince.com', 'https://www.propper.com', 'Bing', 'DuckDuckGo', 'Twitter', 'https://www.packetsofhope.com') AND country = 'US' GROUP BY date, referrer_name HAVING sum(sign) > 0 ORDER BY date ASC
+-- V2
+SELECT toStartOfDay(created_at) AS date, referrer_name, sum(sign) AS sessions FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND referrer_name IN {p4:Array(String)} AND country = {p5:String} GROUP BY date, referrer_name HAVING sum(sign) > 0 ORDER BY date ASC
+-- V2 params: {"p1": "secure-privacy", "p2": "2026-07-01 00:00:00", "p3": "2026-07-08 00:00:00", "p4": ["Google", "https://www.bwtrailerhitches.com", "https://www.kingandprince.com", "https://www.propper.com", "Bing", "DuckDuckGo", "Twitter", "https://www.packetsofhope.com"], "p5": "US"}
+```
+
+**bucketTotals** — IDENTICAL; rows V1/V2 = 7/7; rows_read V1/V2 = 65436/65436; wall V1/V2 = 14 ms / 10 ms; `meta` identical ([{"name": "date", "type": "DateTime"}, {"name": "total", "type": "Int64"}]); clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT toStartOfDay(created_at) AS date, sum(sign) AS total FROM sessions FINAL WHERE project_id = 'secure-privacy' AND created_at BETWEEN toDateTime('2026-07-01 00:00:00') AND toDateTime('2026-07-08 00:00:00') AND country = 'US' GROUP BY date HAVING sum(sign) > 0
+-- V2
+SELECT toStartOfDay(created_at) AS date, sum(sign) AS total FROM sessions FINAL WHERE project_id = {p1:String} AND created_at BETWEEN toDateTime({p2:String}) AND toDateTime({p3:String}) AND country = {p4:String} GROUP BY date HAVING sum(sign) > 0
+-- V2 params: {"p1": "secure-privacy", "p2": "2026-07-01 00:00:00", "p3": "2026-07-08 00:00:00", "p4": "US"}
+```
+## `compiledText` callers left
+
+Every `compiledText(` / `compiledTextWithProfileRefs(` call that wrapped a
+`getEventFiltersWhereClause` result is gone — `chart.sql.ts` (two sites),
+`funnel.sql.ts`, `retention.sql.ts`, `conversion.sql.ts` (via `stepCondition`),
+`sankey.sql.ts` (via `sessionEventCte`) and `overview.sql.ts` (via `rawWhere`)
+all interpolate the fragment directly now. What remains wraps **only**
+field-resolution output or a static SQL literal — M12-003's job — plus
+`filter-where.ts`'s own two calls into the field resolver:
+
+| file:line | what it wraps |
+|---|---|
+| `packages/core/src/modules/chart/src/filter-where.ts:144` | `getGroupPropertySql(name)` — field resolver |
+| `packages/core/src/modules/chart/src/filter-where.ts:243` | `getSelectPropertyKey(...)` — field resolver |
+| `packages/core/src/modules/chart/src/chart.sql.ts:178` | a CTE name (static) |
+| `packages/core/src/modules/chart/src/chart.sql.ts:282` | a select-field list built from field-resolution output |
+| `packages/core/src/modules/chart/src/chart.sql.ts:332` | `spliced` — field resolver + profile-ref rewrite |
+| `packages/core/src/modules/chart/src/chart.sql.ts:348` | a cohort CTE name (static) |
+| `packages/core/src/modules/chart/src/chart.sql.ts:442` | a `label_N` alias (static) |
+| `packages/core/src/modules/chart/src/chart.sql.ts:443` | a `label_N` alias (static) |
+| `packages/core/src/modules/chart/src/chart.sql.ts:476` | a math aggregate name (closed set) |
+| `packages/core/src/modules/chart/src/chart.sql.ts:587` | a `label_N` alias (static) |
+| `packages/core/src/modules/chart/src/chart.sql.ts:691` | field-resolution select expression |
+| `packages/core/src/modules/chart/src/chart.sql.ts:700` | field-resolution select expression |
+| `packages/core/src/modules/chart/src/chart.sql.ts:713` | field-resolution select expression |
+| `packages/core/src/modules/chart/src/chart.sql.ts:797` | `getSelectPropertyKey(...)` — field resolver |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:79` | `STRICT_INCREASE_MODE` (static) |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:180` | `getSelectPropertyKey(...)` — field resolver |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:189` | a `b_N` alias (static) |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:303` | a `b_N` alias (static) |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:310` | a profile column list (`sql.id`-validated upstream) |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:323` | `buildInlineCohortJoin(...)` — field resolver |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:362` | a `b_N` alias (static) |
+| `packages/core/src/modules/chart/src/funnel.sql.ts:387` | a `b_N` normalisation expression (static) |
+| `packages/core/src/modules/chart/src/conversion.sql.ts:116` | a `b_N` alias (static) |
+| `packages/core/src/modules/chart/src/conversion.sql.ts:131` | field-resolution breakdown selects |
+| `packages/core/src/modules/chart/src/conversion.sql.ts:135` | field-resolution breakdown expressions |
+| `packages/core/src/modules/chart/src/conversion.sql.ts:151` | `buildInlineCohortJoin(...)` — field resolver |
+| `packages/core/src/modules/chart/src/retention.sql.ts:170` | `SQL_START_OF[interval]` (closed set) |
+| `packages/core/src/modules/chart/src/retention.sql.ts:171` | an interval unit (closed set) |
+| `packages/core/src/modules/chart/src/retention.sql.ts:172` | `COUNT_CRITERIA[criteria]` (closed set) |
+| `packages/core/src/modules/chart/src/retention.sql.ts:200` | a numeric column index (static) |
+| `packages/core/src/modules/chart/src/retention.sql.ts:206` | a numeric column index (static) |
+| `packages/core/src/modules/chart/src/sankey.sql.ts:28` | `DEDUPE_CONSECUTIVE` (static) |
+| `packages/core/src/modules/chart/src/sankey.sql.ts:38` | `TRUNCATE_AT_REPEAT` (static) |
+| `packages/core/src/modules/chart/src/sankey.sql.ts:48` | `TRANSITION_PAIRS` (static) |
+| `packages/core/src/modules/chart/src/sankey.sql.ts:187` | `BETWEEN_SLICE` (static) |
+| `packages/core/src/modules/chart/src/sankey.sql.ts:201` | a CTE name (static) |
+| `packages/core/src/modules/overview/src/overview.sql.ts:117` | `toIntervalStep(interval)` (closed set) |
+| `packages/core/src/modules/overview/src/overview.sql.ts:672` | `getSelectPropertyKey('properties.href')` — field resolver |
+
+(`grep -rn "compiledText" packages/core/src --include=*.ts | grep -v src/compiled.ts`,
+2026-09-07, minus the two `import` lines.)
+
+## Tests whose assertion moved from TEXT to statement + params
+
+| test | before | after |
+|---|---|---|
+| `overview.service / getRawWhereClause (UTM remapping)` › `rewrites utm_* to properties[__query.utm_*] for the events table` | `expect(where).toContain("properties['__query.utm_source']")` on the returned string | same `toContain` on `rendered(...).query`, **plus** `expect(query_params).toEqual({ p1: 'awn' })` |
+| … › `keeps utm_* as a top-level column for the sessions table` | `expect(where).toMatch(/(?<![._\w])utm_source\s*=/)` on the string | same `toMatch` on `.query`, **plus** `expect(query_params).toEqual({ p1: 'awn' })` |
+| … › `drops non-whitelisted filters` | `expect(where).toBe('')` | `expect(where).toBeNull()` — `joinFilterClauses` returns `null`, not `''` |
+| … › `events utm_source filter parses against real events table` | `EXPLAIN` of a string-spliced statement | `EXPLAIN` of `.query` **with `query_params` passed to `ch.command`** — the params now have to bind for the EXPLAIN to pass |
+| … › `sessions utm_source filter parses against real sessions table` | as above | as above |
+
+No other test changed what it asserts. `event.sql.test.ts`,
+`profile.sql.test.ts` and `session.sql.test.ts` keep their expected SQL text
+byte-for-byte; only their `filterClauses` INPUT fixtures moved from
+`{ f0: "(path = '/')" }` to `compiledFilterClauses({ f0: "(path = '/')" })`,
+because `CompiledFilterClauses` is now `Record<string, SqlFragment>` while
+`buildFilterWhere` (M12-003) still returns text. `overview.sql.test.ts` moved
+its `rawFilterWhere: ''` fixtures to `rawFilterWhere: null` for the same reason.
+`chart.sql.test.ts` and `funnel.sql.test.ts` are untouched — they assert on
+column expressions, which still come from the field resolver.
+
+## Reproducing a case
+
+Every statement above runs as written. V1:
+
+```bash
+curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC&default_format=JSONCompact' \
+ --data-binary "SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = 'secure-privacy' AND created_at >= toDateTime('2026-07-01 00:00:00') AND created_at < toDateTime('2026-07-08 00:00:00') AND (path = '/')"
+```
+
+V2 — bind each `{pN:...}` / `{wN:...}` as `param_pN=` / `param_wN=`:
+
+```bash
+curl -s -G 'http://127.0.0.1:8123/' \
+ --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \
+ --data-urlencode 'default_format=JSONCompact' \
+ --data-urlencode 'param_w1=secure-privacy' \
+ --data-urlencode 'param_w2=2026-07-01 00:00:00' \
+ --data-urlencode 'param_w3=2026-07-08 00:00:00' \
+ --data-urlencode 'param_p1=/' \
+ --data-urlencode "query=SELECT count() AS c, uniq(profile_id) AS u FROM events WHERE project_id = {w1:String} AND created_at >= toDateTime({w2:String}) AND created_at < toDateTime({w3:String}) AND (path = {p1:String})"
+```
+
+Both return `[[3066,986]]`.
+
+## Goldens
+
+`verification/golden/compare.sh` against the harness (`verification/harness
+start`, api and worker both V2), run 2026-09-07 on this box after
+`apps/api pnpm run e2e:sessions`:
+
+```
+target: http://127.0.0.1:3333
+golden: http://127.0.0.1:3333 @ 2026-09-07T02:43:29Z
+passed: 137/137
+OK: zero diffs
+```
+
+**137/137, zero diffs, and no `stale:` line** — every one of the 137 cases
+compared; none was skipped for a rolled UTC day. `full.sh` re-ran the whole
+manifest against a freshly started harness later in the same session and
+reported `passed: 137/137` / `OK: zero diffs` again.
+
+The known unstable case, `insights-event-property-values`, passed in both runs.
+It reads `event_property_values_mv` — an `AggregatingMergeTree` whose `ORDER BY`
+does not include `created_at`, queried `ORDER BY created_at DESC LIMIT 200`, so
+its top-200 reshuffles whenever a background merge lands. It is not in this
+task's path either way: it is served by `eventPropertyValuesQuery`
+(`packages/core/src/modules/event/src/event.sql.ts`), which imports no filter
+compiler and is not in this diff.
+
+## Verification run
+
+All commands run in `/home/deploy/openpanel` on 2026-09-07 against the tree as
+committed. `verification/` paths are in `/home/deploy/rewrite-openpanel`.
+
+| command | result |
+|---|---|
+| `pnpm run typecheck` | green — every workspace `Done` |
+| `cd packages/core && bun test` | `1469 pass, 12 skip, 0 fail`, 4760 expect() calls, 1481 tests across 153 files |
+| `pnpm test` (`bun test --isolate` at the root) | `1469 pass, 12 skip, 0 fail`, 1481 tests across 153 files |
+| `pnpm run check:deps` | `no dependency violations found (2271 modules, 9839 dependencies cruised)` |
+| `bash tooling/gates/p12-grep-gates.sh --report` | TOTAL `sqlstring 115 / clix 73 / sql-builder 6` (baseline `168 / 77 / 6`); `filter-where.ts` no longer appears in the table at all |
+| `test -f packages/core/src/modules/chart/src/filter-where.sql.proof.md` | present (this file) |
+| `verification/harness start` | `OK: api ready on :3333 (3s)` / `OK: worker ready on :9999 (3s)`, both V2 |
+| `cd apps/api && timeout 900 pnpm run e2e:sessions` | **29/29 checks passed** |
+| `verification/golden/compare.sh` | **`passed: 137/137`**, `OK: zero diffs`, no stale |
+| `verification/harness stop` | `OK: api stopped` / `OK: worker stopped` |
+| `verification/full.sh` | **`FULL: green`, RC=0** — 22 `OK:` stages, zero `FAIL:`, zero `BLOCKED`; includes forbidden-patterns, install, typecheck api + start, `pnpm test`, golden seed, harness, `golden/compare.sh` 137/137, `contracts/auth`, `contracts/sdk` (incl. the dist gate), `golden/openapi v2-diff` |
+
+### Gate movement
+
+`sqlstring` dropped by 53 — all of `filter-where.ts`, which leaves the table
+with 0 in every column. `clix` dropped by 4: `referrer-spikes.ts`, converted
+because the fragment's params cannot cross clix's `execute()` — see *Consumer
+conversion* above. Nothing else moved; `sql-builder` is unchanged at 6.
+
+### Lint
+
+`npx ultracite check` on the 25 changed `.ts` files reports 4 errors, all
+pre-existing: the identical 4 fire on the same two files restored from HEAD
+(`overview.service.ts` `useConsistentTypeDefinitions` at HEAD:98 / here:101 and
+`noUnusedVariables` at HEAD:45 / here:48; two `noMisplacedAssertion` in
+`overview-raw-where.sql.test.ts`, where Biome does not recognise the file's
+`itCH(...)` wrapper as a test call, at HEAD:95,108 / here:115,131). Only the
+line numbers move. No new lint debt.
diff --git a/packages/core/src/modules/chart/src/filter-where.ts b/packages/core/src/modules/chart/src/filter-where.ts
index 8a1ec8d57..98e2ee69a 100644
--- a/packages/core/src/modules/chart/src/filter-where.ts
+++ b/packages/core/src/modules/chart/src/filter-where.ts
@@ -1,15 +1,20 @@
/** biome-ignore-all lint/style/useDefaultSwitchClause: operator switches are exhaustive by design */
-// V1's event filter compiler (`getEventFiltersWhereClause`), moved verbatim
-// from packages/db/src/services/chart.service.ts (M7-003). Renders TEXT with
-// sqlstring: ADR-013 keeps the shared filter compilers as they are until
-// funnel, conversion, sankey, retention and overview (M7-004/M7-005) stop
-// splicing their output into text builders. Core splices it through
-// compiled.ts, the one text bridge.
+// 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`.
-import sqlstring from 'sqlstring';
+import {
+ type SqlFragment,
+ type SqlSlot,
+ sql,
+} from '@openpanel/db/src/clickhouse/sql';
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,
@@ -19,10 +24,47 @@ import {
isNumericColumn,
normalizeEventField,
} from './field-resolution';
-import { buildTypedClause, hasTypedCast, isTypedOperator } from './filter-cast';
+import {
+ buildTypedClauseFragment,
+ hasTypedCast,
+ isTypedOperator,
+} from './filter-cast';
export type FilterTableScope = 'events' | 'sessions';
+/** One clause per surviving filter, keyed `f<index>` as V1 keyed them. */
+export type CompiledEventFilters = Record<string, SqlFragment>;
+
+// `sql.id`'s whitelist takes an array; the events branch has already rejected
+// anything outside the set by the time it gets here.
+const EVENT_COLUMN_ALLOWLIST = Array.from(EVENT_TOP_LEVEL_COLUMNS);
+
+/** V1 stringified and trimmed every untyped value before escaping it. */
+function filterValue(value: unknown) {
+ return sql.string(String(value).trim());
+}
+
+/** V1's `(<a> OR <b>)` — the parenthesised disjunction. */
+function anyOf(clauses: SqlFragment[]): SqlFragment {
+ return sql`(${sql.join(clauses, ' OR ')})`;
+}
+
+/** V1's `arrayExists(x -> <a> OR <b>, <haystack>)` — no outer parentheses. */
+function anyItem(clauses: SqlFragment[], haystack: SqlSlot): SqlFragment {
+ return sql`arrayExists(x -> ${sql.join(clauses, ' OR ')}, ${haystack})`;
+}
+
+/**
+ * Combine compiled clauses the way every caller that wants one expression
+ * does. `null` when nothing survived, so a caller can drop the `AND` with it.
+ */
+export function joinFilterClauses(
+ clauses: CompiledEventFilters
+): SqlFragment | null {
+ const parts = Object.values(clauses);
+ return parts.length === 0 ? null : sql.join(parts, ' AND ');
+}
+
export function getEventFiltersWhereClause(
filters: IChartEventFilter[],
projectId?: string,
@@ -42,8 +84,8 @@ export function getEventFiltersWhereClause(
* sets it to 'sessions' when querying the sessions table.
*/
tableScope: FilterTableScope = 'events'
-) {
- const where: Record<string, string> = {};
+): CompiledEventFilters {
+ const where: CompiledEventFilters = {};
filters.forEach((filter, index) => {
const id = `f${index}`;
const { value, operator } = filter;
@@ -68,12 +110,15 @@ export function getEventFiltersWhereClause(
return;
}
const profileIdExpr = eventsAlias
- ? `${eventsAlias}.profile_id`
- : 'profile_id';
- const op = operator === 'notInCohort' ? 'NOT IN' : 'IN';
- const escapedIds = cohortIds.map((c) => sqlstring.escape(c)).join(', ');
+ ? sql.id(`${eventsAlias}.profile_id`)
+ : sql.id('profile_id');
+ // V1 wrote a plain `IN (subquery)` here; ADR-013 conversions never
+ // change IN/GLOBAL IN in either direction (docs/ENVIRONMENT.md).
+ 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)})`;
where[id] =
- `${profileIdExpr} ${op} (SELECT profile_id FROM ${CHART_TABLE.cohortMembers} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;
+ operator === 'notInCohort'
+ ? sql`${profileIdExpr} NOT IN ${members}`
+ : sql`${profileIdExpr} IN ${members}`;
return;
}
@@ -87,72 +132,96 @@ export function getEventFiltersWhereClause(
if (name === 'has_profile') {
if (value.includes('true')) {
- where[id] = 'profile_id != device_id';
+ where[id] = sql`profile_id != device_id`;
} else {
- where[id] = 'profile_id = device_id';
+ where[id] = sql`profile_id = device_id`;
}
return;
}
// Handle group. prefixed filters (requires ARRAY JOIN + _g JOIN in query)
if (name.startsWith('group.') && projectId) {
- const whereFrom = getGroupPropertySql(name);
+ const whereFrom = compiledText(getGroupPropertySql(name));
if (hasTypedCast(filter.type) && isTypedOperator(operator)) {
- where[id] = buildTypedClause(whereFrom, operator, value, filter.type);
+ where[id] = buildTypedClauseFragment(
+ whereFrom,
+ operator,
+ value,
+ filter.type
+ );
return;
}
switch (operator) {
case 'is': {
if (value.length === 1) {
- where[id] =
- `${whereFrom} = ${sqlstring.escape(String(value[0]).trim())}`;
+ where[id] = sql`${whereFrom} = ${filterValue(value[0])}`;
} else {
- where[id] =
- `${whereFrom} IN (${value.map((val) => sqlstring.escape(String(val).trim())).join(', ')})`;
+ where[id] = sql`${whereFrom} IN ${sql.array(
+ 'String',
+ value.map((val) => String(val).trim())
+ )}`;
}
break;
}
case 'isNot': {
if (value.length === 1) {
- where[id] =
- `${whereFrom} != ${sqlstring.escape(String(value[0]).trim())}`;
+ where[id] = sql`${whereFrom} != ${filterValue(value[0])}`;
} else {
- where[id] =
- `${whereFrom} NOT IN (${value.map((val) => sqlstring.escape(String(val).trim())).join(', ')})`;
+ where[id] = sql`${whereFrom} NOT IN ${sql.array(
+ 'String',
+ value.map((val) => String(val).trim())
+ )}`;
}
break;
}
case 'contains': {
- where[id] =
- `(${value.map((val) => `${whereFrom} LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`).join(' OR ')})`;
+ where[id] = anyOf(
+ value.map(
+ (val) =>
+ sql`${whereFrom} LIKE ${sql.string(`%${String(val).trim()}%`)}`
+ )
+ );
break;
}
case 'doesNotContain': {
- where[id] =
- `(${value.map((val) => `${whereFrom} NOT LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`).join(' OR ')})`;
+ where[id] = anyOf(
+ value.map(
+ (val) =>
+ sql`${whereFrom} NOT LIKE ${sql.string(`%${String(val).trim()}%`)}`
+ )
+ );
break;
}
case 'startsWith': {
- where[id] =
- `(${value.map((val) => `${whereFrom} LIKE ${sqlstring.escape(`${String(val).trim()}%`)}`).join(' OR ')})`;
+ where[id] = anyOf(
+ value.map(
+ (val) =>
+ sql`${whereFrom} LIKE ${sql.string(`${String(val).trim()}%`)}`
+ )
+ );
break;
}
case 'endsWith': {
- where[id] =
- `(${value.map((val) => `${whereFrom} LIKE ${sqlstring.escape(`%${String(val).trim()}`)}`).join(' OR ')})`;
+ where[id] = anyOf(
+ value.map(
+ (val) =>
+ sql`${whereFrom} LIKE ${sql.string(`%${String(val).trim()}`)}`
+ )
+ );
break;
}
case 'isNull': {
- where[id] = `(${whereFrom} = '' OR ${whereFrom} IS NULL)`;
+ where[id] = sql`(${whereFrom} = '' OR ${whereFrom} IS NULL)`;
break;
}
case 'isNotNull': {
- where[id] = `(${whereFrom} != '' AND ${whereFrom} IS NOT NULL)`;
+ where[id] = sql`(${whereFrom} != '' AND ${whereFrom} IS NOT NULL)`;
break;
}
case 'regex': {
- where[id] =
- `(${value.map((val) => `match(${whereFrom}, ${sqlstring.escape(String(val).trim())})`).join(' OR ')})`;
+ where[id] = anyOf(
+ value.map((val) => sql`match(${whereFrom}, ${filterValue(val)})`)
+ );
break;
}
}
@@ -171,7 +240,7 @@ export function getEventFiltersWhereClause(
eventsAlias
);
const isWildcard = propertyKey.includes('%');
- const whereFrom = propertyKey;
+ const whereFrom = compiledText(propertyKey);
// Typed cast (number/date/datetime/boolean) short-circuit. Casts both the
// column and each value so e.g. `>= '2019-01-01'` compares as dates
@@ -179,213 +248,177 @@ export function getEventFiltersWhereClause(
// fall through to the legacy switch below.
if (hasTypedCast(filter.type) && isTypedOperator(operator)) {
where[id] = isWildcard
- ? `arrayExists(x -> ${buildTypedClause('x', operator, value, filter.type)}, ${whereFrom})`
- : buildTypedClause(whereFrom, operator, value, filter.type);
+ ? sql`arrayExists(x -> ${buildTypedClauseFragment(sql`x`, operator, value, filter.type)}, ${whereFrom})`
+ : buildTypedClauseFragment(whereFrom, operator, value, filter.type);
return;
}
switch (operator) {
case 'is': {
if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map((val) => `x = ${sqlstring.escape(String(val).trim())}`)
- .join(' OR ')}, ${whereFrom})`;
+ where[id] = anyItem(
+ value.map((val) => sql`x = ${filterValue(val)}`),
+ whereFrom
+ );
} else if (value.length === 1) {
- where[id] =
- `${whereFrom} = ${sqlstring.escape(String(value[0]).trim())}`;
+ where[id] = sql`${whereFrom} = ${filterValue(value[0])}`;
} else {
- where[id] = `${whereFrom} IN (${value
- .map((val) => sqlstring.escape(String(val).trim()))
- .join(', ')})`;
+ where[id] = sql`${whereFrom} IN ${sql.array(
+ 'String',
+ value.map((val) => String(val).trim())
+ )}`;
}
break;
}
case 'isNot': {
if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map((val) => `x != ${sqlstring.escape(String(val).trim())}`)
- .join(' OR ')}, ${whereFrom})`;
+ where[id] = anyItem(
+ value.map((val) => sql`x != ${filterValue(val)}`),
+ whereFrom
+ );
} else if (value.length === 1) {
- where[id] =
- `${whereFrom} != ${sqlstring.escape(String(value[0]).trim())}`;
+ where[id] = sql`${whereFrom} != ${filterValue(value[0])}`;
} else {
- where[id] = `${whereFrom} NOT IN (${value
- .map((val) => sqlstring.escape(String(val).trim()))
- .join(', ')})`;
+ where[id] = sql`${whereFrom} NOT IN ${sql.array(
+ 'String',
+ value.map((val) => String(val).trim())
+ )}`;
}
break;
}
case 'contains': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) => `x LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`
- )
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `${whereFrom} LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`
+ const like = (val: unknown) => sql.string(`%${String(val).trim()}%`);
+ where[id] = isWildcard
+ ? anyItem(
+ value.map((val) => sql`x LIKE ${like(val)}`),
+ whereFrom
)
- .join(' OR ')})`;
- }
+ : anyOf(value.map((val) => sql`${whereFrom} LIKE ${like(val)}`));
break;
}
case 'doesNotContain': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) =>
- `x NOT LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`
+ const like = (val: unknown) => sql.string(`%${String(val).trim()}%`);
+ where[id] = isWildcard
+ ? anyItem(
+ value.map((val) => sql`x NOT LIKE ${like(val)}`),
+ whereFrom
)
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `${whereFrom} NOT LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`
- )
- .join(' OR ')})`;
- }
+ : anyOf(
+ value.map((val) => sql`${whereFrom} NOT LIKE ${like(val)}`)
+ );
break;
}
case 'startsWith': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) => `x LIKE ${sqlstring.escape(`${String(val).trim()}%`)}`
- )
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `${whereFrom} LIKE ${sqlstring.escape(`${String(val).trim()}%`)}`
+ const like = (val: unknown) => sql.string(`${String(val).trim()}%`);
+ where[id] = isWildcard
+ ? anyItem(
+ value.map((val) => sql`x LIKE ${like(val)}`),
+ whereFrom
)
- .join(' OR ')})`;
- }
+ : anyOf(value.map((val) => sql`${whereFrom} LIKE ${like(val)}`));
break;
}
case 'endsWith': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) => `x LIKE ${sqlstring.escape(`%${String(val).trim()}`)}`
- )
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `${whereFrom} LIKE ${sqlstring.escape(`%${String(val).trim()}`)}`
+ const like = (val: unknown) => sql.string(`%${String(val).trim()}`);
+ where[id] = isWildcard
+ ? anyItem(
+ value.map((val) => sql`x LIKE ${like(val)}`),
+ whereFrom
)
- .join(' OR ')})`;
- }
+ : anyOf(value.map((val) => sql`${whereFrom} LIKE ${like(val)}`));
break;
}
case 'regex': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map((val) => `match(x, ${sqlstring.escape(String(val).trim())})`)
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `match(${whereFrom}, ${sqlstring.escape(String(val).trim())})`
+ where[id] = isWildcard
+ ? anyItem(
+ value.map((val) => sql`match(x, ${filterValue(val)})`),
+ whereFrom
)
- .join(' OR ')})`;
- }
+ : anyOf(
+ value.map(
+ (val) => sql`match(${whereFrom}, ${filterValue(val)})`
+ )
+ );
break;
}
case 'isNull': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> x = '' OR x IS NULL, ${whereFrom})`;
- } else {
- where[id] = `(${whereFrom} = '' OR ${whereFrom} IS NULL)`;
- }
+ where[id] = isWildcard
+ ? sql`arrayExists(x -> x = '' OR x IS NULL, ${whereFrom})`
+ : sql`(${whereFrom} = '' OR ${whereFrom} IS NULL)`;
break;
}
case 'isNotNull': {
- if (isWildcard) {
- where[id] =
- `arrayExists(x -> x != '' AND x IS NOT NULL, ${whereFrom})`;
- } else {
- where[id] = `(${whereFrom} != '' AND ${whereFrom} IS NOT NULL)`;
- }
+ where[id] = isWildcard
+ ? sql`arrayExists(x -> x != '' AND x IS NOT NULL, ${whereFrom})`
+ : sql`(${whereFrom} != '' AND ${whereFrom} IS NOT NULL)`;
break;
}
case 'gt': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) =>
- `toFloat64OrZero(x) > toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64OrZero(${whereFrom}) > toFloat64(${sqlstring.escape(String(val).trim())})`
+ where[id] = isWildcard
+ ? anyItem(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(x) > toFloat64(${filterValue(val)})`
+ ),
+ whereFrom
)
- .join(' OR ')})`;
- }
+ : anyOf(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(${whereFrom}) > toFloat64(${filterValue(val)})`
+ )
+ );
break;
}
case 'lt': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) =>
- `toFloat64OrZero(x) < toFloat64(${sqlstring.escape(String(val).trim())})`
+ where[id] = isWildcard
+ ? anyItem(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(x) < toFloat64(${filterValue(val)})`
+ ),
+ whereFrom
)
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64OrZero(${whereFrom}) < toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')})`;
- }
+ : anyOf(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(${whereFrom}) < toFloat64(${filterValue(val)})`
+ )
+ );
break;
}
case 'gte': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) =>
- `toFloat64OrZero(x) >= toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64OrZero(${whereFrom}) >= toFloat64(${sqlstring.escape(String(val).trim())})`
+ where[id] = isWildcard
+ ? anyItem(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(x) >= toFloat64(${filterValue(val)})`
+ ),
+ whereFrom
)
- .join(' OR ')})`;
- }
+ : anyOf(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(${whereFrom}) >= toFloat64(${filterValue(val)})`
+ )
+ );
break;
}
case 'lte': {
- if (isWildcard) {
- where[id] = `arrayExists(x -> ${value
- .map(
- (val) =>
- `toFloat64OrZero(x) <= toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')}, ${whereFrom})`;
- } else {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64OrZero(${whereFrom}) <= toFloat64(${sqlstring.escape(String(val).trim())})`
+ where[id] = isWildcard
+ ? anyItem(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(x) <= toFloat64(${filterValue(val)})`
+ ),
+ whereFrom
)
- .join(' OR ')})`;
- }
+ : anyOf(
+ value.map(
+ (val) =>
+ sql`toFloat64OrZero(${whereFrom}) <= toFloat64(${filterValue(val)})`
+ )
+ );
break;
}
}
@@ -399,150 +432,137 @@ export function getEventFiltersWhereClause(
if (tableScope === 'events' && !EVENT_TOP_LEVEL_COLUMNS.has(name)) {
return;
}
+ // ADR-013 R3: the sessions branch has no closed set here, so `sql.id`
+ // validates the shape and throws rather than inlining anything else.
+ const column =
+ tableScope === 'events'
+ ? sql.id(name, EVENT_COLUMN_ALLOWLIST)
+ : sql.id(name);
// Typed cast short-circuit (see property branch above). Supersedes the
// `isNumericColumn` auto-detect when the user declared an explicit type.
if (hasTypedCast(filter.type) && isTypedOperator(operator)) {
- where[id] = buildTypedClause(name, operator, value, filter.type);
+ where[id] = buildTypedClauseFragment(
+ column,
+ operator,
+ value,
+ filter.type
+ );
return;
}
switch (operator) {
case 'is': {
if (value.length === 1) {
- where[id] =
- `${name} = ${sqlstring.escape(String(value[0]).trim())}`;
+ where[id] = sql`${column} = ${filterValue(value[0])}`;
} else {
- where[id] = `${name} IN (${value
- .map((val) => sqlstring.escape(String(val).trim()))
- .join(', ')})`;
+ where[id] = sql`${column} IN ${sql.array(
+ 'String',
+ value.map((val) => String(val).trim())
+ )}`;
}
break;
}
case 'isNull': {
- where[id] = `(${name} = '' OR ${name} IS NULL)`;
+ where[id] = sql`(${column} = '' OR ${column} IS NULL)`;
break;
}
case 'isNotNull': {
- where[id] = `(${name} != '' AND ${name} IS NOT NULL)`;
+ where[id] = sql`(${column} != '' AND ${column} IS NOT NULL)`;
break;
}
case 'isNot': {
if (value.length === 1) {
- where[id] =
- `${name} != ${sqlstring.escape(String(value[0]).trim())}`;
+ where[id] = sql`${column} != ${filterValue(value[0])}`;
} else {
- where[id] = `${name} NOT IN (${value
- .map((val) => sqlstring.escape(String(val).trim()))
- .join(', ')})`;
+ where[id] = sql`${column} NOT IN ${sql.array(
+ 'String',
+ value.map((val) => String(val).trim())
+ )}`;
}
break;
}
case 'contains': {
- where[id] = `(${value
- .map(
+ where[id] = anyOf(
+ value.map(
(val) =>
- `${name} LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`
+ sql`${column} LIKE ${sql.string(`%${String(val).trim()}%`)}`
)
- .join(' OR ')})`;
+ );
break;
}
case 'doesNotContain': {
- where[id] = `(${value
- .map(
+ where[id] = anyOf(
+ value.map(
(val) =>
- `${name} NOT LIKE ${sqlstring.escape(`%${String(val).trim()}%`)}`
+ sql`${column} NOT LIKE ${sql.string(`%${String(val).trim()}%`)}`
)
- .join(' OR ')})`;
+ );
break;
}
case 'startsWith': {
- where[id] = `(${value
- .map(
+ where[id] = anyOf(
+ value.map(
(val) =>
- `${name} LIKE ${sqlstring.escape(`${String(val).trim()}%`)}`
+ sql`${column} LIKE ${sql.string(`${String(val).trim()}%`)}`
)
- .join(' OR ')})`;
+ );
break;
}
case 'endsWith': {
- where[id] = `(${value
- .map(
+ where[id] = anyOf(
+ value.map(
(val) =>
- `${name} LIKE ${sqlstring.escape(`%${String(val).trim()}`)}`
+ sql`${column} LIKE ${sql.string(`%${String(val).trim()}`)}`
)
- .join(' OR ')})`;
+ );
break;
}
case 'regex': {
- where[id] = `(${value
- .map(
+ where[id] = anyOf(
+ value.map(
(val) =>
- `match(${name}, ${sqlstring.escape(stripLeadingAndTrailingSlashes(String(val)).trim())})`
+ sql`match(${column}, ${sql.string(stripLeadingAndTrailingSlashes(String(val)).trim())})`
)
- .join(' OR ')})`;
+ );
break;
}
case 'gt': {
- if (isNumericColumn(name)) {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64(${name}) > toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')})`;
- } else {
- where[id] = `(${value
- .map((val) => `${name} > ${sqlstring.escape(String(val).trim())}`)
- .join(' OR ')})`;
- }
+ where[id] = anyOf(
+ value.map((val) =>
+ isNumericColumn(name)
+ ? sql`toFloat64(${column}) > toFloat64(${filterValue(val)})`
+ : sql`${column} > ${filterValue(val)}`
+ )
+ );
break;
}
case 'lt': {
- if (isNumericColumn(name)) {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64(${name}) < toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')})`;
- } else {
- where[id] = `(${value
- .map((val) => `${name} < ${sqlstring.escape(String(val).trim())}`)
- .join(' OR ')})`;
- }
+ where[id] = anyOf(
+ value.map((val) =>
+ isNumericColumn(name)
+ ? sql`toFloat64(${column}) < toFloat64(${filterValue(val)})`
+ : sql`${column} < ${filterValue(val)}`
+ )
+ );
break;
}
case 'gte': {
- if (isNumericColumn(name)) {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64(${name}) >= toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')})`;
- } else {
- where[id] = `(${value
- .map(
- (val) => `${name} >= ${sqlstring.escape(String(val).trim())}`
- )
- .join(' OR ')})`;
- }
+ where[id] = anyOf(
+ value.map((val) =>
+ isNumericColumn(name)
+ ? sql`toFloat64(${column}) >= toFloat64(${filterValue(val)})`
+ : sql`${column} >= ${filterValue(val)}`
+ )
+ );
break;
}
case 'lte': {
- if (isNumericColumn(name)) {
- where[id] = `(${value
- .map(
- (val) =>
- `toFloat64(${name}) <= toFloat64(${sqlstring.escape(String(val).trim())})`
- )
- .join(' OR ')})`;
- } else {
- where[id] = `(${value
- .map(
- (val) => `${name} <= ${sqlstring.escape(String(val).trim())}`
- )
- .join(' OR ')})`;
- }
+ where[id] = anyOf(
+ value.map((val) =>
+ isNumericColumn(name)
+ ? sql`toFloat64(${column}) <= toFloat64(${filterValue(val)})`
+ : sql`${column} <= ${filterValue(val)}`
+ )
+ );
break;
}
}
diff --git a/packages/core/src/modules/chart/src/funnel.sql.ts b/packages/core/src/modules/chart/src/funnel.sql.ts
index cefc0685e..29aa3105f 100644
--- a/packages/core/src/modules/chart/src/funnel.sql.ts
+++ b/packages/core/src/modules/chart/src/funnel.sql.ts
@@ -27,7 +27,11 @@ import type {
IChartBreakdown,
IChartEvent,
} from '../../report/report.constants';
-import { compiledText, compiledTextWithProfileRefs } from './compiled';
+import {
+ compiledText,
+ compiledTextWithProfileRefs,
+ fragmentWithProfileRefs,
+} from './compiled';
import {
buildInlineCohortJoin,
CHART_TABLE,
@@ -142,11 +146,7 @@ export function funnelStepConditions(
// profile.properties.Y.
const filters = Object.values(
getEventFiltersWhereClause(event.filters, projectId, 'events')
- )
- .filter(Boolean)
- .map((clause) =>
- compiledTextWithProfileRefs(clause, profilePropertyKeys)
- );
+ ).map((clause) => fragmentWithProfileRefs(clause, profilePropertyKeys));
return sql.join(
[...filters, sql`events.name = ${sql.string(event.name)}`],
' AND '
diff --git a/packages/core/src/modules/chart/src/retention.sql.ts b/packages/core/src/modules/chart/src/retention.sql.ts
index 6a60eeeb5..907993e5c 100644
--- a/packages/core/src/modules/chart/src/retention.sql.ts
+++ b/packages/core/src/modules/chart/src/retention.sql.ts
@@ -188,9 +188,7 @@ export function retentionCohortQuery(
}
if (filters.length > 0) {
baseConditions.push(
- ...Object.values(getEventFiltersWhereClause(filters, projectId)).map(
- compiledText
- )
+ ...Object.values(getEventFiltersWhereClause(filters, projectId))
);
}
const baseWhere = sql.join(baseConditions, ' AND ');
diff --git a/packages/core/src/modules/chart/src/sankey.sql.ts b/packages/core/src/modules/chart/src/sankey.sql.ts
index 26176feb5..a40b48b71 100644
--- a/packages/core/src/modules/chart/src/sankey.sql.ts
+++ b/packages/core/src/modules/chart/src/sankey.sql.ts
@@ -54,7 +54,7 @@ const MIN_PATH_LENGTH = 2;
export interface SankeyEvent {
name: string;
/** Compiled filter clauses for this event's session CTE. */
- whereClause: string;
+ whereClause: SqlFragment | null;
}
export interface SankeyPathsInput {
@@ -99,7 +99,7 @@ function sessionEventCte(
input: SankeyPathsInput
): SqlFragment {
const filters = event.whereClause
- ? sql` AND ${compiledText(event.whereClause)}`
+ ? sql` AND ${event.whereClause}`
: sql.empty;
return sql`SELECT session_id FROM ${sql.id(CHART_TABLE.events)} WHERE project_id = ${sql.string(input.projectId)} AND name = ${sql.string(event.name)} AND created_at BETWEEN toDateTime(${sql.string(input.startDate)}) AND toDateTime(${sql.string(input.endDate)})${filters} GROUP BY session_id`;
}
diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.ts
index 696b7e28a..614cd45d3 100644
--- a/packages/core/src/modules/event/event.service.ts
+++ b/packages/core/src/modules/event/event.service.ts
@@ -65,7 +65,10 @@ import {
topOriginsQuery,
topPagesQuery,
} from './src/event.sql';
-import type { CompiledFilterClauses } from './src/filter-clauses';
+import {
+ type CompiledFilterClauses,
+ compiledFilterClauses,
+} from './src/filter-clauses';
export {
EVENT_LIST_COLUMNS,
@@ -1089,10 +1092,12 @@ export async function queryEventsCore(
let filterClauses: CompiledFilterClauses = {};
if (input.filters?.length) {
const { buildFilterWhere } = await loadFilterCompiler();
- filterClauses = buildFilterWhere(
- input.filters,
- input.projectId,
- QUERY_EVENTS_FILTER_TARGET
+ filterClauses = compiledFilterClauses(
+ 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.ts
index c6020d95c..8e9d44ca5 100644
--- a/packages/core/src/modules/event/src/event.sql.test.ts
+++ b/packages/core/src/modules/event/src/event.sql.test.ts
@@ -21,6 +21,7 @@ import {
topOriginsQuery,
topPagesQuery,
} from './event.sql';
+import { compiledFilterClauses } from './filter-clauses';
const PROJECT_ID = 'proj-1';
const HOSTILE = "x' OR 1=1 --";
@@ -117,7 +118,7 @@ describe('eventListQuery', () => {
startDate: START,
endDate: END,
events: ['a', HOSTILE],
- filterClauses: { f0: "(path = '/')" },
+ filterClauses: compiledFilterClauses({ f0: "(path = '/')" }),
conversionNames: ['signup'],
}).toStatement();
@@ -181,7 +182,7 @@ describe('eventsCountQuery', () => {
startDate: START,
endDate: END,
events: ['a'],
- filterClauses: { f0: "(path = '/')" },
+ filterClauses: compiledFilterClauses({ f0: "(path = '/')" }),
joins: NO_FILTER_JOINS,
}).toStatement();
@@ -301,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: { f0: '(1 = 1)' },
+ filterClauses: compiledFilterClauses({ f0: '(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.ts
index 9ed664751..3c6c0f28a 100644
--- a/packages/core/src/modules/event/src/filter-clauses.ts
+++ b/packages/core/src/modules/event/src/filter-clauses.ts
@@ -1,23 +1,34 @@
// The ONE place this module splices pre-compiled filter SQL.
//
-// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is
-// V1's filter compiler and still emits sqlstring-escaped SQL text: ADR-013
-// leaves the filter compilers as they are ("two behaviours, not two builders")
-// until the shared filter compiler converts to fragments. Until then a
-// `sql`-tag query that takes `IChartEventFilter[]` has to splice that text,
-// and it does so 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.
+// `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.
import { SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';
-export type CompiledFilterClauses = Record<string, string>;
+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: CompiledFilterClauses
): SqlFragment[] {
- return Object.values(clauses).map((clause) => new SqlFragment([clause], []));
+ return Object.values(clauses);
}
export function spliceCompiledFilters(
diff --git a/packages/core/src/modules/insight/src/referrer-spikes.ts b/packages/core/src/modules/insight/src/referrer-spikes.ts
index c3e875be3..d71e1df8c 100644
--- a/packages/core/src/modules/insight/src/referrer-spikes.ts
+++ b/packages/core/src/modules/insight/src/referrer-spikes.ts
@@ -1,12 +1,16 @@
// M10-009: the ClickHouse CLIENT is `deps.ch` (the boot scope's round-robin
// proxy), so the requestId minted at the edge reaches these queries (ADR-018).
-// `clix` stays a value import: it is a pure query BUILDER that takes the
-// client as its first argument, not a connection — same standing as ADR-013's
-// `sql` tag (see shared/ch-query.ts). Table names and the date helper are
-// core's own copies (shared/ch-tables.ts, shared/ch-dates.ts).
-import { clix } from '@openpanel/db/src/clickhouse/query-builder';
+// Table names and the date helper are core's own copies
+// (shared/ch-tables.ts, shared/ch-dates.ts).
+//
+// M12-002 converted these three queries off clix: `getRawWhereClause` now
+// returns a `SqlFragment` carrying bound params, and clix's `.execute()` has
+// no `query_params` slot to carry them through. clix always sent
+// `session_timezone` (query-builder.ts:562) — `chQuery` gets the same value.
+import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';
import type { ServiceDeps } from '../../../services';
import { convertClickhouseDateToJs } from '../../../shared/ch-dates';
+import { chQuery } from '../../../shared/ch-query';
import { TABLE_NAMES } from '../../../shared/ch-tables';
import { overviewService } from '../../../v1-compat';
import type {
@@ -77,36 +81,62 @@ export interface GetReferrerSpikesInput {
timezone: string;
}
+/** clix's `toStartOf` (query-builder.ts:717) — the timezone arg was unused. */
+function bucketStart(interval: IInterval): SqlFragment {
+ switch (interval) {
+ case 'minute':
+ return sql`toStartOfMinute(created_at)`;
+ case 'hour':
+ return sql`toStartOfHour(created_at)`;
+ case 'day':
+ return sql`toStartOfDay(created_at)`;
+ case 'week':
+ return sql`toStartOfWeek(toDateTime(created_at))`;
+ case 'month':
+ return sql`toStartOfMonth(toDateTime(created_at))`;
+ default:
+ throw new Error(`Unsupported referrer-spike interval: ${interval}`);
+ }
+}
+
+/** The window every one of the three queries shares. */
+function sessionWindow(
+ projectId: string,
+ startDate: string,
+ endDate: string
+): SqlFragment {
+ return sql`project_id = ${sql.string(projectId)} AND created_at BETWEEN toDateTime(${sql.string(startDate)}) AND toDateTime(${sql.string(endDate)})`;
+}
+
+/** `getRawWhereClause`'s output, already bound — clix appended it the same way. */
+function andFilters(where: SqlFragment | null): SqlFragment {
+ return where ? sql` AND ${where}` : sql.empty;
+}
+
export async function getReferrerSpikes(
deps: ServiceDeps,
input: GetReferrerSpikesInput
): Promise<ReferrerSpikeCluster[]> {
- const ch = deps.ch;
const { projectId, filters, startDate, endDate, interval, timezone } = input;
- const filtersWhere = overviewService.getRawWhereClause('sessions', filters);
+ const filtersWhere = andFilters(
+ overviewService.getRawWhereClause('sessions', filters)
+ );
+ const window = sessionWindow(projectId, startDate, endDate);
+ const bucket = bucketStart(interval);
+ const sessionsTable = sql.id(TABLE_NAMES.sessions);
+ const settings = { session_timezone: timezone };
// Step 1: top non-direct referrers by total range volume. Bounds the
// expensive per-bucket query — long-tail referrers can't produce
// meaningful spikes anyway because they fail the absolute floor.
- const topReferrers = await clix(ch, timezone)
- .select<{ referrer_name: string; total: number }>([
- 'referrer_name',
- 'sum(sign) AS total',
- ])
- .from(TABLE_NAMES.sessions, true)
- .where('project_id', '=', projectId)
- .where('created_at', 'BETWEEN', [
- clix.datetime(startDate, 'toDateTime'),
- clix.datetime(endDate, 'toDateTime'),
- ])
- .where('referrer_name', '!=', '')
- .where('referrer_name', 'IS NOT NULL')
- .rawWhere(filtersWhere)
- .groupBy(['referrer_name'])
- .having('sum(sign)', '>=', MIN_SESSIONS_FLOOR)
- .orderBy('total', 'DESC')
- .limit(MAX_REFERRERS)
- .execute();
+ const topReferrers = await chQuery<{
+ referrer_name: string;
+ total: number;
+ }>(
+ deps,
+ sql`SELECT referrer_name, sum(sign) AS total FROM ${sessionsTable} FINAL WHERE ${window} AND referrer_name != '' AND referrer_name IS NOT NULL${filtersWhere} GROUP BY referrer_name HAVING sum(sign) >= ${sql.uint64(MIN_SESSIONS_FLOOR)} ORDER BY total DESC LIMIT ${sql.uint64(MAX_REFERRERS)}`,
+ settings
+ );
if (topReferrers.length === 0) {
return [];
@@ -116,49 +146,29 @@ export async function getReferrerSpikes(
// Step 2: per-bucket sessions for top referrers + bucket totals (including
// direct traffic) for the share-of-bucket denominator. Run in parallel.
- const [spikeRows, bucketTotalRows] = await Promise.all([
- clix(ch, timezone)
- .select<{ date: string; referrer_name: string; sessions: number }>([
- `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,
- 'referrer_name',
- 'sum(sign) AS sessions',
- ])
- .from(TABLE_NAMES.sessions, true)
- .where('project_id', '=', projectId)
- .where('created_at', 'BETWEEN', [
- clix.datetime(startDate, 'toDateTime'),
- clix.datetime(endDate, 'toDateTime'),
- ])
- .where('referrer_name', 'IN', referrerNames)
- .rawWhere(filtersWhere)
- .groupBy(['date', 'referrer_name'])
- .having('sum(sign)', '>', 0)
- .orderBy('date', 'ASC')
- .transform({
- date: (item) => convertClickhouseDateToJs(item.date).toISOString(),
- })
- .execute(),
-
- clix(ch, timezone)
- .select<{ date: string; total: number }>([
- `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,
- 'sum(sign) AS total',
- ])
- .from(TABLE_NAMES.sessions, true)
- .where('project_id', '=', projectId)
- .where('created_at', 'BETWEEN', [
- clix.datetime(startDate, 'toDateTime'),
- clix.datetime(endDate, 'toDateTime'),
- ])
- .rawWhere(filtersWhere)
- .groupBy(['date'])
- .having('sum(sign)', '>', 0)
- .transform({
- date: (item) => convertClickhouseDateToJs(item.date).toISOString(),
- })
- .execute(),
+ const [spikeRowsRaw, bucketTotalRowsRaw] = await Promise.all([
+ chQuery<{ date: string; referrer_name: string; sessions: number }>(
+ deps,
+ sql`SELECT ${bucket} AS date, referrer_name, sum(sign) AS sessions FROM ${sessionsTable} FINAL WHERE ${window} AND referrer_name IN ${sql.array('String', referrerNames)}${filtersWhere} GROUP BY date, referrer_name HAVING sum(sign) > 0 ORDER BY date ASC`,
+ settings
+ ),
+ chQuery<{ date: string; total: number }>(
+ deps,
+ sql`SELECT ${bucket} AS date, sum(sign) AS total FROM ${sessionsTable} FINAL WHERE ${window}${filtersWhere} GROUP BY date HAVING sum(sign) > 0`,
+ settings
+ ),
]);
+ // clix's `.transform({ date })` (query-builder.ts:546) ran per row.
+ const spikeRows = spikeRowsRaw.map((row) => ({
+ ...row,
+ date: convertClickhouseDateToJs(row.date).toISOString(),
+ }));
+ const bucketTotalRows = bucketTotalRowsRaw.map((row) => ({
+ ...row,
+ date: convertClickhouseDateToJs(row.date).toISOString(),
+ }));
+
// Bail when the range doesn't have enough buckets to form a stable baseline.
// Median over <5 points is meaningless and produces noisy spikes.
const bucketCount = new Set(bucketTotalRows.map((r) => r.date)).size;
diff --git a/packages/core/src/modules/overview/overview.service.ts b/packages/core/src/modules/overview/overview.service.ts
index 1f0fd784e..502b5aef8 100644
--- a/packages/core/src/modules/overview/overview.service.ts
+++ b/packages/core/src/modules/overview/overview.service.ts
@@ -15,7 +15,10 @@ import { z } from 'zod';
import type { ServiceDeps } from '../../services';
import { average, sum } from '../../shared/math';
import { convertClickhouseDateToJs } from '../chart/src/dates';
-import { getEventFiltersWhereClause } from '../chart/src/filter-where';
+import {
+ getEventFiltersWhereClause,
+ joinFilterClauses,
+} from '../chart/src/filter-where';
import { getSettingsForProject } from '../organization/organization.service';
import type { IChartEventFilter, IInterval } from '../report/report.constants';
import { chartColors, zTimeInterval } from '../report/report.constants';
@@ -318,7 +321,10 @@ function sessionsFilterMode(params: {
projectId: string;
startDate: string;
endDate: string;
-}): { rawFilterWhere: string; distinctSessionsCte: SqlFragment | null } {
+}): {
+ rawFilterWhere: SqlFragment | null;
+ distinctSessionsCte: SqlFragment | null;
+} {
if (!isPageFilter(params.filters)) {
return {
rawFilterWhere: getRawWhereClause('sessions', params.filters),
@@ -326,7 +332,7 @@ function sessionsFilterMode(params: {
};
}
return {
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte: distinctSessionsQuery({
projectId: params.projectId,
startDate: params.startDate,
@@ -535,7 +541,7 @@ async function getMetricsWithPageFilter(
export function getRawWhereClause(
type: 'events' | 'sessions',
filters: IChartEventFilter[]
-) {
+): SqlFragment | null {
const where = getEventFiltersWhereClause(
filters.flatMap((item) => {
if (!WHITELISTED_FILTERS.includes(item.name)) {
@@ -577,7 +583,7 @@ export function getRawWhereClause(
type
);
- return Object.values(where).join(' AND ');
+ return joinFilterClauses(where);
}
export async function getTopPages(
@@ -1368,7 +1374,7 @@ export interface OverviewService {
getRawWhereClause(
type: 'events' | 'sessions',
filters: IChartEventFilter[]
- ): string;
+ ): SqlFragment | null;
getMetrics(input: IGetMetricsInput): ReturnType<typeof getMetrics>;
getTopPages(input: IGetTopPagesInput): ReturnType<typeof getTopPages>;
getTopEntryExit(
diff --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.ts
index 8d68c9ebf..a99a2bfc8 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
@@ -3,11 +3,12 @@
* remapping). Moved from packages/db/src/services/overview-sql.test.ts
* (M8-005) alongside its subject, which moved to core in M7-005 — same
* pattern as the chart cases moving to chart.sql.test.ts with theirs
- * (M7-003). `getRawWhereClause` itself is still clix/sqlstring-based
- * (pre-ADR-013); the rest of the overview module's queries already run
+ * (M7-003). M12-002 put `getRawWhereClause` on the `sql` tag, so these
+ * assertions read the rendered statement AND its bound params instead of one
+ * escaped string; the rest of the overview module's queries already run
* through overview.sql.ts, covered by overview.sql.test.ts. M10-005 turned it
* from a class method into a module function — it never needed a client,
- * being pure string building.
+ * being pure fragment building.
*
* Strategy: build the SQL string, then run `EXPLAIN <sql>` against the local
* ClickHouse instance. EXPLAIN parses the query, resolves columns, and builds
@@ -22,6 +23,7 @@
import { afterAll, beforeAll, describe, expect, it, spyOn } from 'bun:test';
import { ch } from '@openpanel/db/src/clickhouse/client';
+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';
import { getRawWhereClause } from '../overview.service';
const PROJECT_ID = 'test-sql-validation';
@@ -29,10 +31,20 @@ const PROJECT_ID = 'test-sql-validation';
let chReachable = false;
let logSpy: ReturnType<typeof spyOn>;
-async function explain(sql: string): Promise<void> {
+async function explain(
+ query: string,
+ queryParams: Record<string, unknown>
+): Promise<void> {
// EXPLAIN runs the parser + analyzer and builds the query plan, which
// catches UNKNOWN_IDENTIFIER and AMBIGUOUS_IDENTIFIER. It does not execute.
- await ch.command({ query: `EXPLAIN ${sql}` });
+ await ch.command({ query: `EXPLAIN ${query}`, query_params: queryParams });
+}
+
+/** The clause plus the values it binds — both halves of a converted filter. */
+function rendered(where: SqlFragment | null) {
+ return (
+ where ?? { toStatement: () => ({ query: '', query_params: {} }) }
+ ).toStatement();
}
beforeAll(async () => {
@@ -64,37 +76,46 @@ const itCH = (name: string, fn: () => Promise<void>) =>
describe('overview.service / getRawWhereClause (UTM remapping)', () => {
it('rewrites utm_* to properties[__query.utm_*] for the events table', () => {
- const where = getRawWhereClause('events', [
- { name: 'utm_source', operator: 'is', value: ['awn'] },
- ]);
- expect(where).toContain("properties['__query.utm_source']");
- expect(where).not.toMatch(/(?<![._\w])utm_source\s*=/);
+ const { query, query_params } = rendered(
+ getRawWhereClause('events', [
+ { name: 'utm_source', operator: 'is', value: ['awn'] },
+ ])
+ );
+ expect(query).toContain("properties['__query.utm_source']");
+ expect(query).not.toMatch(/(?<![._\w])utm_source\s*=/);
+ expect(query_params).toEqual({ p1: 'awn' });
});
it('keeps utm_* as a top-level column for the sessions table', () => {
- const where = getRawWhereClause('sessions', [
- { name: 'utm_source', operator: 'is', value: ['awn'] },
- ]);
- expect(where).toMatch(/(?<![._\w])utm_source\s*=/);
- expect(where).not.toContain("properties['__query.utm_source']");
+ const { query, query_params } = rendered(
+ getRawWhereClause('sessions', [
+ { name: 'utm_source', operator: 'is', value: ['awn'] },
+ ])
+ );
+ expect(query).toMatch(/(?<![._\w])utm_source\s*=/);
+ expect(query).not.toContain("properties['__query.utm_source']");
+ expect(query_params).toEqual({ p1: 'awn' });
});
it('drops non-whitelisted filters', () => {
const where = getRawWhereClause('events', [
{ name: 'malicious_column', operator: 'is', value: ['x'] },
]);
- expect(where).toBe('');
+ expect(where).toBeNull();
});
itCH(
'events utm_source filter parses against real events table',
async () => {
- const where = getRawWhereClause('events', [
- { name: 'utm_source', operator: 'is', value: ['awn'] },
- ]);
- expect(where).toBeTruthy();
+ const { query, query_params } = rendered(
+ getRawWhereClause('events', [
+ { name: 'utm_source', operator: 'is', value: ['awn'] },
+ ])
+ );
+ expect(query).toBeTruthy();
await explain(
- `SELECT count() FROM events WHERE project_id = '${PROJECT_ID}' AND ${where}`
+ `SELECT count() FROM events WHERE project_id = '${PROJECT_ID}' AND ${query}`,
+ query_params
);
}
);
@@ -102,12 +123,15 @@ describe('overview.service / getRawWhereClause (UTM remapping)', () => {
itCH(
'sessions utm_source filter parses against real sessions table',
async () => {
- const where = getRawWhereClause('sessions', [
- { name: 'utm_source', operator: 'is', value: ['awn'] },
- ]);
- expect(where).toBeTruthy();
+ const { query, query_params } = rendered(
+ getRawWhereClause('sessions', [
+ { name: 'utm_source', operator: 'is', value: ['awn'] },
+ ])
+ );
+ expect(query).toBeTruthy();
await explain(
- `SELECT count() FROM sessions WHERE project_id = '${PROJECT_ID}' AND ${where}`
+ `SELECT count() FROM sessions WHERE project_id = '${PROJECT_ID}' AND ${query}`,
+ query_params
);
}
);
diff --git a/packages/core/src/modules/overview/src/overview.sql.test.ts b/packages/core/src/modules/overview/src/overview.sql.test.ts
index 713221046..5264b3d79 100644
--- a/packages/core/src/modules/overview/src/overview.sql.test.ts
+++ b/packages/core/src/modules/overview/src/overview.sql.test.ts
@@ -36,7 +36,7 @@ describe('overview.sql — parses against ClickHouse', () => {
startDate: START,
endDate: END,
interval: 'day',
- rawFilterWhere: '',
+ rawFilterWhere: null,
})
);
});
@@ -48,7 +48,7 @@ describe('overview.sql — parses against ClickHouse', () => {
startDate: START,
endDate: END,
interval: 'day',
- rawFilterWhere: '',
+ rawFilterWhere: null,
})
);
});
@@ -60,7 +60,7 @@ describe('overview.sql — parses against ClickHouse', () => {
startDate: START,
endDate: END,
interval: 'week',
- rawFilterWhere: '',
+ rawFilterWhere: null,
})
);
await explain(
@@ -69,7 +69,7 @@ describe('overview.sql — parses against ClickHouse', () => {
startDate: START,
endDate: END,
interval: 'month',
- rawFilterWhere: '',
+ rawFilterWhere: null,
})
);
});
@@ -81,8 +81,8 @@ describe('overview.sql — parses against ClickHouse', () => {
startDate: START,
endDate: END,
interval: 'day',
- rawSessionFilterWhere: '',
- rawEventFilterWhere: '',
+ rawSessionFilterWhere: null,
+ rawEventFilterWhere: null,
})
);
});
@@ -93,7 +93,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
limit: 20,
})
);
@@ -107,7 +107,7 @@ describe('overview.sql — parses against ClickHouse', () => {
endDate: END,
mode: 'entry',
limit: 20,
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte: null,
})
);
@@ -118,7 +118,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
});
await explain(
OV.topEntryExitQuery({
@@ -127,7 +127,7 @@ describe('overview.sql — parses against ClickHouse', () => {
endDate: END,
mode: 'exit',
limit: 20,
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte,
})
);
@@ -142,7 +142,7 @@ describe('overview.sql — parses against ClickHouse', () => {
column: 'country',
prefixColumn: null,
limit: 1000,
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte: null,
})
);
@@ -157,7 +157,7 @@ describe('overview.sql — parses against ClickHouse', () => {
column: 'region',
prefixColumn: 'country',
limit: 1000,
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte: null,
})
);
@@ -172,7 +172,7 @@ describe('overview.sql — parses against ClickHouse', () => {
interval: 'day',
column: 'referrer',
prefixColumn: null,
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte: null,
})
);
@@ -180,7 +180,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
});
await explain(
OV.topGenericSeriesTimeSeriesQuery({
@@ -190,7 +190,7 @@ describe('overview.sql — parses against ClickHouse', () => {
interval: 'day',
column: 'referrer',
prefixColumn: null,
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte,
})
);
@@ -202,7 +202,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
steps: 5,
topEntries: 3,
})
@@ -215,9 +215,12 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
steps: 5,
- topEntryPages: ['https://a.example.com/', 'https://a.example.com/pricing'],
+ topEntryPages: [
+ 'https://a.example.com/',
+ 'https://a.example.com/pricing',
+ ],
})
);
});
@@ -228,7 +231,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
excludeEvents: ['session_start', 'session_end', 'screen_view'],
})
);
@@ -237,7 +240,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
excludeEvents: [],
})
);
@@ -249,7 +252,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
})
);
});
@@ -260,7 +263,7 @@ describe('overview.sql — parses against ClickHouse', () => {
projectId: PROJECT_ID,
startDate: START,
endDate: END,
- rawFilterWhere: '',
+ rawFilterWhere: null,
})
);
});
@@ -283,7 +286,7 @@ describe('overview.sql — sql.id() identifier whitelists (R3)', () => {
column: 'password',
prefixColumn: null,
limit: 10,
- rawFilterWhere: '',
+ rawFilterWhere: null,
distinctSessionsCte: null,
})
).toThrow();
diff --git a/packages/core/src/modules/overview/src/overview.sql.ts b/packages/core/src/modules/overview/src/overview.sql.ts
index cc3d5aa85..61023dd5c 100644
--- a/packages/core/src/modules/overview/src/overview.sql.ts
+++ b/packages/core/src/modules/overview/src/overview.sql.ts
@@ -125,9 +125,9 @@ function dateRangeWhere(
return sql`${sql.id(column)} BETWEEN toDateTime(${sql.string(toDateTimeLiteral(startDate))}) AND toDateTime(${sql.string(toDateTimeLiteral(endDate))})`;
}
-/** `getRawWhereClause`'s output — pre-compiled text, spliced verbatim. */
-function rawWhere(where: string): SqlFragment {
- return where ? sql`AND ${compiledText(where)}` : sql.empty;
+/** `getRawWhereClause`'s output — already a bound fragment, or nothing. */
+function rawWhere(where: SqlFragment | null): SqlFragment {
+ return where ? sql`AND ${where}` : sql.empty;
}
// --- revenue -----------------------------------------------------------------
@@ -137,7 +137,7 @@ export interface RevenueQueryInput {
startDate: string;
endDate: string;
interval: IInterval;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
}
export function revenueQuery(input: RevenueQueryInput): SqlFragment {
@@ -163,7 +163,7 @@ export interface SessionMetricsQueryInput {
startDate: string;
endDate: string;
interval: IInterval;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
}
export function sessionMetricsQuery(
@@ -198,8 +198,8 @@ export interface PageFilterMetricsQueryInput {
startDate: string;
endDate: string;
interval: IInterval;
- rawSessionFilterWhere: string;
- rawEventFilterWhere: string;
+ rawSessionFilterWhere: SqlFragment | null;
+ rawEventFilterWhere: SqlFragment | null;
}
function rollupDateLiteral(interval: IInterval): SqlFragment {
@@ -292,7 +292,7 @@ export interface TopPagesQueryInput {
projectId: string;
startDate: string;
endDate: string;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
limit: number;
}
@@ -322,7 +322,7 @@ export interface DistinctSessionsQueryInput {
projectId: string;
startDate: string;
endDate: string;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
}
export function distinctSessionsQuery(
@@ -363,7 +363,7 @@ export interface TopEntryExitQueryInput {
mode: 'entry' | 'exit';
limit: number;
/** Mutually exclusive with `distinctSessionsCte`, exactly as V1's `withDistinctSessionsIfNeeded`. */
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
distinctSessionsCte: SqlFragment | null;
}
@@ -429,7 +429,7 @@ export interface TopGenericQueryInput {
prefixColumn: string | null;
limit: number;
/** Mutually exclusive with `distinctSessionsCte`, exactly as V1's `withDistinctSessionsIfNeeded`. */
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
distinctSessionsCte: SqlFragment | null;
}
@@ -496,7 +496,7 @@ export interface TopGenericSeriesTimeSeriesInput {
column: string;
prefixColumn: string | null;
/** Always applied — unlike the top-items query, V1 applies this unconditionally. */
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
/** Additionally applied on top of `rawFilterWhere` when the caller has a page filter. */
distinctSessionsCte: SqlFragment | null;
}
@@ -528,7 +528,7 @@ export interface OrderedEventsQueryInput {
projectId: string;
startDate: string;
endDate: string;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
}
function orderedEventsQuery(input: OrderedEventsQueryInput): SqlFragment {
@@ -637,7 +637,7 @@ export interface TopEventsQueryInput {
projectId: string;
startDate: string;
endDate: string;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
excludeEvents: string[];
}
@@ -665,7 +665,7 @@ export interface TopLinkOutQueryInput {
projectId: string;
startDate: string;
endDate: string;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
}
export function topLinkOutQuery(input: TopLinkOutQueryInput): SqlFragment {
@@ -690,7 +690,7 @@ export interface MapDataQueryInput {
projectId: string;
startDate: string;
endDate: string;
- rawFilterWhere: string;
+ rawFilterWhere: SqlFragment | null;
}
export function mapDataQuery(input: MapDataQueryInput): SqlFragment {
diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.ts
index 71685266b..92f33eb1b 100644
--- a/packages/core/src/modules/profile/profile.service.ts
+++ b/packages/core/src/modules/profile/profile.service.ts
@@ -29,7 +29,10 @@ import {
formatClickhouseDate,
toNullIfDefaultMinDate,
} from './src/dates';
-import type { CompiledFilterClauses } from './src/filter-clauses';
+import {
+ type CompiledFilterClauses,
+ compiledFilterClauses,
+} from './src/filter-clauses';
import {
findProfilesQuery,
powerUsersQuery,
@@ -187,7 +190,9 @@ async function compileProfileFilters(
return {};
}
const { buildFilterWhere } = await loadFilterCompiler();
- return buildFilterWhere(filters, projectId, PROFILE_FILTER_TARGET);
+ return compiledFilterClauses(
+ 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.ts
index 9ed664751..3c6c0f28a 100644
--- a/packages/core/src/modules/profile/src/filter-clauses.ts
+++ b/packages/core/src/modules/profile/src/filter-clauses.ts
@@ -1,23 +1,34 @@
// The ONE place this module splices pre-compiled filter SQL.
//
-// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is
-// V1's filter compiler and still emits sqlstring-escaped SQL text: ADR-013
-// leaves the filter compilers as they are ("two behaviours, not two builders")
-// until the shared filter compiler converts to fragments. Until then a
-// `sql`-tag query that takes `IChartEventFilter[]` has to splice that text,
-// and it does so 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.
+// `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.
import { SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';
-export type CompiledFilterClauses = Record<string, string>;
+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: CompiledFilterClauses
): SqlFragment[] {
- return Object.values(clauses).map((clause) => new SqlFragment([clause], []));
+ return Object.values(clauses);
}
export function spliceCompiledFilters(
diff --git a/packages/core/src/modules/profile/src/profile.sql.test.ts b/packages/core/src/modules/profile/src/profile.sql.test.ts
index e9042776d..34e4a87c2 100644
--- a/packages/core/src/modules/profile/src/profile.sql.test.ts
+++ b/packages/core/src/modules/profile/src/profile.sql.test.ts
@@ -5,6 +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 {
findProfilesQuery,
PROFILE_COLUMNS,
@@ -157,7 +158,9 @@ describe('profileListQuery', () => {
offset: 100,
search: 'ann',
isExternal: true,
- filterClauses: { f0: "(properties['plan'] = 'pro')" },
+ filterClauses: compiledFilterClauses({
+ f0: "(properties['plan'] = 'pro')",
+ }),
}).toStatement();
const text = collapse(query);
@@ -178,7 +181,7 @@ describe('profileListQuery', () => {
projectId: PROJECT_ID,
search: 'ann',
isExternal: false,
- filterClauses: { f0: "(email != '')" },
+ filterClauses: compiledFilterClauses({ f0: "(email != '')" }),
};
const page = collapse(
profileListQuery({ ...list, take: 1, offset: 0 }).toStatement().query
@@ -226,7 +229,7 @@ describe('findProfilesQuery', () => {
inactiveDays: 7,
minSessions: 3,
performedEvent: HOSTILE,
- filterClauses: { f0: '(1 = 1)' },
+ filterClauses: compiledFilterClauses({ f0: '(1 = 1)' }),
}).toStatement();
const text = collapse(query);
diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.ts
index b9d3e0d34..1a58698e3 100644
--- a/packages/core/src/modules/session/session.service.ts
+++ b/packages/core/src/modules/session/session.service.ts
@@ -24,6 +24,10 @@ 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 {
hasSessionListLookback,
querySessionsQuery,
@@ -226,15 +230,17 @@ async function compileSessionFilters(
filters: IChartEventFilter[] | undefined,
projectId: string,
range: { startDate?: Date; endDate?: Date }
-) {
+): Promise<CompiledFilterClauses> {
if (!filters?.length) {
return {};
}
const { buildFilterWhere } = await loadFilterCompiler();
- return buildFilterWhere(filters, projectId, {
- ...SESSION_FILTER_TABLE,
- ...range,
- });
+ return compiledFilterClauses(
+ 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.ts
index 22b08d5d4..2ad287d63 100644
--- a/packages/core/src/modules/session/src/filter-clauses.ts
+++ b/packages/core/src/modules/session/src/filter-clauses.ts
@@ -1,25 +1,33 @@
// The ONE place this module splices pre-compiled filter SQL.
//
-// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is
-// V1's filter compiler and still emits sqlstring-escaped SQL text: ADR-013
-// leaves the filter compilers as they are ("two behaviours, not two builders")
-// until the shared filter compiler converts to fragments. Until then a
-// `sql`-tag query that takes `IChartEventFilter[]` has to splice that text,
-// and it does so 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.
+// `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.
import { SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';
-export type CompiledFilterClauses = Record<string, string>;
+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 spliceCompiledFilters(
clauses: CompiledFilterClauses
): SqlFragment {
- const fragments = Object.values(clauses).map(
- (clause) => new SqlFragment([clause], [])
- );
+ const fragments = Object.values(clauses);
if (fragments.length === 0) {
return sql.empty;
}
diff --git a/packages/core/src/modules/session/src/session.sql.test.ts b/packages/core/src/modules/session/src/session.sql.test.ts
index dcf5a3004..5bb4acf38 100644
--- a/packages/core/src/modules/session/src/session.sql.test.ts
+++ b/packages/core/src/modules/session/src/session.sql.test.ts
@@ -5,6 +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 {
hasSessionListLookback,
querySessionsQuery,
@@ -79,7 +80,10 @@ describe('sessionListQuery', () => {
endDate: new Date('2026-07-31T23:59:59Z'),
profileId: 'user-1',
search: 'checkout',
- filterClauses: { f0: "country = 'SE'", f1: "device = 'mobile'" },
+ filterClauses: compiledFilterClauses({
+ f0: "country = 'SE'",
+ f1: "device = 'mobile'",
+ }),
}).toStatement();
const text = collapse(query);