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-007): insight engine off clix: the five insight modules, engine.ts, types.ts and the cached wrapper rebuilt on the sql tag with the same cache semantics, proof, goldens 137/137

ralph68fea1a7d12b
diff --git a/packages/core/src/modules/insight/insight.service.ts b/packages/core/src/modules/insight/insight.service.ts
index 2fb077a2e..6b500bb2e 100644
--- a/packages/core/src/modules/insight/insight.service.ts
+++ b/packages/core/src/modules/insight/insight.service.ts
@@ -15,9 +15,10 @@
// intra-package lazy imports (engine, store, detection modules) kept lazy for
// their own import cost, not for a client's.
//
-// ClickHouse queries here still go through clix, 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.
+// M12-007: the engine and its five detection modules run on the `sql` tag
+// (ADR-013); `createEngine` therefore takes the scope's deps rather than a bare
+// ClickHouse client, so the requestId reaches every module statement.
+// `legacy-scan.ts` is the last clix holdout in this module (M12-008).
import { getRedisCache } from '@openpanel/redis';
import {
@@ -231,7 +232,6 @@ export async function runProjectInsights(
}
): Promise<void> {
const { projectId, date, logger } = args;
- const ch = deps.ch;
const [{ createEngine }, insightStore, detectionModules] = await Promise.all([
loadEngine(),
loadStore(deps),
@@ -247,7 +247,7 @@ export async function runProjectInsights(
detectionModules.geoModule,
detectionModules.devicesModule,
],
- db: ch,
+ deps,
config: DEFAULT_ENGINE_CONFIG,
});
diff --git a/packages/core/src/modules/insight/src/cached-clix.ts b/packages/core/src/modules/insight/src/cached-clix.ts
deleted file mode 100644
index 332d2c965..000000000
--- a/packages/core/src/modules/insight/src/cached-clix.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import crypto from 'node:crypto';
-import type { ClickHouseClient } from '@clickhouse/client';
-import {
- clix as originalClix,
- type Query,
-} from '@openpanel/db/src/clickhouse/query-builder';
-
-/**
- * Creates a cached wrapper around clix that automatically caches query results
- * based on query hash. This eliminates duplicate queries within the same module/window context.
- *
- * @param client - ClickHouse client
- * @param cache - Optional cache Map to store query results
- * @param timezone - Timezone for queries (defaults to UTC)
- * @returns A function that creates cached Query instances (compatible with clix API)
- */
-export function createCachedClix(
- client: ClickHouseClient,
- cache?: Map<string, any>,
- timezone?: string
-) {
- function clixCached(): Query {
- const query = originalClix(client, timezone);
- const queryTimezone = timezone ?? 'UTC';
-
- // Override execute() method to add caching
- const originalExecute = query.execute.bind(query);
- query.execute = async () => {
- // Build the query SQL string
- const querySQL = query.toSQL();
-
- // Create cache key from query SQL + timezone
- const cacheKey = crypto
- .createHash('sha256')
- .update(`${querySQL}|${queryTimezone}`)
- .digest('hex');
-
- // Check cache first
- if (cache?.has(cacheKey)) {
- return cache.get(cacheKey);
- }
-
- // Execute query
- const result = await originalExecute();
-
- // Cache the result
- if (cache) {
- cache.set(cacheKey, result);
- }
-
- return result;
- };
-
- return query;
- }
-
- // Copy static methods from original clix
- clixCached.exp = originalClix.exp;
- clixCached.date = originalClix.date;
- clixCached.datetime = originalClix.datetime;
- clixCached.dynamicDatetime = originalClix.dynamicDatetime;
- clixCached.toStartOf = originalClix.toStartOf;
- clixCached.toStartOfInterval = originalClix.toStartOfInterval;
- clixCached.toInterval = originalClix.toInterval;
- clixCached.toDate = originalClix.toDate;
-
- return clixCached;
-}
diff --git a/packages/core/src/modules/insight/src/cached-query.test.ts b/packages/core/src/modules/insight/src/cached-query.test.ts
new file mode 100644
index 000000000..5b3698212
--- /dev/null
+++ b/packages/core/src/modules/insight/src/cached-query.test.ts
@@ -0,0 +1,113 @@
+// The cache-key contract of the wrapper that replaced `cached-clix.ts`.
+//
+// The clix wrapper keyed on `sha256(toSQL() + '|' + timezone)`, which was only
+// sound because clix inlined every value into the text it hashed. The `sql`
+// tag names its placeholders `{p1}, {p2}, …` from a per-render counter, so two
+// statements that differ only in their bound values render to the SAME text —
+// the second test below is the regression that a text-only key would fail.
+//
+// No module mock: `chQuery` is a thin wrapper over `deps.ch.query`, so a fake
+// client counts the round trips and shows what was actually sent.
+
+import { expect, test } from 'bun:test';
+import { sql } from '@openpanel/db/src/clickhouse/sql';
+import type { ChScope } from '../../../shared/ch-query';
+import { createStatementCache } from './cached-query';
+
+function fakeDeps(
+ rowsFor: (query_params: Record<string, unknown>) => object[]
+) {
+ const calls: {
+ query: string;
+ query_params?: Record<string, unknown>;
+ settings?: Record<string, unknown>;
+ }[] = [];
+ const deps = {
+ ch: {
+ query: async ({ query, query_params, clickhouse_settings }: any) => {
+ calls.push({ query, query_params, settings: clickhouse_settings });
+ return {
+ json: async () => ({
+ data: rowsFor(query_params ?? {}),
+ meta: [{ name: 'c', type: 'String' }],
+ rows: 1,
+ }),
+ };
+ },
+ },
+ logger: {
+ info: () => undefined,
+ warn: () => undefined,
+ error: () => undefined,
+ },
+ } as unknown as ChScope;
+ return { deps, calls };
+}
+
+const countFor = (projectId: string) =>
+ sql`SELECT count() AS c FROM sessions WHERE project_id = ${sql.string(projectId)}`;
+
+test('an identical statement runs once per module/window context', async () => {
+ const { deps, calls } = fakeDeps(() => [{ c: '1' }]);
+ const run = createStatementCache(deps, new Map());
+
+ const first = await run(countFor('alpha'));
+ const second = await run(countFor('alpha'));
+
+ expect(calls).toHaveLength(1);
+ expect(second).toEqual(first);
+});
+
+test('equal text with different params is a different key', async () => {
+ const alpha = countFor('alpha');
+ const beta = countFor('beta');
+ // The premise: a key over the rendered text alone would collide here.
+ expect(beta.toStatement().query).toBe(alpha.toStatement().query);
+ expect(beta.toStatement().query_params).not.toEqual(
+ alpha.toStatement().query_params
+ );
+
+ const { deps, calls } = fakeDeps((params) => [{ c: params.p1 }]);
+ const run = createStatementCache(deps, new Map());
+
+ expect(await run(alpha)).toEqual([{ c: 'alpha' }]);
+ expect(await run(beta)).toEqual([{ c: 'beta' }]);
+ expect(calls).toHaveLength(2);
+});
+
+test('without a cache every call reaches ClickHouse', async () => {
+ const { deps, calls } = fakeDeps(() => [{ c: '1' }]);
+ const run = createStatementCache(deps);
+
+ await run(countFor('alpha'));
+ await run(countFor('alpha'));
+
+ expect(calls).toHaveLength(2);
+});
+
+test('the timezone defaults to UTC, travels as session_timezone, and keys', async () => {
+ const { deps, calls } = fakeDeps(() => [{ c: '1' }]);
+ const shared = new Map<string, unknown>();
+
+ await createStatementCache(deps, shared)(countFor('alpha'));
+ expect(calls[0]?.settings).toEqual({ session_timezone: 'UTC' });
+
+ await createStatementCache(
+ deps,
+ shared,
+ 'Europe/Stockholm'
+ )(countFor('alpha'));
+ expect(calls).toHaveLength(2);
+ expect(calls[1]?.settings).toEqual({ session_timezone: 'Europe/Stockholm' });
+});
+
+test('the bound params reach ClickHouse, never the query text', async () => {
+ const { deps, calls } = fakeDeps(() => [{ c: '1' }]);
+ const run = createStatementCache(deps, new Map());
+
+ await run(countFor("o'brien"));
+
+ expect(calls[0]?.query).toContain('{p1:String}');
+ expect(calls[0]?.query).not.toContain("o'brien");
+ expect(calls[0]?.query_params).toEqual({ p1: "o'brien" });
+});
diff --git a/packages/core/src/modules/insight/src/cached-query.ts b/packages/core/src/modules/insight/src/cached-query.ts
new file mode 100644
index 000000000..d267a9776
--- /dev/null
+++ b/packages/core/src/modules/insight/src/cached-query.ts
@@ -0,0 +1,66 @@
+// M12-007: the replacement for `cached-clix.ts` (ADR-013 decision 21).
+//
+// The wrapper it replaces memoised `clix`'s `execute()` on
+// `sha256(query.toSQL() + '|' + timezone)` — safe only because clix inlined
+// every value into the text it hashed. The `sql` tag renders `{pN:Type}`
+// placeholders whose names come from a per-render counter, so two statements
+// that differ only in their bound values render to the SAME text: the key must
+// carry the params as well, or one project's window would serve another's.
+//
+// Everything else is deliberately unchanged from the clix wrapper: the `Map`
+// belongs to the caller (per module+window, never module-level — it is keyed by
+// nothing tenant-scoped), the timezone defaults to `'UTC'` exactly as
+// `clix(client, timezone)` did (query-builder.ts:696) and travels as
+// `session_timezone` in `clickhouse_settings` exactly as `.execute()` sent it
+// (query-builder.ts:562).
+
+import crypto from 'node:crypto';
+import type { ClickHouseSettings } from '@clickhouse/client';
+import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';
+import { type ChScope, chQuery } from '../../../shared/ch-query';
+
+/** clix's own default when a call site passed no timezone. */
+const DEFAULT_SESSION_TIMEZONE = 'UTC';
+
+/** Runs one bound statement, memoised per module+window context. */
+export type StatementRunner = <T extends object>(
+ statement: SqlFragment
+) => Promise<T[]>;
+
+/**
+ * @param deps the scope's ClickHouse client + logger (so the requestId reaches
+ * the query — ADR-018).
+ * @param cache per module+window result cache; omit to disable memoisation.
+ * @param timezone `session_timezone` for every statement run through it.
+ */
+export function createStatementCache(
+ deps: ChScope,
+ cache?: Map<string, unknown>,
+ timezone?: string
+): StatementRunner {
+ const sessionTimezone = timezone ?? DEFAULT_SESSION_TIMEZONE;
+ const settings: ClickHouseSettings = { session_timezone: sessionTimezone };
+
+ return async <T extends object>(statement: SqlFragment): Promise<T[]> => {
+ if (!cache) {
+ return chQuery<T>(deps, statement, settings);
+ }
+
+ const { query, query_params } = statement.toStatement();
+ // Param names are assigned in render order from one counter, so
+ // `JSON.stringify` is stable for a given fragment and two fragments that
+ // differ only in param ORDER are correctly different keys. Do not sort.
+ const cacheKey = crypto
+ .createHash('sha256')
+ .update(`${query}|${JSON.stringify(query_params)}|${sessionTimezone}`)
+ .digest('hex');
+
+ if (cache.has(cacheKey)) {
+ return cache.get(cacheKey) as T[];
+ }
+
+ const rows = await chQuery<T>(deps, statement, settings);
+ cache.set(cacheKey, rows);
+ return rows;
+ };
+}
diff --git a/packages/core/src/modules/insight/src/engine.ts b/packages/core/src/modules/insight/src/engine.ts
index 4c4a3738a..7222d76dc 100644
--- a/packages/core/src/modules/insight/src/engine.ts
+++ b/packages/core/src/modules/insight/src/engine.ts
@@ -1,4 +1,5 @@
-import { createCachedClix } from './cached-clix';
+import type { ChScope } from '../../../shared/ch-query';
+import { createStatementCache } from './cached-query';
import { materialDecision } from './material';
import { defaultImpactScore, severityBand } from './scoring';
import type {
@@ -79,11 +80,12 @@ function chunk<T>(arr: T[], size: number): T[][] {
export function createEngine(args: {
store: InsightStore;
modules: InsightModule[];
- db: any;
+ /** The scope's ClickHouse client + logger; every module query runs on it. */
+ deps: ChScope;
logger?: Pick<Console, 'info' | 'warn' | 'error'>;
config: EngineConfig;
}) {
- const { store, modules, db, config } = args;
+ const { store, modules, deps, config } = args;
const logger = args.logger ?? console;
function isProjectOldEnoughForWindow(
@@ -120,14 +122,13 @@ export function createEngine(args: {
}
// Initialize cache for this module+window combination.
// Cache is automatically garbage collected when context goes out of scope.
- const cache = new Map<string, any>();
+ const cache = new Map<string, unknown>();
ctx = {
projectId,
window,
- db,
now,
logger: projLogger,
- clix: createCachedClix(db, cache),
+ runQuery: createStatementCache(deps, cache),
};
} catch (e) {
projLogger.error('[insights] failed to create compute context', {
diff --git a/packages/core/src/modules/insight/src/insight-modules.sql.proof.md b/packages/core/src/modules/insight/src/insight-modules.sql.proof.md
new file mode 100644
index 000000000..ca8339439
--- /dev/null
+++ b/packages/core/src/modules/insight/src/insight-modules.sql.proof.md
@@ -0,0 +1,727 @@
+# insight-modules — V1 → V2 result-set proof (M12-007)
+
+The five insight detection modules (`devices`, `geo`, `page-trends`,
+`referrers`, `entry-pages`) moved off `createCachedClix` onto the ADR-013 `sql`
+tag. V1 is the code at `43dedb75` (this task's parent), extracted with
+`git show HEAD:<path>` into `/tmp/m12007/v1src/` with only its relative import
+specifiers rewritten to absolute paths — the SQL-producing code is byte-identical
+to HEAD. Both sides were driven through the **same** `enumerateDimensions(ctx)`
+entry point with the same `projectId`, the same `now` and the same three window
+kinds; V1's ClickHouse client and V2's `ctx.runQuery` were each replaced by a
+recorder, so the two statement lists come from the real code paths rather than
+from retyped SQL. Every V1 statement was then executed as `query`, every V2
+statement as `query` + `query_params`, against the same local prod-copy
+ClickHouse over one HTTP endpoint with `default_format=JSON` and
+`session_timezone=UTC` on both sides (clix's own default — `query-builder.ts:696`
+sets `timezone ?? 'UTC'` and `:562` sends it as `session_timezone`; the new
+wrapper defaults to `'UTC'` identically). `data` and `meta` were compared in
+full. None of these statements has a total `ORDER BY` — every one is a bare
+`GROUP BY` or a single-row aggregate — so **all 35 cases were compared as sets**
+(rows sorted by their JSON encoding on both sides before comparison); `meta` was
+compared in column order.
+
+- **Date**: 2026-09-07.
+- **Data**: local prod-copy `openpanel`, 319,850,963 events. Project
+ `openalternative`, driven at `now = 2026-08-26T12:00:00.000Z` (its
+ `screen_view` events stop on 2026-08-25, and this `now` is what keeps every
+ page-trends case non-empty). Project timezone is not read by these modules —
+ clix sent `session_timezone: 'UTC'` unconditionally and so does the
+ replacement. No fixture is empty here: **every one of the 35 cases returns a
+ non-zero row count on both sides**.
+- **Machine**: single-node ClickHouse 26.1.3.52 on a 4-vCPU box — timings are
+ directional only; production is 2 shards × 2 replicas
+ (`docs/ENVIRONMENT.md`). None of these statements contains `IN`, `GLOBAL IN`,
+ `JOIN` or a subquery of any kind: `grep -nE 'GLOBAL |[^A-Za-z_]IN[ (]|JOIN'`
+ over the five converted `*.module.ts` files returns nothing, and the same grep
+ over their V1 form at `43dedb75` also returns nothing. No `IN`/`GLOBAL IN` was
+ introduced, removed or rewritten in either direction.
+- **Verdict**: **35 cases, all IDENTICAL.**
+
+## Coverage
+
+Each module issues 5 distinct statements — 3 on the `yesterday` branch, 2 on the
+`rolling_*` branch. Both branches were exercised, and the `rolling_*` branch
+twice (`rolling_7d` and `rolling_30d`, different dates through the same text),
+giving 7 executed cases per module and 35 in total.
+
+## Cache-key derivation, before and after
+
+| | V1 (`cached-clix.ts`, deleted) | V2 (`cached-query.ts`) |
+|---|---|---|
+| key | `sha256(query.toSQL() + '\|' + timezone)` (lines 32-36) | `sha256(query + '\|' + JSON.stringify(query_params) + '\|' + timezone)` |
+| why it worked / must change | clix inlined every value as a literal, so the text alone identified the query | the `sql` tag renders `{p1:Type}, {p2:Type}, …` from a per-render counter, so two statements differing only in their bound values render to the **same text** |
+| timezone | `timezone ?? 'UTC'`, folded into the key | unchanged, including the `'UTC'` default |
+| `session_timezone` | `clickhouse_settings.session_timezone` on every `execute()` | `clickhouse_settings.session_timezone` on every `chQuery` |
+| cache | caller-supplied `Map`, one per module+window, built in `engine.ts` | unchanged — same `Map`, same place, same lifetime |
+| miss path | `clix(...).execute()` | `chQuery(deps, statement, settings)` — same retry/round-robin client, now carrying the request's logger (ADR-018) |
+
+`JSON.stringify(query_params)` is stable because `toStatement()` assigns
+`p1, p2, …` in render order from one counter; the keys are deliberately **not**
+sorted, so two fragments that differ only in param order stay different keys.
+
+`packages/core/src/modules/insight/src/cached-query.test.ts` pins all of it —
+in particular `equal text with different params is a different key`, which first
+asserts the two statements' rendered text is byte-equal (the collision a
+text-only key would produce) and then that both reach ClickHouse.
+
+## Tests
+
+No existing insight test compared generated SQL text: the three test files in
+this module (`insight.service.test.ts`, `insight.jobs.test.ts`,
+`insight.rpc.test.ts`) assert delegation and payload shapes only, and none of
+them is touched by this task. There was therefore no text-comparing test to
+retarget onto `statement + params`; the new `cached-query.test.ts` is the only
+test added, and it compares statement text **and** params.
+
+## Cases
+
+### devices
+
+**devices — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 3/3; rows_read V1/V2 = 16384/16384; wall V1/V2 = 11 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "device", "type": "LowCardinality(String)"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT device, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device
+
+-- V2
+SELECT device, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY device
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}
+```
+
+**devices — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 99/99; rows_read V1/V2 = 212928/212928; wall V1/V2 = 23 ms / 18 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "device", "type": "LowCardinality(String)"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT toDate(created_at) as date, device, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, device
+
+-- V2
+SELECT toDate(created_at) as date, device, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY date, device
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}
+```
+
+**devices — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 15 ms / 12 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total
+FROM sessions
+WHERE project_id = {p3:String}
+ AND sign = {p4:Int8}
+ AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}
+```
+
+**devices — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 5/5; rows_read V1/V2 = 131025/131025; wall V1/V2 = 11 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "device", "type": "LowCardinality(String)"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT device, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device
+
+-- V2
+SELECT device, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY device
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**devices — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 9 ms / 7 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**devices — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 6/6; rows_read V1/V2 = 311191/311191; wall V1/V2 = 16 ms / 14 ms; `meta` V1/V2 (identical) = `[{"name": "device", "type": "LowCardinality(String)"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT device, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device
+
+-- V2
+SELECT device, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY device
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**devices — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 10 ms / 9 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+### geo
+
+**geo — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 154/154; rows_read V1/V2 = 16384/16384; wall V1/V2 = 5 ms / 4 ms; `meta` V1/V2 (identical) = `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT country, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY country
+
+-- V2
+SELECT country, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY country
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}
+```
+
+**geo — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 3876/3876; rows_read V1/V2 = 212928/212928; wall V1/V2 = 14 ms / 13 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT toDate(created_at) as date, country, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, country
+
+-- V2
+SELECT toDate(created_at) as date, country, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY date, country
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}
+```
+
+**geo — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 9 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total
+FROM sessions
+WHERE project_id = {p3:String}
+ AND sign = {p4:Int8}
+ AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}
+```
+
+**geo — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 202/202; rows_read V1/V2 = 131025/131025; wall V1/V2 = 8 ms / 7 ms; `meta` V1/V2 (identical) = `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT country, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY country
+
+-- V2
+SELECT country, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY country
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**geo — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 7 ms / 12 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**geo — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 213/213; rows_read V1/V2 = 311191/311191; wall V1/V2 = 14 ms / 15 ms; `meta` V1/V2 (identical) = `[{"name": "country", "type": "LowCardinality(FixedString(2))"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT country, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY country
+
+-- V2
+SELECT country, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY country
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**geo — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 11 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+### page-trends
+
+**page-trends — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 1057/1057; rows_read V1/V2 = 32755/32755; wall V1/V2 = 8 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT origin, path, count(*) as cnt FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY origin, path
+
+-- V2
+SELECT origin, path, count(*) as cnt
+FROM events
+WHERE project_id = {p1:String}
+ AND name = {p2:String}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY origin, path
+
+-- V2 params: {"p1": "openalternative", "p2": "screen_view", "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}
+```
+
+**page-trends — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 54996/54996; rows_read V1/V2 = 1212377/1212377; wall V1/V2 = 160 ms / 148 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT toDate(created_at) as date, origin, path, count(*) as cnt FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, origin, path
+
+-- V2
+SELECT toDate(created_at) as date, origin, path, count(*) as cnt
+FROM events
+WHERE project_id = {p1:String}
+ AND name = {p2:String}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY date, origin, path
+
+-- V2 params: {"p1": "openalternative", "p2": "screen_view", "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}
+```
+
+**page-trends — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1245144/1245144; wall V1/V2 = 40 ms / 28 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total
+FROM events
+WHERE project_id = {p3:String}
+ AND name = {p4:String}
+ AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": "screen_view", "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}
+```
+
+**page-trends — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 6608/6608; rows_read V1/V2 = 581593/581593; wall V1/V2 = 42 ms / 50 ms; `meta` V1/V2 (identical) = `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT origin, path, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY origin, path
+
+-- V2
+SELECT origin, path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM events
+WHERE project_id = {p5:String}
+ AND name = {p6:String}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY origin, path
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**page-trends — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 581593/581593; wall V1/V2 = 32 ms / 21 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM events
+WHERE project_id = {p5:String}
+ AND name = {p6:String}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**page-trends — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 13246/13246; rows_read V1/V2 = 1687334/1687334; wall V1/V2 = 99 ms / 112 ms; `meta` V1/V2 (identical) = `[{"name": "origin", "type": "String"}, {"name": "path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT origin, path, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY origin, path
+
+-- V2
+SELECT origin, path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM events
+WHERE project_id = {p5:String}
+ AND name = {p6:String}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY origin, path
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**page-trends — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 1687334/1687334; wall V1/V2 = 42 ms / 31 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM events WHERE project_id = 'openalternative' AND name = 'screen_view' AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM events
+WHERE project_id = {p5:String}
+ AND name = {p6:String}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": "screen_view", "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+### referrers
+
+**referrers — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 75/75; rows_read V1/V2 = 16384/16384; wall V1/V2 = 5 ms / 5 ms; `meta` V1/V2 (identical) = `[{"name": "referrer_name", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT referrer_name, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY referrer_name
+
+-- V2
+SELECT referrer_name, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY referrer_name
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}
+```
+
+**referrers — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 2112/2112; rows_read V1/V2 = 212928/212928; wall V1/V2 = 15 ms / 15 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "referrer_name", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT toDate(created_at) as date, referrer_name, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, referrer_name
+
+-- V2
+SELECT toDate(created_at) as date, referrer_name, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY date, referrer_name
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}
+```
+
+**referrers — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 12 ms / 11 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total
+FROM sessions
+WHERE project_id = {p3:String}
+ AND sign = {p4:Int8}
+ AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}
+```
+
+**referrers — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 331/331; rows_read V1/V2 = 131025/131025; wall V1/V2 = 10 ms / 10 ms; `meta` V1/V2 (identical) = `[{"name": "referrer_name", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT referrer_name, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY referrer_name
+
+-- V2
+SELECT referrer_name, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY referrer_name
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**referrers — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 8 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**referrers — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 798/798; rows_read V1/V2 = 311191/311191; wall V1/V2 = 16 ms / 13 ms; `meta` V1/V2 (identical) = `[{"name": "referrer_name", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT referrer_name, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY referrer_name
+
+-- V2
+SELECT referrer_name, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY referrer_name
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**referrers — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 9 ms / 9 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+### entry-pages
+
+**entry-pages — current window, grouped (`yesterday`)** — IDENTICAL; rows V1/V2 = 1191/1191; rows_read V1/V2 = 16384/16384; wall V1/V2 = 7 ms / 6 ms; `meta` V1/V2 (identical) = `[{"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT entry_origin, entry_path, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY entry_origin, entry_path
+
+-- V2
+SELECT entry_origin, entry_path, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY entry_origin, entry_path
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-08-25 00:00:00", "p4": "2026-08-25 23:59:59"}
+```
+
+**entry-pages — baseline 28 days, grouped by day (`yesterday`)** — IDENTICAL; rows V1/V2 = 34473/34473; rows_read V1/V2 = 212928/212928; wall V1/V2 = 94 ms / 93 ms; `meta` V1/V2 (identical) = `[{"name": "date", "type": "Date"}, {"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cnt", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT toDate(created_at) as date, entry_origin, entry_path, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-24 23:59:59' GROUP BY date, entry_origin, entry_path
+
+-- V2
+SELECT toDate(created_at) as date, entry_origin, entry_path, count(*) as cnt
+FROM sessions
+WHERE project_id = {p1:String}
+ AND sign = {p2:Int8}
+ AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}
+GROUP BY date, entry_origin, entry_path
+
+-- V2 params: {"p1": "openalternative", "p2": 1, "p3": "2026-07-28 00:00:00", "p4": "2026-08-24 23:59:59"}
+```
+
+**entry-pages — current-window total (`yesterday`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 270245/270245; wall V1/V2 = 15 ms / 13 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59') as cur_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-07-28 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total
+FROM sessions
+WHERE project_id = {p3:String}
+ AND sign = {p4:Int8}
+ AND created_at BETWEEN {p5:DateTime64(3)} AND {p6:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-25 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "openalternative", "p4": 1, "p5": "2026-07-28 00:00:00", "p6": "2026-08-25 23:59:59"}
+```
+
+**entry-pages — current + baseline countIf, grouped (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 5724/5724; rows_read V1/V2 = 131025/131025; wall V1/V2 = 38 ms / 28 ms; `meta` V1/V2 (identical) = `[{"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT entry_origin, entry_path, countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59' GROUP BY entry_origin, entry_path
+
+-- V2
+SELECT entry_origin, entry_path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY entry_origin, entry_path
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**entry-pages — current + baseline totals (`rolling_7d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 131025/131025; wall V1/V2 = 10 ms / 8 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-08-19 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-18 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-12 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-08-19 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-08-12 00:00:00", "p4": "2026-08-18 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-08-12 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**entry-pages — current + baseline countIf, grouped (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 11423/11423; rows_read V1/V2 = 311191/311191; wall V1/V2 = 41 ms / 46 ms; `meta` V1/V2 (identical) = `[{"name": "entry_origin", "type": "LowCardinality(String)"}, {"name": "entry_path", "type": "String"}, {"name": "cur", "type": "UInt64"}, {"name": "base", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT entry_origin, entry_path, countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59' GROUP BY entry_origin, entry_path
+
+-- V2
+SELECT entry_origin, entry_path, countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+GROUP BY entry_origin, entry_path
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+**entry-pages — current + baseline totals (`rolling_30d`)** — IDENTICAL; rows V1/V2 = 1/1; rows_read V1/V2 = 311191/311191; wall V1/V2 = 14 ms / 9 ms; `meta` V1/V2 (identical) = `[{"name": "cur_total", "type": "UInt64"}, {"name": "base_total", "type": "UInt64"}]`; clickhouse_settings: session_timezone=UTC (both).
+
+```sql
+-- V1
+SELECT countIf(created_at BETWEEN '2026-07-27 00:00:00' AND '2026-08-25 23:59:59') as cur_total, countIf(created_at BETWEEN '2026-06-27 00:00:00' AND '2026-07-26 23:59:59') as base_total FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-06-27 00:00:00' AND '2026-08-25 23:59:59'
+
+-- V2
+SELECT countIf(created_at BETWEEN {p1:DateTime64(3)} AND {p2:DateTime64(3)}) as cur_total, countIf(created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)}) as base_total
+FROM sessions
+WHERE project_id = {p5:String}
+ AND sign = {p6:Int8}
+ AND created_at BETWEEN {p7:DateTime64(3)} AND {p8:DateTime64(3)}
+
+-- V2 params: {"p1": "2026-07-27 00:00:00", "p2": "2026-08-25 23:59:59", "p3": "2026-06-27 00:00:00", "p4": "2026-07-26 23:59:59", "p5": "openalternative", "p6": 1, "p7": "2026-06-27 00:00:00", "p8": "2026-08-25 23:59:59"}
+```
+
+## Reproducing any case
+
+V1 is the literal text above; V2 is the text plus `param_pN=` values:
+
+```bash
+# V1 (devices / current window, grouped)
+curl -s -G 'http://127.0.0.1:8123/' \
+ --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \
+ --data-urlencode 'default_format=JSONCompact' \
+ --data-urlencode "query=SELECT device, count(*) as cnt FROM sessions WHERE project_id = 'openalternative' AND sign = 1 AND created_at BETWEEN '2026-08-25 00:00:00' AND '2026-08-25 23:59:59' GROUP BY device"
+
+# V2
+curl -s -G 'http://127.0.0.1:8123/' \
+ --data-urlencode 'database=openpanel' --data-urlencode 'session_timezone=UTC' \
+ --data-urlencode 'default_format=JSONCompact' \
+ --data-urlencode 'param_p1=openalternative' \
+ --data-urlencode 'param_p2=1' \
+ --data-urlencode 'param_p3=2026-08-25 00:00:00' \
+ --data-urlencode 'param_p4=2026-08-25 23:59:59' \
+ --data-urlencode 'query=SELECT device, count(*) as cnt FROM sessions WHERE project_id = {p1:String} AND sign = {p2:Int8} AND created_at BETWEEN {p3:DateTime64(3)} AND {p4:DateTime64(3)} GROUP BY device'
+```
+
+Both return the same three rows.
+
+## Conversion notes
+
+- **`DateTime64(3)`, not `String`.** `created_at` is `DateTime64(3)` and V1
+ compared it against a quoted literal, which ClickHouse converts to that type.
+ Measured 2026-09-07 on this box: `{p:DateTime}`, `{p:DateTime64(3)}` and
+ `{p:String}` all return the identical count, but only `DateTime64(3)`
+ reproduces V1's `rows_read` exactly (163,730 for `{p:String}` vs 212,831 for
+ the literal on a probe query), i.e. only it keeps the same index analysis.
+- **The date strings are unchanged.** clix's `escapeDate` ran
+ `sqlstring.escape(clix.datetime(d))` = `toISOString().slice(0,19)`, and
+ `formatClickhouseDate` produces the same string for the same input — including
+ the truncation of `getEndOfDay`'s `.999` milliseconds to `23:59:59`. The
+ `countIf(...)` expressions already used `formatClickhouseDate` in V1 (they
+ went through `clix.exp`, which bypasses `escapeDate`), so both sides of every
+ window boundary agree byte-for-byte.
+- **`sign = 1` and `name = 'screen_view'` are now bound**, as `{pN:Int8}` and
+ `{pN:String}`. Both were *values* handed to `clix.where(...)` in V1, so they
+ bind under the mechanical rule; the emitted comparison is unchanged.
+- **`escapeDate`'s date-substring rewrite (recipe trap 1) is not reachable
+ here.** The only strings V1 escaped were the project id and the window
+ boundaries; no `SELECT` expression or column name in these five modules
+ contains a date-shaped substring, so nothing relied on the implicit re-quoting
+ and no V2 text had to add a quote back. The proof's 35 identical texts are the
+ evidence.
+- **Bound through the real driver too, not only over HTTP.** The 35 cases above
+ were executed over ClickHouse's HTTP interface (`param_pN=`), which is what
+ makes them reproducible with `curl`. As a separate check on 2026-09-07,
+ `devicesModule.enumerateDimensions` was run once with `ctx.runQuery` wired to a
+ real `@clickhouse/client` `query({query, query_params, …})` against local
+ prod-copy `openpanel`; it returned
+ `["device:mobile", "device:desktop", "device:tablet", "device:smarttv"]`, so
+ the `{pN:DateTime64(3)}` / `{pN:Int8}` / `{pN:String}` bindings survive the
+ driver's own parameter serialization, not just the query string.
+- **`session_timezone` is pinned, not dropped** (recipe trap 3): the new wrapper
+ defaults to `'UTC'` and sends it on every statement, exactly as
+ `clix(client, undefined)` did.
diff --git a/packages/core/src/modules/insight/src/modules/devices.module.ts b/packages/core/src/modules/insight/src/modules/devices.module.ts
index 2246bab94..14b3b817c 100644
--- a/packages/core/src/modules/insight/src/modules/devices.module.ts
+++ b/packages/core/src/modules/insight/src/modules/devices.module.ts
@@ -1,3 +1,4 @@
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import { formatClickhouseDate } from '../../../../shared/ch-dates';
import { TABLE_NAMES } from '../../../../shared/ch-tables';
import type {
@@ -16,57 +17,54 @@ import {
selectTopDimensions,
} from '../utils';
+/** clix inlined the value; `sign = 1` is the sessions table's live-row
+ * predicate and now binds like every other value. */
+const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);
+
async function fetchDeviceAggregates(ctx: ComputeContext): Promise<{
currentMap: Map<string, number>;
baselineMap: Map<string, number>;
totalCurrent: number;
totalBaseline: number;
}> {
+ const sessions = sql.id(TABLE_NAMES.sessions);
+ const projectId = sql.string(ctx.projectId);
+ const curStart = sql.dateTime64(formatClickhouseDate(ctx.window.start));
+ const curEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.end))
+ );
+ const baseStart = sql.dateTime64(
+ formatClickhouseDate(ctx.window.baselineStart)
+ );
+ const baseEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd))
+ );
+
if (ctx.window.kind === 'yesterday') {
const [currentResults, baselineResults, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ device: string; cnt: number }>(['device', 'count(*) as cnt'])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.start,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['device'])
- .execute(),
- ctx
- .clix()
- .select<{ date: string; device: string; cnt: number }>([
- 'toDate(created_at) as date',
- 'device',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.baselineEnd),
- ])
- .groupBy(['date', 'device'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{ device: string; cnt: number }>(sql`
+ SELECT device, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${curStart} AND ${curEnd}
+ GROUP BY device
+ `),
+ ctx.runQuery<{ date: string; device: string; cnt: number }>(sql`
+ SELECT toDate(created_at) as date, device, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${baseEnd}
+ GROUP BY date, device
+ `),
+ ctx.runQuery<{ cur_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(currentResults, (r) => r.device);
@@ -107,50 +105,22 @@ async function fetchDeviceAggregates(ctx: ComputeContext): Promise<{
return { currentMap, baselineMap, totalCurrent, totalBaseline };
}
- const curStart = formatClickhouseDate(ctx.window.start);
- const curEnd = formatClickhouseDate(getEndOfDay(ctx.window.end));
- const baseStart = formatClickhouseDate(ctx.window.baselineStart);
- const baseEnd = formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd));
-
const [results, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ device: string; cur: number; base: number }>([
- 'device',
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['device'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number; base_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{ device: string; cur: number; base: number }>(sql`
+ SELECT device, countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ GROUP BY device
+ `),
+ ctx.runQuery<{ cur_total: number; base_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
diff --git a/packages/core/src/modules/insight/src/modules/entry-pages.module.ts b/packages/core/src/modules/insight/src/modules/entry-pages.module.ts
index 3508e3af0..3a3eb126f 100644
--- a/packages/core/src/modules/insight/src/modules/entry-pages.module.ts
+++ b/packages/core/src/modules/insight/src/modules/entry-pages.module.ts
@@ -1,3 +1,4 @@
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import { formatClickhouseDate } from '../../../../shared/ch-dates';
import { TABLE_NAMES } from '../../../../shared/ch-tables';
import type {
@@ -18,67 +19,63 @@ import {
const DELIMITER = '|||';
+/** clix inlined the value; `sign = 1` is the sessions table's live-row
+ * predicate and now binds like every other value. */
+const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);
+
async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{
currentMap: Map<string, number>;
baselineMap: Map<string, number>;
totalCurrent: number;
totalBaseline: number;
}> {
+ const sessions = sql.id(TABLE_NAMES.sessions);
+ const projectId = sql.string(ctx.projectId);
+ const curStart = sql.dateTime64(formatClickhouseDate(ctx.window.start));
+ const curEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.end))
+ );
+ const baseStart = sql.dateTime64(
+ formatClickhouseDate(ctx.window.baselineStart)
+ );
+ const baseEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd))
+ );
+
if (ctx.window.kind === 'yesterday') {
const [currentResults, baselineResults, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ entry_origin: string; entry_path: string; cnt: number }>([
- 'entry_origin',
- 'entry_path',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.start,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['entry_origin', 'entry_path'])
- .execute(),
- ctx
- .clix()
- .select<{
- date: string;
- entry_origin: string;
- entry_path: string;
- cnt: number;
- }>([
- 'toDate(created_at) as date',
- 'entry_origin',
- 'entry_path',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.baselineEnd),
- ])
- .groupBy(['date', 'entry_origin', 'entry_path'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{
+ entry_origin: string;
+ entry_path: string;
+ cnt: number;
+ }>(sql`
+ SELECT entry_origin, entry_path, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${curStart} AND ${curEnd}
+ GROUP BY entry_origin, entry_path
+ `),
+ ctx.runQuery<{
+ date: string;
+ entry_origin: string;
+ entry_path: string;
+ cnt: number;
+ }>(sql`
+ SELECT toDate(created_at) as date, entry_origin, entry_path, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${baseEnd}
+ GROUP BY date, entry_origin, entry_path
+ `),
+ ctx.runQuery<{ cur_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
@@ -102,56 +99,27 @@ async function fetchEntryPageAggregates(ctx: ComputeContext): Promise<{
return { currentMap, baselineMap, totalCurrent, totalBaseline };
}
- const curStart = formatClickhouseDate(ctx.window.start);
- const curEnd = formatClickhouseDate(getEndOfDay(ctx.window.end));
- const baseStart = formatClickhouseDate(ctx.window.baselineStart);
- const baseEnd = formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd));
-
const [results, totals] = await Promise.all([
- ctx
- .clix()
- .select<{
- entry_origin: string;
- entry_path: string;
- cur: number;
- base: number;
- }>([
- 'entry_origin',
- 'entry_path',
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['entry_origin', 'entry_path'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number; base_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{
+ entry_origin: string;
+ entry_path: string;
+ cur: number;
+ base: number;
+ }>(sql`
+ SELECT entry_origin, entry_path, countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ GROUP BY entry_origin, entry_path
+ `),
+ ctx.runQuery<{ cur_total: number; base_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
diff --git a/packages/core/src/modules/insight/src/modules/geo.module.ts b/packages/core/src/modules/insight/src/modules/geo.module.ts
index 8ab61ea6a..adcba4726 100644
--- a/packages/core/src/modules/insight/src/modules/geo.module.ts
+++ b/packages/core/src/modules/insight/src/modules/geo.module.ts
@@ -1,3 +1,4 @@
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import { formatClickhouseDate } from '../../../../shared/ch-dates';
import { TABLE_NAMES } from '../../../../shared/ch-tables';
import { getCountry } from '../../../report/report.constants';
@@ -17,60 +18,54 @@ import {
selectTopDimensions,
} from '../utils';
+/** clix inlined the value; `sign = 1` is the sessions table's live-row
+ * predicate and now binds like every other value. */
+const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);
+
async function fetchGeoAggregates(ctx: ComputeContext): Promise<{
currentMap: Map<string, number>;
baselineMap: Map<string, number>;
totalCurrent: number;
totalBaseline: number;
}> {
+ const sessions = sql.id(TABLE_NAMES.sessions);
+ const projectId = sql.string(ctx.projectId);
+ const curStart = sql.dateTime64(formatClickhouseDate(ctx.window.start));
+ const curEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.end))
+ );
+ const baseStart = sql.dateTime64(
+ formatClickhouseDate(ctx.window.baselineStart)
+ );
+ const baseEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd))
+ );
+
if (ctx.window.kind === 'yesterday') {
const [currentResults, baselineResults, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ country: string; cnt: number }>([
- 'country',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.start,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['country'])
- .execute(),
- ctx
- .clix()
- .select<{ date: string; country: string; cnt: number }>([
- 'toDate(created_at) as date',
- 'country',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.baselineEnd),
- ])
- .groupBy(['date', 'country'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{ country: string; cnt: number }>(sql`
+ SELECT country, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${curStart} AND ${curEnd}
+ GROUP BY country
+ `),
+ ctx.runQuery<{ date: string; country: string; cnt: number }>(sql`
+ SELECT toDate(created_at) as date, country, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${baseEnd}
+ GROUP BY date, country
+ `),
+ ctx.runQuery<{ cur_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
@@ -94,50 +89,22 @@ async function fetchGeoAggregates(ctx: ComputeContext): Promise<{
return { currentMap, baselineMap, totalCurrent, totalBaseline };
}
- const curStart = formatClickhouseDate(ctx.window.start);
- const curEnd = formatClickhouseDate(getEndOfDay(ctx.window.end));
- const baseStart = formatClickhouseDate(ctx.window.baselineStart);
- const baseEnd = formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd));
-
const [results, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ country: string; cur: number; base: number }>([
- 'country',
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['country'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number; base_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{ country: string; cur: number; base: number }>(sql`
+ SELECT country, countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ GROUP BY country
+ `),
+ ctx.runQuery<{ cur_total: number; base_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
diff --git a/packages/core/src/modules/insight/src/modules/page-trends.module.ts b/packages/core/src/modules/insight/src/modules/page-trends.module.ts
index 4b95edf7e..dd7ac4e9d 100644
--- a/packages/core/src/modules/insight/src/modules/page-trends.module.ts
+++ b/packages/core/src/modules/insight/src/modules/page-trends.module.ts
@@ -1,3 +1,4 @@
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import { formatClickhouseDate } from '../../../../shared/ch-dates';
import { TABLE_NAMES } from '../../../../shared/ch-tables';
import type {
@@ -18,62 +19,58 @@ import {
const DELIMITER = '|||';
+/** clix inlined the value; the pageview event name now binds. */
+const SCREEN_VIEW_EVENT = sql.string('screen_view');
+
async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{
currentMap: Map<string, number>;
baselineMap: Map<string, number>;
totalCurrent: number;
totalBaseline: number;
}> {
+ const events = sql.id(TABLE_NAMES.events);
+ const projectId = sql.string(ctx.projectId);
+ const curStart = sql.dateTime64(formatClickhouseDate(ctx.window.start));
+ const curEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.end))
+ );
+ const baseStart = sql.dateTime64(
+ formatClickhouseDate(ctx.window.baselineStart)
+ );
+ const baseEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd))
+ );
+
if (ctx.window.kind === 'yesterday') {
const [currentResults, baselineResults, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ origin: string; path: string; cnt: number }>([
- 'origin',
- 'path',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', ctx.projectId)
- .where('name', '=', 'screen_view')
- .where('created_at', 'BETWEEN', [
- ctx.window.start,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['origin', 'path'])
- .execute(),
- ctx
- .clix()
- .select<{ date: string; origin: string; path: string; cnt: number }>([
- 'toDate(created_at) as date',
- 'origin',
- 'path',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', ctx.projectId)
- .where('name', '=', 'screen_view')
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.baselineEnd),
- ])
- .groupBy(['date', 'origin', 'path'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
- ),
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', ctx.projectId)
- .where('name', '=', 'screen_view')
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{ origin: string; path: string; cnt: number }>(sql`
+ SELECT origin, path, count(*) as cnt
+ FROM ${events}
+ WHERE project_id = ${projectId}
+ AND name = ${SCREEN_VIEW_EVENT}
+ AND created_at BETWEEN ${curStart} AND ${curEnd}
+ GROUP BY origin, path
+ `),
+ ctx.runQuery<{
+ date: string;
+ origin: string;
+ path: string;
+ cnt: number;
+ }>(sql`
+ SELECT toDate(created_at) as date, origin, path, count(*) as cnt
+ FROM ${events}
+ WHERE project_id = ${projectId}
+ AND name = ${SCREEN_VIEW_EVENT}
+ AND created_at BETWEEN ${baseStart} AND ${baseEnd}
+ GROUP BY date, origin, path
+ `),
+ ctx.runQuery<{ cur_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total
+ FROM ${events}
+ WHERE project_id = ${projectId}
+ AND name = ${SCREEN_VIEW_EVENT}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
@@ -97,51 +94,27 @@ async function fetchPageTrendAggregates(ctx: ComputeContext): Promise<{
return { currentMap, baselineMap, totalCurrent, totalBaseline };
}
- const curStart = formatClickhouseDate(ctx.window.start);
- const curEnd = formatClickhouseDate(getEndOfDay(ctx.window.end));
- const baseStart = formatClickhouseDate(ctx.window.baselineStart);
- const baseEnd = formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd));
-
const [results, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ origin: string; path: string; cur: number; base: number }>([
- 'origin',
- 'path',
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
- ),
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', ctx.projectId)
- .where('name', '=', 'screen_view')
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['origin', 'path'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number; base_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
- ),
- ])
- .from(TABLE_NAMES.events)
- .where('project_id', '=', ctx.projectId)
- .where('name', '=', 'screen_view')
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{
+ origin: string;
+ path: string;
+ cur: number;
+ base: number;
+ }>(sql`
+ SELECT origin, path, countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base
+ FROM ${events}
+ WHERE project_id = ${projectId}
+ AND name = ${SCREEN_VIEW_EVENT}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ GROUP BY origin, path
+ `),
+ ctx.runQuery<{ cur_total: number; base_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base_total
+ FROM ${events}
+ WHERE project_id = ${projectId}
+ AND name = ${SCREEN_VIEW_EVENT}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
diff --git a/packages/core/src/modules/insight/src/modules/referrers.module.ts b/packages/core/src/modules/insight/src/modules/referrers.module.ts
index c7647af55..c5ab9ae71 100644
--- a/packages/core/src/modules/insight/src/modules/referrers.module.ts
+++ b/packages/core/src/modules/insight/src/modules/referrers.module.ts
@@ -1,3 +1,4 @@
+import { sql } from '@openpanel/db/src/clickhouse/sql';
import { formatClickhouseDate } from '../../../../shared/ch-dates';
import { TABLE_NAMES } from '../../../../shared/ch-tables';
import type {
@@ -16,60 +17,54 @@ import {
selectTopDimensions,
} from '../utils';
+/** clix inlined the value; `sign = 1` is the sessions table's live-row
+ * predicate and now binds like every other value. */
+const ACTIVE_SESSION_SIGN = sql.param('Int8', 1);
+
async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{
currentMap: Map<string, number>;
baselineMap: Map<string, number>;
totalCurrent: number;
totalBaseline: number;
}> {
+ const sessions = sql.id(TABLE_NAMES.sessions);
+ const projectId = sql.string(ctx.projectId);
+ const curStart = sql.dateTime64(formatClickhouseDate(ctx.window.start));
+ const curEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.end))
+ );
+ const baseStart = sql.dateTime64(
+ formatClickhouseDate(ctx.window.baselineStart)
+ );
+ const baseEnd = sql.dateTime64(
+ formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd))
+ );
+
if (ctx.window.kind === 'yesterday') {
const [currentResults, baselineResults, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ referrer_name: string; cnt: number }>([
- 'referrer_name',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.start,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['referrer_name'])
- .execute(),
- ctx
- .clix()
- .select<{ date: string; referrer_name: string; cnt: number }>([
- 'toDate(created_at) as date',
- 'referrer_name',
- 'count(*) as cnt',
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.baselineEnd),
- ])
- .groupBy(['date', 'referrer_name'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${formatClickhouseDate(ctx.window.start)}' AND '${formatClickhouseDate(getEndOfDay(ctx.window.end))}') as cur_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{ referrer_name: string; cnt: number }>(sql`
+ SELECT referrer_name, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${curStart} AND ${curEnd}
+ GROUP BY referrer_name
+ `),
+ ctx.runQuery<{ date: string; referrer_name: string; cnt: number }>(sql`
+ SELECT toDate(created_at) as date, referrer_name, count(*) as cnt
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${baseEnd}
+ GROUP BY date, referrer_name
+ `),
+ ctx.runQuery<{ cur_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
@@ -93,50 +88,22 @@ async function fetchReferrerAggregates(ctx: ComputeContext): Promise<{
return { currentMap, baselineMap, totalCurrent, totalBaseline };
}
- const curStart = formatClickhouseDate(ctx.window.start);
- const curEnd = formatClickhouseDate(getEndOfDay(ctx.window.end));
- const baseStart = formatClickhouseDate(ctx.window.baselineStart);
- const baseEnd = formatClickhouseDate(getEndOfDay(ctx.window.baselineEnd));
-
const [results, totals] = await Promise.all([
- ctx
- .clix()
- .select<{ referrer_name: string; cur: number; base: number }>([
- 'referrer_name',
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .groupBy(['referrer_name'])
- .execute(),
- ctx
- .clix()
- .select<{ cur_total: number; base_total: number }>([
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${curStart}' AND '${curEnd}') as cur_total`
- ),
- ctx.clix.exp(
- `countIf(created_at BETWEEN '${baseStart}' AND '${baseEnd}') as base_total`
- ),
- ])
- .from(TABLE_NAMES.sessions)
- .where('project_id', '=', ctx.projectId)
- .where('sign', '=', 1)
- .where('created_at', 'BETWEEN', [
- ctx.window.baselineStart,
- getEndOfDay(ctx.window.end),
- ])
- .execute(),
+ ctx.runQuery<{ referrer_name: string; cur: number; base: number }>(sql`
+ SELECT referrer_name, countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ GROUP BY referrer_name
+ `),
+ ctx.runQuery<{ cur_total: number; base_total: number }>(sql`
+ SELECT countIf(created_at BETWEEN ${curStart} AND ${curEnd}) as cur_total, countIf(created_at BETWEEN ${baseStart} AND ${baseEnd}) as base_total
+ FROM ${sessions}
+ WHERE project_id = ${projectId}
+ AND sign = ${ACTIVE_SESSION_SIGN}
+ AND created_at BETWEEN ${baseStart} AND ${curEnd}
+ `),
]);
const currentMap = buildLookupMap(
diff --git a/packages/core/src/modules/insight/src/types.ts b/packages/core/src/modules/insight/src/types.ts
index 8028bbeca..ae863c67e 100644
--- a/packages/core/src/modules/insight/src/types.ts
+++ b/packages/core/src/modules/insight/src/types.ts
@@ -1,4 +1,5 @@
import type { InsightPayload } from '../insight.constants';
+import type { StatementRunner } from './cached-query';
export type Cadence = 'daily';
@@ -16,15 +17,14 @@ export interface WindowRange {
export interface ComputeContext {
projectId: string;
window: WindowRange;
- db: any; // your DB client
now: Date;
logger: Pick<Console, 'info' | 'warn' | 'error'>;
/**
- * Cached clix function that automatically caches query results based on query hash.
- * This eliminates duplicate queries within the same module+window context.
- * Use this instead of importing clix directly to benefit from automatic caching.
+ * Runs a bound `SqlStatement`, memoised on the rendered text PLUS its params
+ * within this module+window context. Modules read ClickHouse only through
+ * this — it is the only handle they get.
*/
- clix: ReturnType<typeof import('./cached-clix').createCachedClix>;
+ runQuery: StatementRunner;
}
export interface ComputeResult {