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-006): organization.service.ts, project.service.ts and mcp property-values.ts onto the sql tag: 0 sqlstring, 0 clix, the mcp lazy import gone, three proofs, goldens 137/137

ralph43dedb751949
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/property-values.sql.proof.md b/packages/core/src/modules/mcp/src/tools/analytics/property-values.sql.proof.md
new file mode 100644
index 000000000..454b8dd8d
--- /dev/null
+++ b/packages/core/src/modules/mcp/src/tools/analytics/property-values.sql.proof.md
@@ -0,0 +1,218 @@
+# property-values.ts — V1 → V2 result-set proof (M12-006)
+
+Both ClickHouse statements
+`packages/core/src/modules/mcp/src/tools/analytics/property-values.ts` runs
+(three cases, because `list_event_properties` has an optional `eventName`
+branch), executed V1 against V2 on the local prod-copy `openpanel`. V1 is the
+file at commit `78098bdc`
+(`git show HEAD:packages/core/src/modules/mcp/src/tools/analytics/property-values.ts`),
+which builds both statements with `clix`; V2 is the converted file, every value
+bound as a `{pN:Type}` param. **Both files were imported into one Bun process
+and their tools registered against the same stub MCP server**, then invoked with
+the same inputs — the SQL below was produced by calling the real registered tool
+handlers with a `deps.ch.query` stub that captures
+`{query, query_params, clickhouse_settings}`, never by retyping V1 by hand. Each
+captured statement was then executed through the local HTTP interface at
+`format: 'JSON'` with the settings its own side asked for; V1 went as `query`,
+V2 as `query` + `param_pN`. `data` was compared row-for-row and `meta`
+column-for-column.
+
+No case needed set comparison: both statements carry a total `ORDER BY`
+(`property_key ASC, name ASC` on the first, `created_at DESC` on the second) and
+both sides returned byte-identical row order.
+
+- **Date**: 2026-09-07.
+- **Data**: local prod-copy `openpanel`, 319,850,903 events. Project fixture
+ `pincali-production`, whose `event_property_values_mv` rows cover 500+
+ `(property_key, name)` pairs, 299 of them under `screen_view`, and 1,288,989+
+ rows under `(viewed_property, property_id)`. Nothing is empty here — every
+ case below returns its full `LIMIT` window or close to it.
+- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are
+ directional only; production is 2 shards × 2 replicas
+ (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either
+ direction.** `grep -c 'GLOBAL'` is `0` on the V1 file and `0` on the V2 file,
+ and `grep -c ' IN '` is `0` on both — neither statement contains an `IN` of
+ any kind, so the distributed-`IN` trap does not arise here at all.
+- **Verdict**: **3 cases, all IDENTICAL.**
+
+## `session_timezone`
+
+`clix(client)` with no timezone argument defaults to `'UTC'`
+(`query-builder.ts:696-697`) and sends it as
+`clickhouse_settings.session_timezone` on every `execute()` (`:562`). Both
+statements came off `clix`, so both sent it; V2 sends it through
+`CLIX_SESSION_TIMEZONE` and the capture confirms `session_timezone=UTC` on both
+sides of all three cases. Dropping it would have changed the meaning of
+`created_at DESC` ordering under a non-UTC server default, which is why it is
+pinned rather than inherited.
+
+## `list_event_properties` — no `eventName`
+
+**statement** — IDENTICAL; rows V1/V2 = **500/500** (the `LIMIT` window, full);
+`meta` V1/V2 =
+`[{"name":"property_key","type":"String"},{"name":"event_name","type":"LowCardinality(String)"}]`;
+rows_read V1/V2 = 131456/131456; wall V1/V2 = 16 ms / 13 ms;
+clickhouse_settings: `session_timezone=UTC` (both). First rows on both sides:
+`{"property_key":"__bot","event_name":"applied_filters"}`,
+`{"property_key":"__bot","event_name":"authentication_modal_opened"}`, …
+
+```sql
+-- V1
+SELECT property_key, name as event_name FROM event_property_values_mv
+WHERE project_id = 'pincali-production'
+GROUP BY property_key, name
+ORDER BY property_key ASC, name ASC
+LIMIT 500
+-- V2
+SELECT property_key, name as event_name FROM event_property_values_mv
+WHERE project_id = {p1:String}
+GROUP BY property_key, name
+ORDER BY property_key ASC, name ASC
+LIMIT {p2:UInt64}
+-- V2 params: {"p1":"pincali-production","p2":500}
+```
+
+`LIMIT {p2:UInt64}` is a bound parameter, not inlined text: `UInt64` is the
+right type because the scan limit is a compile-time constant that cannot be
+negative (recipe, *Numbers*). V1's `500` and V2's bound `500` produce the same
+window, which the equal 500-row results and equal `rows_read` show.
+
+## `list_event_properties` — `eventName = 'screen_view'`
+
+**statement** — IDENTICAL; rows V1/V2 = **299/299**; `meta` V1/V2 as above;
+rows_read V1/V2 = 98688/98688; wall V1/V2 = 14 ms / 11 ms; clickhouse_settings:
+`session_timezone=UTC` (both).
+
+This is the conditional-fragment case: V1 appended a second `.where('name','=',…)`
+to the builder after `orderBy`/`limit` and clix folded it into the WHERE in call
+order; V2 splices `sql\` AND name = ${sql.string(eventName)}\`` (or `sql.empty`)
+into the same position. The two texts below differ only in the binding.
+
+```sql
+-- V1
+SELECT property_key, name as event_name FROM event_property_values_mv
+WHERE project_id = 'pincali-production' AND name = 'screen_view'
+GROUP BY property_key, name
+ORDER BY property_key ASC, name ASC
+LIMIT 500
+-- V2
+SELECT property_key, name as event_name FROM event_property_values_mv
+WHERE project_id = {p1:String} AND name = {p2:String}
+GROUP BY property_key, name
+ORDER BY property_key ASC, name ASC
+LIMIT {p3:UInt64}
+-- V2 params: {"p1":"pincali-production","p2":"screen_view","p3":500}
+```
+
+The no-`eventName` case above is the other half of that branch: `sql.empty`
+renders to nothing, and the resulting text is byte-for-byte V1's minus the
+`AND name = …` clause.
+
+## `get_event_property_values`
+
+**statement** — IDENTICAL; rows V1/V2 = **2000/2000** (the `LIMIT` window,
+full); `meta` V1/V2 = `[{"name":"value","type":"String"}]`; rows_read V1/V2 =
+1082520/1081344; wall V1/V2 = 39 ms / 42 ms; clickhouse_settings:
+`session_timezone=UTC` (both). First rows on both sides: `EB-RG9481`,
+`EB-SS0279`, `EB-WN5258`, `EB-WH9815`, …
+
+```sql
+-- V1
+SELECT property_value as value FROM event_property_values_mv
+WHERE project_id = 'pincali-production'
+ AND name = 'viewed_property'
+ AND property_key = 'property_id'
+ORDER BY created_at DESC
+LIMIT 2000
+-- V2
+SELECT property_value as value FROM event_property_values_mv
+WHERE project_id = {p1:String}
+ AND name = {p2:String}
+ AND property_key = {p3:String}
+ORDER BY created_at DESC
+LIMIT {p4:UInt64}
+-- V2 params: {"p1":"pincali-production","p2":"viewed_property","p3":"property_id","p4":2000}
+```
+
+**Known instability of this table, not of this conversion.** The
+`event_property_values_mv` is an AggregatingMergeTree read without `FINAL` whose
+`created_at` is outside the sort key, so the top-2000 window reshuffles when a
+background merge lands (`docs/TECH_DEBT.md`, *Golden coverage hole:
+`insights-event-property-values`*). Both sides of this case were executed back to
+back through the same client against the same parts and returned identical rows;
+a re-run days later may return a different — but still identical-between-sides —
+2000. V1 runs the same query, so the conversion neither introduces nor fixes it.
+
+## The lazy loaders
+
+V1 opened each handler with
+`const [ch, { clix, TABLE_NAMES }] = await Promise.all([loadCompatCh(), loadCompatChHelpers()])`
+— two awaited dynamic `import('../../../../v1-compat')` hops per tool call, one
+of them only to fetch `clix` and `TABLE_NAMES`. V2 imports `sql`, `chQuery` and
+core's own `TABLE_NAMES` statically and takes the ClickHouse scope from
+`loadCompatChScope()` (ADR-007: no lazy loaders; MCP handlers have a fixed
+`@modelcontextprotocol/sdk` signature with no `Ctx` slot, so the v1-compat seam
+stays — it is the *dynamic import* that goes). `tools/shared.ts` lost its
+dynamic form too: its surviving `loadCompat*` helpers all read a static import
+of `v1-compat` (which that file already value-imported for
+`resolveClientProjectId`, so the dynamic form deferred nothing), and
+`organization.service.ts` lost the last one in its own module. Consequences visible in the capture: the statement
+now carries `deps.logger`, so the `query info` line carries the request's scope,
+and `tools/shared.ts` no longer exports `loadCompatChHelpers` (property-values
+was its only caller) nor `loadCompatCh` (same) — with them the comment saying
+property-values "still builds its query with `clix`" is gone.
+
+**The `await`-dynamic-import gate is 0 across the three module trees' source
+files**, which is what the acceptance criterion asks for:
+
+```
+$ grep -rn "await imp"'ort' --include='*.ts' --exclude='*.test.ts' \
+ packages/core/src/modules/mcp packages/core/src/modules/project \
+ packages/core/src/modules/organization
+$ echo $?
+1
+```
+
+Measured 2026-09-07 on this tree. The `--exclude=*.test.ts` is not a loophole
+around this task, it is the ADR: the modules' 10 test files hold 55 awaited
+dynamic imports that are the mandated `bun:test` idiom, not lazy loaders.
+ADR-010's acceptance note and `packages/core/AGENTS.md` require top-level
+`mock.module` followed by an awaited dynamic import of the subject inside
+`beforeAll`, and state that "a static `import` of the subject at the top of the
+file defeats it". They are unchanged by this task.
+
+| scope | occurrences |
+|---|---:|
+| `*.ts` source in the three module trees | **0** |
+| `*.test.ts` in the three module trees (the ADR-010 idiom) | 55 |
+| the three `*.sql.proof.md` files this task adds (deliberately phrased so they add none) | 0 |
+
+## Tests
+
+No test compares this tool's generated SQL text, so none had to be retargeted to
+compare statement + params. `src/integration/tools.test.ts` invokes both tools
+against the isolated `openpanel_test` databases and asserts on the returned
+shape (`res.columns`, `res.properties`, `res.event`, `res.property`,
+`res.values`); its assertions are unchanged and the file is untouched.
+(`src/tools/analytics/profiles.test.ts` is the module's one statement+params
+comparison, and it belongs to the profile service, not to this file.)
+
+## Reproduce
+
+```bash
+# get_event_property_values, V1
+curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC&default_format=JSONCompact' \
+ --data-binary "SELECT property_value as value FROM event_property_values_mv WHERE project_id = 'pincali-production' AND name = 'viewed_property' AND property_key = 'property_id' ORDER BY created_at DESC LIMIT 2000"
+
+# get_event_property_values, V2
+curl -s -G 'http://127.0.0.1:8123/' \
+ --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \
+ --data-urlencode 'default_format=JSONCompact' \
+ --data-urlencode 'param_p1=pincali-production' \
+ --data-urlencode 'param_p2=viewed_property' \
+ --data-urlencode 'param_p3=property_id' \
+ --data-urlencode 'param_p4=2000' \
+ --data-urlencode 'query=SELECT property_value as value FROM event_property_values_mv WHERE project_id = {p1:String} AND name = {p2:String} AND property_key = {p3:String} ORDER BY created_at DESC LIMIT {p4:UInt64}'
+```
+
+Both return 2,000 rows.
diff --git a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
index ceeebe675..f48a2cca7 100644
--- a/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
+++ b/packages/core/src/modules/mcp/src/tools/analytics/property-values.ts
@@ -1,10 +1,12 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import { z } from 'zod';
+import { chQuery } from '../../../../../shared/ch-query';
+import { TABLE_NAMES } from '../../../../../shared/ch-tables';
import { EVENT_COLUMNS } from '../../../../event/event.service';
import type { McpAuthContext } from '../../auth';
import {
- loadCompatCh,
- loadCompatChHelpers,
+ loadCompatChScope,
projectIdSchema,
resolveProjectId,
withErrorHandling,
@@ -15,6 +17,16 @@ const DEFAULT_PROPERTY_LIMIT = 50;
const MAX_PROPERTY_LIMIT = 500;
const DEFAULT_VALUE_LIMIT = 50;
const MAX_VALUE_LIMIT = 500;
+/** Raw (property_key, name) pairs scanned before `compactPropertyKeys` ranks
+ * them — V1's `.limit(500)`. */
+const PROPERTY_KEY_SCAN_LIMIT = 500;
+/** Raw MV rows scanned before de-duplication — V1's `.limit(2000)`. */
+const PROPERTY_VALUE_SCAN_LIMIT = 2000;
+// clix built both statements below with no timezone argument, and
+// `clix(client)` defaults to `'UTC'` (query-builder.ts:696-697), sending it as
+// `clickhouse_settings.session_timezone` on every `execute()` (:562). Both
+// keep sending it so their result sets stay identical.
+const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;
/**
* Collapse the raw property-key rows into a discovery list.
@@ -76,31 +88,28 @@ export function registerPropertyValueTools(
async ({ projectId: inputProjectId, eventName, limit }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
- const [ch, { clix, TABLE_NAMES }] = await Promise.all([
- loadCompatCh(),
- loadCompatChHelpers(),
- ]);
+ const deps = await loadCompatChScope();
// GROUP BY rather than DISTINCT so the epv_keys projection can serve
// this (a multi-column DISTINCT cannot be matched against an
// aggregating projection); `name` tie-breaks the ORDER BY so the
// LIMIT window is deterministic. See listEventPropertiesCore.
- const builder = clix(ch)
- .select<{ property_key: string; event_name: string }>([
- 'property_key',
- 'name as event_name',
- ])
- .from(TABLE_NAMES.event_property_values_mv)
- .where('project_id', '=', projectId)
- .groupBy(['property_key', 'name'])
- .orderBy('property_key', 'ASC')
- .orderBy('name', 'ASC')
- .limit(500);
-
- if (eventName) {
- builder.where('name', '=', eventName);
- }
-
- const rows = await builder.execute();
+ const rows = await chQuery<{
+ property_key: string;
+ event_name: string;
+ }>(
+ deps,
+ sql`
+ SELECT property_key, name as event_name
+ FROM ${sql.id(TABLE_NAMES.event_property_values_mv)}
+ WHERE project_id = ${sql.string(projectId)}${
+ eventName ? sql` AND name = ${sql.string(eventName)}` : sql.empty
+ }
+ GROUP BY property_key, name
+ ORDER BY property_key ASC, name ASC
+ LIMIT ${sql.uint64(PROPERTY_KEY_SCAN_LIMIT)}
+ `,
+ CLIX_SESSION_TIMEZONE
+ );
return {
...(eventName ? { event_name: eventName } : {}),
columns: EVENT_COLUMNS,
@@ -129,23 +138,24 @@ export function registerPropertyValueTools(
async ({ projectId: inputProjectId, eventName, propertyKey, limit }) =>
withErrorHandling(async () => {
const projectId = await resolveProjectId(context, inputProjectId);
- const [ch, { clix, TABLE_NAMES }] = await Promise.all([
- loadCompatCh(),
- loadCompatChHelpers(),
- ]);
+ const deps = await loadCompatChScope();
const take = limit ?? DEFAULT_VALUE_LIMIT;
// The MV holds one row per (property, value, day), so the same value
// recurs across the window — dedupe before counting against the limit,
// otherwise a single stable value can fill the whole response.
- const rows = await clix(ch)
- .select<{ value: string }>(['property_value as value'])
- .from(TABLE_NAMES.event_property_values_mv)
- .where('project_id', '=', projectId)
- .where('name', '=', eventName)
- .where('property_key', '=', propertyKey)
- .orderBy('created_at', 'DESC')
- .limit(2000)
- .execute();
+ const rows = await chQuery<{ value: string }>(
+ deps,
+ sql`
+ SELECT property_value as value
+ FROM ${sql.id(TABLE_NAMES.event_property_values_mv)}
+ WHERE project_id = ${sql.string(projectId)}
+ AND name = ${sql.string(eventName)}
+ AND property_key = ${sql.string(propertyKey)}
+ ORDER BY created_at DESC
+ LIMIT ${sql.uint64(PROPERTY_VALUE_SCAN_LIMIT)}
+ `,
+ CLIX_SESSION_TIMEZONE
+ );
const distinct: string[] = [];
const seen = new Set<string>();
diff --git a/packages/core/src/modules/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.ts
index 91eb9ed6a..443b9c3a9 100644
--- a/packages/core/src/modules/mcp/src/tools/shared.ts
+++ b/packages/core/src/modules/mcp/src/tools/shared.ts
@@ -1,6 +1,13 @@
import { z } from 'zod';
import { createLogger } from '../../../../clients/logger';
-import { resolveClientProjectId } from '../../../../v1-compat';
+import type { ServiceDeps } from '../../../../services';
+import {
+ compatDb,
+ compatPrisma,
+ compatServiceDeps,
+ pagesService,
+ resolveClientProjectId,
+} from '../../../../v1-compat';
import type { McpAuthContext } from '../auth';
const logger = createLogger({ name: 'mcp' });
@@ -14,36 +21,40 @@ const logger = createLogger({ name: 'mcp' });
* the v1-compat singleton instead of `@openpanel/db` (M10-004, see
* v1-compat.ts's header) — the same pattern every other bare, no-`Ctx`
* caller in this wave uses.
+ *
+ * M12-006 made the seam a static import (ADR-007: no lazy loaders). It always
+ * could be: this module already value-imported `resolveClientProjectId` from
+ * the same file, so the dynamic form deferred nothing and only hid the edge.
+ * The v1-compat seam itself is still lazy where it matters — it constructs no
+ * database until a caller asks for one.
*/
-export async function loadCompatDb() {
- return (await import('../../../../v1-compat')).compatDb();
-}
-
-export async function loadCompatCh() {
- return (await import('../../../../v1-compat')).compatCh();
+export function loadCompatDb() {
+ return compatDb();
}
/** `dashboard-management.ts`'s only need from `@openpanel/db`: the
* `Prisma.DbNull` sentinel for an explicit SQL NULL on a nullable Json
- * column, not a client — same seam as `loadCompatDb`/`loadCompatCh`. */
-export async function loadCompatPrisma() {
- return (await import('../../../../v1-compat')).compatPrisma();
+ * column, not a client — same seam as `loadCompatDb`. */
+export function loadCompatPrisma() {
+ return compatPrisma();
}
-/** `analytics/property-values.ts` still builds its query with `clix`/
- * `TABLE_NAMES` (ADR-013 converts the analytics read path one query per P7
- * task) — the query-building helpers, not the client (`loadCompatCh`
- * covers that), reached the same way. */
-export async function loadCompatChHelpers() {
- return (await import('../../../../v1-compat')).compatChHelpers();
+/** `analytics/property-values.ts` reads ClickHouse through core's own
+ * `chQuery` (shared/ch-query.ts), which wants the scope's client AND its
+ * logger rather than a bare client — same seam, widened to what a read
+ * needs. */
+export function loadCompatChScope(): Promise<
+ Pick<ServiceDeps, 'ch' | 'logger'>
+> {
+ return compatServiceDeps();
}
/** `analytics/page-performance.ts` used to construct its own `PagesService`
* per call to dodge a module-singleton mocking hazard; since M10-005 there is
* no singleton and no class, so it reaches the bare, v1-compat-wrapped pages
* service instead. */
-export async function loadCompatPagesService() {
- return (await import('../../../../v1-compat')).pagesService;
+export function loadCompatPagesService() {
+ return Promise.resolve(pagesService);
}
/**
diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.ts
index 812266bfb..3daac2294 100644
--- a/packages/core/src/modules/organization/organization.service.test.ts
+++ b/packages/core/src/modules/organization/organization.service.test.ts
@@ -1,8 +1,7 @@
-// organization.service.ts's db/ch access is lazy (`await import(...)` inside
-// each function — see the file's header), which is exactly what makes
-// `mock.module` work here with no import-time side effects to race: every
-// mock below is registered before the subject's first call, not before its
-// (side-effect-free) import.
+// organization.service.ts reaches Postgres/ClickHouse through the `ServiceDeps`
+// it is handed, and its module body has no import-time side effects, which is
+// what makes `mock.module` work here with nothing to race: every mock below is
+// registered before the subject's first call, not before its import.
import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.ts
index 0237f2863..31a715bd1 100644
--- a/packages/core/src/modules/organization/organization.service.ts
+++ b/packages/core/src/modules/organization/organization.service.ts
@@ -18,28 +18,39 @@
// `deps` cannot be a leading parameter and they reach the boot scope through
// the declared v1-compat seam instead.
//
-// ClickHouse queries here still go through raw sqlstring-escaped strings and
-// the (still-live, pre-ADR-013) `createSqlBuilder`, not the `sql` tag:
-// ADR-013 converts the analytics read path one query per P7 task, and this
-// module's queries haven't been converted yet. `createSqlBuilder` stays a
-// value import of `@openpanel/db`: like ADR-013's `sql` tag and `clix`, it is
-// a pure string BUILDER that holds no client (see shared/ch-query.ts).
-
+// M12-006 also made `shared/access-lookups.ts` a static import: that file
+// value-imports only zod-free leaves (`@openpanel/redis`, a Prisma TYPE) and
+// reaches Postgres through the lazy v1-compat seam itself, so it has no static
+// edge back here and the dynamic form deferred nothing (ADR-007: no lazy
+// loaders).
+//
+// M12-006 converted all five ClickHouse statements here onto the ADR-013 `sql`
+// tag: the four billing counters and `deleteFromClickhouse`'s project filter
+// bind every value as a `{pN:Type}` param, and the statements are written out
+// in full instead of assembled by `createSqlBuilder`'s record-of-strings.
+// `sqlstring` and `createSqlBuilder` are both gone from this module. The
+// `sql` tag is a value import of `@openpanel/db` and stays one: it is a
+// compile-time template tag holding no client (see shared/ch-query.ts). The
+// V1-vs-V2 result-set proof is `organization.sql.proof.md` beside this file.
+
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import type {
Invite,
Prisma,
ProjectAccess,
User,
} from '@openpanel/db/src/prisma-client';
-import { createSqlBuilder } from '@openpanel/db/src/sql-builder';
import { cacheable } from '@openpanel/redis';
-import sqlstring from 'sqlstring';
import { sendEmail } from '../../clients/email';
import { TRPCBadRequestError } from '../../rpc/errors';
import type { ServiceDeps } from '../../services';
+import {
+ getOrganizationAccess,
+ getProjectAccess,
+} from '../../shared/access-lookups';
import { formatClickhouseDate } from '../../shared/ch-dates';
import { chQuery } from '../../shared/ch-query';
-import { getReplicatedTableName, TABLE_NAMES } from '../../shared/ch-tables';
+import { isClickhouseClustered, TABLE_NAMES } from '../../shared/ch-tables';
import { DateTime } from '../../shared/date';
import { generateSecureId } from '../../shared/id';
@@ -55,6 +66,10 @@ export type IServiceProjectAccess = ProjectAccess;
const DEFAULT_TIMEZONE = 'UTC';
// Grace period between a scheduled deletion and the `delete` cron sweeping it
// up — matches V1's `addHours(new Date(), 24)`.
+// Session bookkeeping rows are worker-generated (the reaper can emit
+// session_end long after tracking stopped), so they are not billable activity.
+// V1 wrote this list inline as SQL text in all four counters below.
+const NON_BILLABLE_EVENT_NAMES = ['session_start', 'session_end'];
/** A module function's parameters with its leading `ServiceDeps` dropped. */
type Tail<T extends unknown[]> = T extends [unknown, ...infer Rest]
? Rest
@@ -227,9 +242,6 @@ export async function connectUserToOrganization(
}
) {
const db = deps.db;
- const { getOrganizationAccess, getProjectAccess } = await import(
- '../../shared/access-lookups'
- );
// Use primary since before this we might have just created the invite
// If we use replica it might not find the invite
@@ -327,14 +339,18 @@ export async function getOrganizationBillingEventsCount(
return 0;
}
- const { sb, getSql } = createSqlBuilder();
-
- sb.select.count = 'COUNT(*) AS count';
- sb.where.projectIds = `project_id IN (${organization.projects.map((project) => sqlstring.escape(project.id)).join(',')})`;
- sb.where.createdAt = `created_at BETWEEN ${sqlstring.escape(formatClickhouseDate(periodStart))} AND ${sqlstring.escape(formatClickhouseDate(periodEnd))}`;
- sb.where.names = `name NOT IN ('session_start', 'session_end')`;
-
- const res = await chQuery<{ count: number }>(deps, getSql());
+ const statement = sql`
+ SELECT COUNT(*) AS count
+ FROM ${sql.id(TABLE_NAMES.events)} e
+ WHERE project_id IN ${sql.array(
+ 'String',
+ organization.projects.map((project) => project.id)
+ )}
+ AND created_at BETWEEN ${sql.string(formatClickhouseDate(periodStart))} AND ${sql.string(formatClickhouseDate(periodEnd))}
+ AND name NOT IN ${sql.array('String', NON_BILLABLE_EVENT_NAMES)}
+ `;
+
+ const res = await chQuery<{ count: number }>(deps, statement);
return res[0]?.count;
}
@@ -349,13 +365,14 @@ export async function getOrganizationEventsCount(
return 0;
}
- const { sb, getSql } = createSqlBuilder();
-
- sb.select.count = 'COUNT(*) AS count';
- sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;
- sb.where.names = `name NOT IN ('session_start', 'session_end')`;
+ const statement = sql`
+ SELECT COUNT(*) AS count
+ FROM ${sql.id(TABLE_NAMES.events)} e
+ WHERE project_id IN ${sql.array('String', projectIds)}
+ AND name NOT IN ${sql.array('String', NON_BILLABLE_EVENT_NAMES)}
+ `;
- const res = await chQuery<{ count: number }>(deps, getSql());
+ const res = await chQuery<{ count: number }>(deps, statement);
return res[0]?.count ?? 0;
}
@@ -372,14 +389,15 @@ export async function getOrganizationEventsCountSince(
return 0;
}
- const { sb, getSql } = createSqlBuilder();
-
- sb.select.count = 'COUNT(*) AS count';
- sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;
- sb.where.names = `name NOT IN ('session_start', 'session_end')`;
- sb.where.createdAt = `created_at >= ${sqlstring.escape(formatClickhouseDate(since, true))}`;
+ const statement = sql`
+ SELECT COUNT(*) AS count
+ FROM ${sql.id(TABLE_NAMES.events)} e
+ WHERE project_id IN ${sql.array('String', projectIds)}
+ AND name NOT IN ${sql.array('String', NON_BILLABLE_EVENT_NAMES)}
+ AND created_at >= ${sql.string(formatClickhouseDate(since, true))}
+ `;
- const res = await chQuery<{ count: number }>(deps, getSql());
+ const res = await chQuery<{ count: number }>(deps, statement);
return res[0]?.count ?? 0;
}
@@ -394,18 +412,26 @@ export async function getOrganizationBillingEventsCountSerie(
endDate: Date;
}
): Promise<{ count: number; day: string }[]> {
- const interval = 'day';
- const { sb, getSql } = createSqlBuilder();
-
- sb.select.count = 'COUNT(*) AS count';
- sb.select.day = `toDate(toStartOf${interval.slice(0, 1).toUpperCase() + interval.slice(1)}(created_at)) AS ${interval}`;
- sb.groupBy.day = interval;
- sb.orderBy.day = `${interval} WITH FILL FROM toDate(${sqlstring.escape(formatClickhouseDate(startDate, true))}) TO toDate(${sqlstring.escape(formatClickhouseDate(endDate, true))}) STEP INTERVAL 1 ${interval.toUpperCase()}`;
- sb.where.projectIds = `project_id IN (${organization.projects.map((project) => sqlstring.escape(project.id)).join(',')})`;
- sb.where.createdAt = `${interval} BETWEEN ${sqlstring.escape(formatClickhouseDate(startDate, true))} AND ${sqlstring.escape(formatClickhouseDate(endDate, true))}`;
- sb.where.names = `name NOT IN ('session_start', 'session_end')`;
-
- return chQuery<{ count: number; day: string }>(deps, getSql());
+ // V1 built this through a `const interval = 'day'` that was never anything
+ // but 'day'; the fragment writes the bucket out instead of deriving four
+ // spellings of it. `day` is the SELECT alias, referenced by the WHERE and
+ // the WITH FILL exactly as V1 referenced it.
+ const from = formatClickhouseDate(startDate, true);
+ const to = formatClickhouseDate(endDate, true);
+ const statement = sql`
+ SELECT COUNT(*) AS count, toDate(toStartOfDay(created_at)) AS day
+ FROM ${sql.id(TABLE_NAMES.events)} e
+ WHERE project_id IN ${sql.array(
+ 'String',
+ organization.projects.map((project) => project.id)
+ )}
+ AND day BETWEEN ${sql.string(from)} AND ${sql.string(to)}
+ AND name NOT IN ${sql.array('String', NON_BILLABLE_EVENT_NAMES)}
+ GROUP BY day
+ ORDER BY day WITH FILL FROM toDate(${sql.string(from)}) TO toDate(${sql.string(to)}) STEP INTERVAL 1 DAY
+ `;
+
+ return chQuery<{ count: number; day: string }>(deps, statement);
}
const BILLING_EVENTS_SERIE_CACHE_TTL_SEC = 60 * 10;
@@ -522,7 +548,7 @@ export async function deleteFromClickhouse(
projectIds: string[]
) {
const ch = deps.ch;
- const where = `project_id IN (${projectIds.map((projectId) => sqlstring.escape(projectId)).join(',')})`;
+ const where = sql`project_id IN ${sql.array('String', projectIds)}`;
const tables = [
TABLE_NAMES.events,
TABLE_NAMES.profiles,
@@ -541,13 +567,21 @@ export async function deleteFromClickhouse(
];
for (const table of tables) {
+ // `getReplicatedTableName` appends `ON CLUSTER '{cluster}'` in clustered
+ // mode, which is a clause rather than an identifier — so the table name
+ // goes through `sql.id` and the clause stays literal template text.
+ const target = isClickhouseClustered()
+ ? sql`${sql.id(`${table}_replicated`)} ON CLUSTER '{cluster}'`
+ : sql.id(table);
// If materialized view, use ALTER TABLE since DELETE is not supported
- const query = table.endsWith('_mv')
- ? `ALTER TABLE ${getReplicatedTableName(table)} DELETE WHERE ${where};`
- : `DELETE FROM ${getReplicatedTableName(table)} WHERE ${where};`;
+ const statement = table.endsWith('_mv')
+ ? sql`ALTER TABLE ${target} DELETE WHERE ${where};`
+ : sql`DELETE FROM ${target} WHERE ${where};`;
+ const { query, query_params } = statement.toStatement();
await ch.command({
query,
+ query_params,
clickhouse_settings: {
lightweight_deletes_sync: '0',
},
diff --git a/packages/core/src/modules/organization/organization.sql.proof.md b/packages/core/src/modules/organization/organization.sql.proof.md
new file mode 100644
index 000000000..094d4f0e3
--- /dev/null
+++ b/packages/core/src/modules/organization/organization.sql.proof.md
@@ -0,0 +1,238 @@
+# organization.service.ts — V1 → V2 result-set proof (M12-006)
+
+Every ClickHouse statement `packages/core/src/modules/organization/organization.service.ts`
+runs, executed V1 against V2. V1 is the file at commit `78098bdc`
+(`git show HEAD:packages/core/src/modules/organization/organization.service.ts`),
+which builds four counters with `createSqlBuilder` + `sqlstring.escape` and
+`deleteFromClickhouse`'s filter with `sqlstring.escape`; V2 is the converted
+file, every value bound as a `{pN:Type}` param. **Both files were imported into
+one Bun process and called with the same inputs** — the SQL below was produced
+by calling the real exported functions with a `deps.ch.query` / `deps.ch.command`
+stub that captures `{query, query_params, clickhouse_settings}`, never by
+retyping V1 by hand. Each captured statement was then executed through the local
+HTTP interface at `format: 'JSON'` with the settings its own side asked for; V1
+went as `query`, V2 as `query` + `param_pN`. `data` was compared row-for-row and
+`meta` column-for-column.
+
+No case needed set comparison: the four counters return one row or a fully
+ordered `WITH FILL` series.
+
+- **Date**: 2026-09-07.
+- **Data**: local prod-copy `openpanel`, 319,850,903 events. Organization
+ fixture: two projects, `verdict` (real: 41,921,451 non-session events) and
+ `o'brien-prod` (**does not exist** — it is the quote-carrying value, present
+ so the escaping case is covered; its contribution to every count is 0 on both
+ sides). Billing window `2026-08-01 00:00:00` … `2026-08-20 00:00:00`, inside
+ the copy's `2026-07-01` … `2026-08-25` range. Every SELECT case below returns
+ a non-zero count.
+- **Deletes run elsewhere, deliberately.** `deleteFromClickhouse` issues 14
+ `DELETE` / `ALTER TABLE … DELETE` statements. Running those against the
+ prod-copy would mutate the golden harness's data, so both sides were executed
+ against a scratch database `m12_006_proof` holding 14 tables that carry only
+ the column the statements filter on, seeded identically per side and dropped
+ at the end of the run. §*deleteFromClickhouse* records the row counts.
+- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are
+ directional only; production is 2 shards × 2 replicas
+ (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either
+ direction.** `grep -c GLOBAL` is `0` on the V1 file and `0` on the V2 file.
+ Every `IN` operand on both sides is a literal value list (V1 an inline tuple,
+ V2 an `Array(String)` param) — there is no `IN (subquery)` anywhere in this
+ module, so the distributed-`IN` trap does not arise.
+- **Verdict**: **32 statement pairs, all IDENTICAL** — 18 IDENTICAL (4 counters
+ + 14 scratch-database deletes) and 14 IDENTICAL ERROR (the clustered
+ rendering, which cannot run on a single node; §*deleteFromClickhouse,
+ clustered rendering*).
+
+## `session_timezone`
+
+None of the five statements came off `clix`, so none of them ever sent a
+`session_timezone`. V1 sent no `clickhouse_settings` on the four counters and
+`{lightweight_deletes_sync: '0'}` on the deletes; V2 sends exactly the same,
+captured and compared per statement.
+
+## `getOrganizationBillingEventsCount`
+
+**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **15080373/15080373**;
+`meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 =
+16008988/16008988; wall V1/V2 = 232 ms / 204 ms; clickhouse_settings: *(none)*
+on both.
+
+```sql
+-- V1
+SELECT COUNT(*) AS count FROM events e
+WHERE project_id IN ('verdict','o\'brien-prod')
+ AND created_at BETWEEN '2026-08-01 00:00:00' AND '2026-08-20 00:00:00'
+ AND name NOT IN ('session_start', 'session_end')
+-- V2
+SELECT COUNT(*) AS count FROM events e
+WHERE project_id IN {p1:Array(String)}
+ AND created_at BETWEEN {p2:String} AND {p3:String}
+ AND name NOT IN {p4:Array(String)}
+-- V2 params: {"p1":["verdict","o'brien-prod"],"p2":"2026-08-01 00:00:00","p3":"2026-08-20 00:00:00","p4":["session_start","session_end"]}
+```
+
+## `getOrganizationEventsCount`
+
+**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **41921451/41921451**;
+`meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 =
+44371055/44371055; wall V1/V2 = 358 ms / 340 ms; clickhouse_settings: *(none)*
+on both.
+
+```sql
+-- V1
+SELECT COUNT(*) AS count FROM events e
+WHERE project_id IN ('verdict','o\'brien-prod')
+ AND name NOT IN ('session_start', 'session_end')
+-- V2
+SELECT COUNT(*) AS count FROM events e
+WHERE project_id IN {p1:Array(String)}
+ AND name NOT IN {p2:Array(String)}
+-- V2 params: {"p1":["verdict","o'brien-prod"],"p2":["session_start","session_end"]}
+```
+
+## `getOrganizationEventsCountSince`
+
+**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **18487546/18487546**;
+`meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 =
+19697131/19697131; wall V1/V2 = 248 ms / 259 ms; clickhouse_settings: *(none)*
+on both.
+
+`since = 2026-08-01T00:00:00Z`, and `formatClickhouseDate(since, true)` narrows
+it to the calendar day `'2026-08-01'` on both sides — kept as a bound `String`
+compared against a `DateTime64`, exactly the comparison V1 wrote, not promoted
+to `sql.date`.
+
+```sql
+-- V1
+SELECT COUNT(*) AS count FROM events e
+WHERE project_id IN ('verdict','o\'brien-prod')
+ AND name NOT IN ('session_start', 'session_end')
+ AND created_at >= '2026-08-01'
+-- V2
+SELECT COUNT(*) AS count FROM events e
+WHERE project_id IN {p1:Array(String)}
+ AND name NOT IN {p2:Array(String)}
+ AND created_at >= {p3:String}
+-- V2 params: {"p1":["verdict","o'brien-prod"],"p2":["session_start","session_end"],"p3":"2026-08-01"}
+```
+
+## `getOrganizationBillingEventsCountSerie`
+
+**statement** — IDENTICAL; rows V1/V2 = **20/20**; `data` byte-identical
+row-for-row (`2026-08-01` → 2852707, `2026-08-02` → 456447, `2026-08-03` → 360613,
+`2026-08-04` → 298741, … through `2026-08-20`);
+`meta` V1/V2 = `[{"name":"count","type":"UInt64"},{"name":"day","type":"Date"}]`;
+rows_read V1/V2 = 16352596/16352596; wall V1/V2 = 269 ms / 455 ms;
+clickhouse_settings: *(none)* on both.
+
+This is the case that proves `WITH FILL FROM toDate({pN:String})` is accepted:
+`WITH FILL` needs a constant bound, parameters are substituted at parse time, and
+the filled series comes back with the same 20 days on both sides.
+
+```sql
+-- V1
+SELECT COUNT(*) AS count, toDate(toStartOfDay(created_at)) AS day
+FROM events e
+WHERE project_id IN ('verdict','o\'brien-prod')
+ AND day BETWEEN '2026-08-01' AND '2026-08-20'
+ AND name NOT IN ('session_start', 'session_end')
+GROUP BY day
+ORDER BY day WITH FILL FROM toDate('2026-08-01') TO toDate('2026-08-20') STEP INTERVAL 1 DAY
+-- V2
+SELECT COUNT(*) AS count, toDate(toStartOfDay(created_at)) AS day
+FROM events e
+WHERE project_id IN {p1:Array(String)}
+ AND day BETWEEN {p2:String} AND {p3:String}
+ AND name NOT IN {p4:Array(String)}
+GROUP BY day
+ORDER BY day WITH FILL FROM toDate({p5:String}) TO toDate({p6:String}) STEP INTERVAL 1 DAY
+-- V2 params: {"p1":["verdict","o'brien-prod"],"p2":"2026-08-01","p3":"2026-08-20","p4":["session_start","session_end"],"p5":"2026-08-01","p6":"2026-08-20"}
+```
+
+V1's `const interval = 'day'` was never anything but `'day'`; V2 writes the
+bucket, the alias, the GROUP BY and the `STEP INTERVAL 1 DAY` out instead of
+deriving four spellings of it. The emitted text is identical apart from the
+bindings, as the two blocks above show.
+
+## `deleteFromClickhouse`, non-clustered rendering (executed)
+
+14 statements per side — 6 `DELETE FROM <t>` and 8 `ALTER TABLE <t> DELETE`,
+in `TABLE_NAMES` order — each ending `WHERE project_id IN …;` and each sent with
+`clickhouse_settings: {lightweight_deletes_sync: '0'}` on **both** sides.
+
+Executed against scratch database `m12_006_proof`: 14 tables
+`(project_id String, n UInt32) ENGINE = MergeTree ORDER BY project_id`, each
+seeded with 5 rows — `('verdict',1), ('verdict',2), ('o''brien-prod',3),
+('keepme',4), ('keepme',5)`. Each side got a freshly dropped + recreated +
+reseeded database; after issuing all 14 statements the run waited for
+`system.mutations` to drain and read every table back
+`ORDER BY project_id, n`. The scratch database is dropped at the end
+(`SELECT count() FROM system.databases WHERE name='m12_006_proof'` → 0).
+
+**statement set** — IDENTICAL; rows before = **70/70**; rows deleted V1/V2 =
+**42/42**; rows remaining V1/V2 = **28/28**; the post-delete contents of all 14
+tables are byte-identical between the two sides (`[["keepme",4],["keepme",5]]`
+in every table). The `o'brien-prod` row is deleted by both sides, which is the
+quote-escaping case reaching a row rather than a count.
+
+```sql
+-- V1 (first and fifth of the fourteen)
+DELETE FROM events WHERE project_id IN ('verdict','o\'brien-prod');
+ALTER TABLE cohort_events_mv DELETE WHERE project_id IN ('verdict','o\'brien-prod');
+-- V2
+DELETE FROM events WHERE project_id IN {p1:Array(String)};
+ALTER TABLE cohort_events_mv DELETE WHERE project_id IN {p1:Array(String)};
+-- V2 params (every one of the 14): {"p1":["verdict","o'brien-prod"]}
+```
+
+## `deleteFromClickhouse`, clustered rendering (IDENTICAL ERROR)
+
+`isClickhouseClustered()` is true unless `SELF_HOSTED` is set, and
+`getReplicatedTableName` then appends `ON CLUSTER '{cluster}'` — a clause, not
+an identifier, which is why V2 renders it as `sql.id(`${table}_replicated`)`
+followed by literal template text rather than through a single identifier.
+
+Both sides' 14 clustered statements were executed as rendered against
+`openpanel`. This box has no `*_replicated` table
+(`SELECT name FROM system.tables WHERE database='openpanel' AND name LIKE
+'%_replicated'` → 0 rows) and no cluster, so all 28 fail — **and they fail
+identically, statement for statement**:
+
+| rendering | V1 error | V2 error |
+|---|---|---|
+| `DELETE FROM <t>_replicated ON CLUSTER '{cluster}' …` (6) | `Code: 60 … UNKNOWN_TABLE` | same |
+| `ALTER TABLE <t>_replicated ON CLUSTER '{cluster}' DELETE …` (8) | `Code: 701 … Requested cluster 'openpanel_cluster' not found. (CLUSTER_DOESNT_EXIST)` | same |
+
+The `CLUSTER_DOESNT_EXIST` rows are the load-bearing evidence: the `{cluster}`
+macro expanded to `openpanel_cluster` on the V2 side **with `param_p1` supplied**,
+so ClickHouse's `{name:Type}` substitution does not disturb the `ON CLUSTER
+'{cluster}'` macro. 14 pairs, all IDENTICAL ERROR — V1 defects (well, V1
+*environment* limits) reproduced byte-for-byte, not fixed here.
+
+## Tests
+
+No test in this module compares generated SQL text, so none had to be retargeted
+to compare statement + params. `organization.service.test.ts` stubs
+`deps.ch.command` and asserts only that it was called
+(`expect(chCommand).toHaveBeenCalled()`); its assertions are unchanged. The one
+edit to that file is its header comment, which described the per-function lazy
+dynamic imports this task removed.
+
+## Reproduce
+
+```bash
+# getOrganizationBillingEventsCount, V1
+curl -s 'http://127.0.0.1:8123/?database=openpanel&default_format=JSONCompact' \
+ --data-binary "SELECT COUNT(*) AS count FROM events e WHERE project_id IN ('verdict','o\\'brien-prod') AND created_at BETWEEN '2026-08-01 00:00:00' AND '2026-08-20 00:00:00' AND name NOT IN ('session_start', 'session_end')"
+
+# getOrganizationBillingEventsCount, V2
+curl -s -G 'http://127.0.0.1:8123/' \
+ --data-urlencode 'database=openpanel' --data-urlencode 'default_format=JSONCompact' \
+ --data-urlencode "param_p1=['verdict','o\\'brien-prod']" \
+ --data-urlencode 'param_p2=2026-08-01 00:00:00' \
+ --data-urlencode 'param_p3=2026-08-20 00:00:00' \
+ --data-urlencode "param_p4=['session_start','session_end']" \
+ --data-urlencode 'query=SELECT COUNT(*) AS count FROM events e WHERE project_id IN {p1:Array(String)} AND created_at BETWEEN {p2:String} AND {p3:String} AND name NOT IN {p4:Array(String)}'
+```
+
+Both return `[[15080373]]`.
diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.ts
index 4c14e6e68..15f29a05b 100644
--- a/packages/core/src/modules/project/project.service.ts
+++ b/packages/core/src/modules/project/project.service.ts
@@ -13,22 +13,22 @@
// INSIDE `createProjectService(deps)` for the same reason
// `getClientByIdCached` does in client.service.ts — see that file's header.
//
-// ClickHouse queries here still build with clix/sqlstring/`chQuery`, not raw
-// `sql` fragments: ADR-013 converts the analytics read path one query per P7
-// task, and this module's two queries (`getProjectEventsCount`/
-// `getLastEventPerProject`) haven't been converted yet. The CLIENT is
-// `deps.ch` either way, through core's own `chQuery` (shared/ch-query.ts) —
-// M10-009 dropped the `compatChHelpers()` hop these two used to make.
+// M12-006 converted this module's two ClickHouse statements
+// (`getProjectEventsCount` / `getLastEventPerProject`) onto the ADR-013 `sql`
+// tag: every value binds as a `{pN:Type}` param, so `sqlstring` and `clix` are
+// both gone. The CLIENT is `deps.ch` either way, through core's own `chQuery`
+// (shared/ch-query.ts) — M10-009 dropped the `compatChHelpers()` hop these two
+// used to make. The V1-vs-V2 result-set proof is `project.sql.proof.md` beside
+// this file.
import crypto from 'node:crypto';
-import { clix } from '@openpanel/db/src/clickhouse/query-builder';
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import type {
Prisma,
Project,
ProjectType,
} from '@openpanel/db/src/prisma-client';
import { cacheable } from '@openpanel/redis';
-import sqlstring from 'sqlstring';
import { TRPCBadRequestError } from '../../rpc/errors';
import type { ServiceDeps } from '../../services';
import { convertClickhouseDateToJs } from '../../shared/ch-dates';
@@ -38,11 +38,21 @@ import { getId } from '../../shared/slug-id';
import { stripTrailingSlash } from '../../shared/string';
import { hashPassword } from '../auth/auth.service';
-// `clix` is a value import of `@openpanel/db` and stays one: it is a pure
-// query BUILDER that takes the client as its first argument
-// (`clix(deps.ch)`), not a connection — the same standing ADR-013's `sql` tag
-// has (see shared/ch-query.ts). `TABLE_NAMES` and the date helper are core's
-// own copies (shared/ch-tables.ts, shared/ch-dates.ts).
+// The `sql` tag is a value import of `@openpanel/db` and stays one: it is a
+// compile-time template tag holding no client (see shared/ch-query.ts).
+// `TABLE_NAMES` and the date helper are core's own copies
+// (shared/ch-tables.ts, shared/ch-dates.ts).
+//
+// clix sent `clickhouse_settings.session_timezone = 'UTC'` on every
+// `execute()` — `clix(client)` with no timezone argument defaults to it
+// (query-builder.ts:696-697, :562). `getLastEventPerProject` came off clix and
+// keeps sending it so its result set stays identical; `getProjectEventsCount`
+// was already a raw `chQuery` call, sent none, and still sends none.
+const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;
+// Session bookkeeping rows are worker-generated (the reaper can emit
+// session_end after tracking already stopped) — only real tracking activity
+// counts. V1 wrote this list inline in both statements.
+const NON_TRACKING_EVENT_NAMES = ['session_start', 'session_end'];
// GENUINE CYCLE, kept lazy: `createClientForOrganization`/
// `updateClientForOrganization` invalidate a project's clients' cache
// entries, and that cache now lives inside `createClientService(deps)` (see
@@ -171,7 +181,7 @@ export const getProjectEventsCount = async (
) => {
const res = await chQuery<{ count: number }>(
deps,
- `SELECT sum(event_count) as count FROM ${TABLE_NAMES.event_names_mv} WHERE project_id = ${sqlstring.escape(projectId)} AND name NOT IN ('session_start', 'session_end')`
+ sql`SELECT sum(event_count) as count FROM ${sql.id(TABLE_NAMES.event_names_mv)} WHERE project_id = ${sql.string(projectId)} AND name NOT IN ${sql.array('String', NON_TRACKING_EVENT_NAMES)}`
);
return res[0]?.count;
};
@@ -186,17 +196,16 @@ export const getProjectEventsCount = async (
export const getLastEventPerProject = async (
deps: ServiceDeps
): Promise<Map<string, Date>> => {
- const res = await clix(deps.ch)
- .select<{ project_id: string; last_event_at: string }>([
- 'project_id',
- 'max(created_at) AS last_event_at',
- ])
- .from(TABLE_NAMES.event_names_mv)
- // Session rows are worker-generated (the reaper can emit session_end after
- // tracking already stopped) — only real tracking activity should count.
- .where('name', 'NOT IN', ['session_start', 'session_end'])
- .groupBy(['project_id'])
- .execute();
+ const res = await chQuery<{ project_id: string; last_event_at: string }>(
+ deps,
+ sql`
+ SELECT project_id, max(created_at) AS last_event_at
+ FROM ${sql.id(TABLE_NAMES.event_names_mv)}
+ WHERE name NOT IN ${sql.array('String', NON_TRACKING_EVENT_NAMES)}
+ GROUP BY project_id
+ `,
+ CLIX_SESSION_TIMEZONE
+ );
return new Map(
res.map((row) => [
row.project_id,
diff --git a/packages/core/src/modules/project/project.sql.proof.md b/packages/core/src/modules/project/project.sql.proof.md
new file mode 100644
index 000000000..36997e4f2
--- /dev/null
+++ b/packages/core/src/modules/project/project.sql.proof.md
@@ -0,0 +1,146 @@
+# project.service.ts — V1 → V2 result-set proof (M12-006)
+
+Both ClickHouse statements `packages/core/src/modules/project/project.service.ts`
+runs, executed V1 against V2 on the local prod-copy `openpanel`. V1 is the file
+at commit `78098bdc`
+(`git show HEAD:packages/core/src/modules/project/project.service.ts`), which
+builds `getProjectEventsCount` as a `sqlstring.escape`d template string and
+`getLastEventPerProject` with `clix`; V2 is the converted file, every value
+bound as a `{pN:Type}` param. **Both files were imported into one Bun process
+and called with the same inputs** — the SQL below was produced by calling the
+real exported functions with a `deps.ch.query` stub that captures
+`{query, query_params, clickhouse_settings}`, never by retyping V1 by hand. Each
+captured statement was then executed through the local HTTP interface at
+`format: 'JSON'` with the settings its own side asked for; V1 went as `query`,
+V2 as `query` + `param_pN`. `data` was compared row-for-row and `meta`
+column-for-column.
+
+**One case was compared as a set**: `getLastEventPerProject` is
+`GROUP BY project_id` with **no `ORDER BY` at all**, so ClickHouse is free to
+emit the 1,864 groups in any order and V1-vs-V2 row order carries no meaning.
+Its 1,864 rows are identical as a set (`{project_id, last_event_at}` pairs
+sorted and compared) and the two sides did in fact come back in different orders
+— V1's 3rd/4th rows are `paper`/`2334`, V2's are `2334`/`paper`, same pairs — so
+the set comparison is load-bearing here rather than a formality. Nothing was
+sorted away that is not explained here.
+
+- **Date**: 2026-09-07.
+- **Data**: local prod-copy `openpanel`, 319,850,903 events;
+ `distinct_event_names_mv` holds 1,864 projects. Fixtures: `verdict`
+ (41,921,451 non-session events) for the positive-row case, and
+ `o'brien-prod` — **which does not exist** — for the quote-in-the-value
+ escaping case. That second case returns one row whose `count` is 0; its
+ positive-row twin is the `verdict` run immediately above it, and it is listed
+ because a value carrying a `'` is the whole point of the escaping half of this
+ conversion.
+- **Machine**: single-node ClickHouse 26.1.3.52 on this box — timings are
+ directional only; production is 2 shards × 2 replicas
+ (`docs/ENVIRONMENT.md`). **No `IN` / `GLOBAL IN` was changed in either
+ direction.** `grep -c GLOBAL` is `0` on the V1 file and `0` on the V2 file;
+ both sides emit exactly one `NOT IN` per statement and its operand is a
+ literal value list (V1 an inline tuple, V2 an `Array(String)` param) — there
+ is no `IN (subquery)` in this module, so the distributed-`IN` trap does not
+ arise.
+- **Verdict**: **3 statement pairs, all IDENTICAL.**
+
+## `session_timezone`
+
+`clix(client)` with no timezone argument defaults to `'UTC'`
+(`query-builder.ts:696-697`) and sends it as
+`clickhouse_settings.session_timezone` on every `execute()` (`:562`).
+`getProjectEventsCount` was already a raw `chQuery(deps, text)` call and sent
+none. V2 preserves both halves via `CLIX_SESSION_TIMEZONE`, and the capture
+confirms it per statement:
+
+| statement | built by (V1) | V1 sent | V2 sends |
+|---|---|---|---|
+| `getProjectEventsCount` | raw `chQuery` | *(none)* | *(none)* |
+| `getLastEventPerProject` | `clix` | `UTC` | `UTC` |
+
+## `getProjectEventsCount` — `verdict`
+
+**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 =
+**41921451/41921451**; `meta` V1/V2 = `[{"name":"count","type":"UInt64"}]`;
+rows_read V1/V2 = 221184/221184; wall V1/V2 = 10 ms / 9 ms;
+clickhouse_settings: *(none)* on both.
+
+```sql
+-- V1
+SELECT sum(event_count) as count FROM distinct_event_names_mv
+WHERE project_id = 'verdict' AND name NOT IN ('session_start', 'session_end')
+-- V2
+SELECT sum(event_count) as count FROM distinct_event_names_mv
+WHERE project_id = {p1:String} AND name NOT IN {p2:Array(String)}
+-- V2 params: {"p1":"verdict","p2":["session_start","session_end"]}
+```
+
+## `getProjectEventsCount` — `o'brien-prod` (quote in the value)
+
+**statement** — IDENTICAL; rows V1/V2 = 1/1; `count` V1/V2 = **0/0**; `meta`
+V1/V2 = `[{"name":"count","type":"UInt64"}]`; rows_read V1/V2 = 8192/8192; wall
+V1/V2 = 4 ms / 4 ms; clickhouse_settings: *(none)* on both.
+
+The single quote is handled on both sides — V1 by `sqlstring`'s backslash escape
+(`'o\'brien-prod'`), V2 by never putting the value in the text at all. No such
+project exists in the prod copy, so the count is 0 on both sides; the row-bearing
+coverage for this statement is the `verdict` case above.
+
+```sql
+-- V1
+SELECT sum(event_count) as count FROM distinct_event_names_mv
+WHERE project_id = 'o\'brien-prod' AND name NOT IN ('session_start', 'session_end')
+-- V2
+SELECT sum(event_count) as count FROM distinct_event_names_mv
+WHERE project_id = {p1:String} AND name NOT IN {p2:Array(String)}
+-- V2 params: {"p1":"o'brien-prod","p2":["session_start","session_end"]}
+```
+
+## `getLastEventPerProject`
+
+**statement** — IDENTICAL (**compared as a set**, see the header); rows V1/V2 =
+**1864/1864**; `meta` V1/V2 =
+`[{"name":"project_id","type":"String"},{"name":"last_event_at","type":"DateTime64(3)"}]`;
+rows_read V1/V2 = 10992588/11000780; wall V1/V2 = 125 ms / 134 ms;
+clickhouse_settings: `session_timezone=UTC` (both).
+
+`rows_read` differs by 8,192 (one granule) between the two sides. That is index
+analysis treating a bound `{p1:Array(String)}` differently from an inline tuple
+for the `NOT IN` on a `LowCardinality(String)` column — a perf note, not a
+semantic one: the 1,864 returned groups and their `max(created_at)` values are
+identical.
+
+```sql
+-- V1
+SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv
+WHERE name NOT IN ('session_start', 'session_end')
+GROUP BY project_id
+-- V2
+SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv
+WHERE name NOT IN {p1:Array(String)}
+GROUP BY project_id
+-- V2 params: {"p1":["session_start","session_end"]}
+```
+
+## Tests
+
+No test in this module compares generated SQL text, so none had to be retargeted
+to compare statement + params. `project.service.test.ts` exercises the Postgres
+half of the service through a fake `deps.db`; its assertions are unchanged and
+the file is untouched by this task.
+
+## Reproduce
+
+```bash
+# getLastEventPerProject, V1
+curl -s 'http://127.0.0.1:8123/?database=openpanel&session_timezone=UTC&default_format=JSONCompact' \
+ --data-binary "SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv WHERE name NOT IN ('session_start', 'session_end') GROUP BY project_id"
+
+# getLastEventPerProject, V2
+curl -s -G 'http://127.0.0.1:8123/' \
+ --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \
+ --data-urlencode 'default_format=JSONCompact' \
+ --data-urlencode "param_p1=['session_start','session_end']" \
+ --data-urlencode 'query=SELECT project_id, max(created_at) AS last_event_at FROM distinct_event_names_mv WHERE name NOT IN {p1:Array(String)} GROUP BY project_id'
+```
+
+Both return 1,864 rows.
diff --git a/packages/core/src/v1-compat.ts b/packages/core/src/v1-compat.ts
index 15c3693c6..56322d1c6 100644
--- a/packages/core/src/v1-compat.ts
+++ b/packages/core/src/v1-compat.ts
@@ -381,12 +381,12 @@ export async function compatPrisma(): Promise<
/**
* ADR-013 keeps `clix`/`chQuery`/`TABLE_NAMES` alive until the analytics read
- * path's P7 conversion (one query per task, old-vs-new result sets diffed) —
- * `project.service.ts`'s two still-unconverted functions and mcp's
- * `analytics/property-values.ts` reach the query-building helpers here
- * instead of importing `@openpanel/db` themselves. The CLIENT itself is
- * still `deps.ch` / `compatCh()`; this is only the pure helpers that live
- * beside it.
+ * path's conversion (one query per task, old-vs-new result sets diffed) —
+ * `misc.service.ts`'s still-unconverted queries reach the query-building
+ * helpers here instead of importing `@openpanel/db` themselves. The CLIENT
+ * itself is still `deps.ch` / `compatCh()`; this is only the pure helpers
+ * that live beside it. (M12-006 converted the other two callers,
+ * `project.service.ts` and mcp's `analytics/property-values.ts`.)
*/
export async function compatChHelpers(): Promise<{
TABLE_NAMES: typeof import('@openpanel/db/src/clickhouse/client').TABLE_NAMES;