fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
@@ -0,0 +1,433 @@
/**
* tests/integration/analyst-sql-clickhouse.integration.test.ts
* =============================================================
* BI-P017 — the proof that matters: the bypass corpus run against a LIVE
* ClickHouse **with the statement guard removed**.
*
* The guard (layer 2) is a text analysis of a dialect it does not implement.
* Testing only the guard proves the guard. What has to hold is that when the
* guard is WRONG, nothing leaks — so this file skips the guard entirely and
* sends each attack straight to the engine as the tenant's restricted user.
* Layer 3 (grants + `readonly = 1`) and layer 4 (views that bake the tenant
* predicate, over base tables carrying a row policy) must refuse it anyway.
*
* The assertion is deliberately NOT "the engine returned an error". It is
* "no foreign row came back", checked by canary values seeded into the other
* tenant's rows and into an ungranted table. An attack that succeeds and
* returns nothing interesting still fails the test if it returns a canary.
*
* Counterfactual, run first, because a test that would pass against an empty
* database proves nothing: as the ADMIN user the base table holds both
* tenants' rows, and `BETA_CANARY` IS readable. Every later assertion is
* therefore about isolation, not about absence of data.
*
* ── HOW THIS AVOIDS THE SILENT-SKIP TRAP ──────────────────────────────────
* l0re's 28 Postgres tests skipped silently for months and nobody noticed.
* This suite self-skips when ClickHouse is unreachable — but on a live run it
* WRITES `evidence/bi-p017/analyst-sql-live-bypass.json`, and
* tests/analytics/analyst-sql-evidence.test.ts (which never skips) fails if
* that file is missing, stale, or does not cover every attempt in the corpus.
* Adding an attack without re-running this suite breaks the build.
*
* Point it at a disposable instance:
* docker run -d --name ch -p 28123:8123 -e CLICKHOUSE_SKIP_USER_SETUP=1 \
* clickhouse/clickhouse-server:24.8
* ANALYTICS_CLICKHOUSE_URL=http://127.0.0.1:28123 pnpm vitest run \
* tests/integration/analyst-sql-clickhouse.integration.test.ts
*/
import fs from 'node:fs';
import path from 'node:path';
import { beforeAll, describe, expect, it } from 'vitest';
import {
BYPASS_CORPUS,
GUARD_ADMITS_ENGINE_REFUSES,
LEGITIMATE_CORPUS,
} from '../analytics/analyst-sql-bypass-corpus';
import { guardAnalystStatement } from '@/src/analytics/sql/statement-guard';
import {
rowPolicyVerificationSql,
tenantSqlCatalogDdl,
tenantSqlUserDdl,
} from '@/src/analytics/sql/tenant-catalog';
import { applyQuota, DEFAULT_BUDGETS } from '@/src/analytics/engine/resource-governance';
/**
* Gated on the ENV VAR, matching the convention already in
* tests/integration/analytics-tenant-isolation.integration.test.ts — and
* chosen over a liveness probe on purpose: with the variable set, a
* ClickHouse that is down makes this suite FAIL. A probe would have turned a
* broken server into a silent green, which is the failure mode this estate
* keeps shipping.
*/
const BASE_URL = process.env.CLICKHOUSE_URL ?? '';
const ADMIN_AUTH = process.env.CLICKHOUSE_AUTH ?? 'default:';
const DB = 'opt_analytics';
const ALPHA_PW = 'alpha_test_pw_not_a_secret';
const BETA_PW = 'beta_test_pw_not_a_secret';
const EVIDENCE_PATH = path.join(process.cwd(), 'evidence/bi-p017/analyst-sql-live-bypass.json');
/** Canaries. Their presence in a response body is the definition of a leak. */
const BETA_CANARY = 'BETA_CANARY_9f21c4';
const SECRET_CANARY = 'SECRET_CANARY_4d80ab';
const ALPHA_MARK = 'ALPHA_ROW';
interface ChResponse {
ok: boolean;
status: number;
body: string;
}
async function run(sql: string, auth: string, settings: Record<string, string> = {}): Promise<ChResponse> {
const url = new URL(BASE_URL);
url.searchParams.set('query', sql);
for (const [k, v] of Object.entries(settings)) url.searchParams.set(k, v);
const res = await fetch(url.toString(), {
method: 'POST',
headers: { Authorization: `Basic ${Buffer.from(auth).toString('base64')}` },
body: '',
signal: AbortSignal.timeout(30_000),
});
return { ok: res.ok, status: res.status, body: await res.text() };
}
const admin = (sql: string) => run(sql, ADMIN_AUTH);
/**
* The session's real posture: the restricted user, and NO settings on the
* request.
*
* MEASURED: a user whose profile carries `readonly = 1` cannot have any
* setting changed from the request — ClickHouse answers `Code: 164. Cannot
* modify 'max_rows_to_read' setting in readonly mode.` So the BI-P012 ceilings
* cannot travel with the statement here the way they do for the non-readonly
* engine user; they are baked into the SETTINGS PROFILE by
* `tenantSqlUserDdl`, and the test below proves the profile enforces them.
*/
const asAlpha = (sql: string) => run(sql, `t_alpha_sql_user:${ALPHA_PW}`);
/**
* An earlier revision set a `reachable` flag inside `beforeAll` and used
* `describe.skipIf(!reachable)`. Vitest evaluates `skipIf` at COLLECTION time,
* before any hook runs, so the flag was always false and all ten tests skipped
* against a live, reachable ClickHouse — a suite that could never run,
* reporting green. Same shape as l0re's 28 silently-skipped Postgres tests.
* Recorded here because the next person will reach for `skipIf` too.
*/
const suite = BASE_URL ? describe : describe.skip;
let version = '';
/** The session budget for the main user: generous enough for real analyst work. */
const TEST_BUDGET = applyQuota(DEFAULT_BUDGETS.ANALYTICAL, {
maxRowsToRead: 100_000,
maxExecutionTimeSec: 10,
});
/**
* A SECOND user with a deliberately tiny `maxRowsToRead` (60), provisioned
* only to make the profile's enforcement observable: the tenant view holds 50
* rows, which passes; anything wider exceeds it and must fail with ClickHouse
* code 158. A ceiling nothing can breach proves nothing, and the first
* revision of this file proved exactly that by starving the legitimate corpus.
*/
const TINY_BUDGET = applyQuota(DEFAULT_BUDGETS.ANALYTICAL, { maxRowsToRead: 60, maxExecutionTimeSec: 10 });
const TINY_PW = 'tiny_test_pw_not_a_secret';
const OBJECTS = [
{ table: 'sales', columns: ['customer', 'amount', 'event_time'] },
{ table: 'events', columns: ['customer', 'kind', 'event_time'] },
];
beforeAll(async () => {
if (!BASE_URL) return;
// With CLICKHOUSE_URL set, an unreachable server FAILS here. It does not
// degrade to a skip.
const v = await admin('SELECT version()');
if (!v.ok)
throw new Error(
`CLICKHOUSE_URL is set but ClickHouse is not answering: ${v.status} ${v.body.slice(0, 200)}`,
);
version = v.body.trim();
await admin(`DROP DATABASE IF EXISTS ${DB}`);
await admin(`DROP DATABASE IF EXISTS t_alpha_sql`);
await admin(`DROP DATABASE IF EXISTS t_beta_sql`);
await admin(`DROP USER IF EXISTS t_alpha_sql_user`);
await admin(`DROP USER IF EXISTS t_beta_sql_user`);
await admin(`DROP USER IF EXISTS t_alpha_tiny_user`);
await admin(`CREATE DATABASE ${DB}`);
await admin(
`CREATE TABLE ${DB}.sales (tenant_id String, customer String, amount Float64, event_time DateTime) ` +
`ENGINE = MergeTree ORDER BY (tenant_id, event_time)`,
);
await admin(
`CREATE TABLE ${DB}.events (tenant_id String, customer String, kind String, event_time DateTime) ` +
`ENGINE = MergeTree ORDER BY (tenant_id, event_time)`,
);
await admin(
`CREATE TABLE ${DB}.secret_ledger (tenant_id String, note String) ENGINE = MergeTree ORDER BY tenant_id`,
);
// Also present, because several attacks name it: the BI-P010 event table.
await admin(
`CREATE TABLE ${DB}.opt_analytics_event (tenant_id String, project_id String, dataset_id String, ` +
`event_id String, metric String, value Float64, event_time DateTime) ENGINE = MergeTree ` +
`ORDER BY (tenant_id, event_time)`,
);
await admin(
`INSERT INTO ${DB}.sales SELECT 't_alpha', '${ALPHA_MARK}_' || toString(number), number, now() FROM numbers(50)`,
);
await admin(
`INSERT INTO ${DB}.sales SELECT 't_beta', '${BETA_CANARY}_' || toString(number), number, now() FROM numbers(50)`,
);
await admin(
`INSERT INTO ${DB}.events SELECT 't_alpha', '${ALPHA_MARK}_' || toString(number), 'click', now() FROM numbers(20)`,
);
await admin(
`INSERT INTO ${DB}.events SELECT 't_beta', '${BETA_CANARY}_' || toString(number), 'click', now() FROM numbers(20)`,
);
await admin(`INSERT INTO ${DB}.secret_ledger VALUES ('t_alpha', '${SECRET_CANARY}')`);
await admin(
`INSERT INTO ${DB}.opt_analytics_event SELECT 't_beta', 'p', 'd', toString(number), 'm', number, now() FROM numbers(10)`,
);
for (const [tenant, catalog, user, pw] of [
['t_alpha', 't_alpha_sql', 't_alpha_sql_user', ALPHA_PW],
['t_beta', 't_beta_sql', 't_beta_sql_user', BETA_PW],
] as const) {
const spec = { sourceDatabase: DB, tenantId: tenant, catalog, objects: OBJECTS };
for (const stmt of tenantSqlCatalogDdl(spec)) {
const r = await admin(stmt);
if (!r.ok) throw new Error(`catalog DDL failed: ${stmt} -> ${r.body.slice(0, 200)}`);
}
for (const stmt of tenantSqlUserDdl({ ...spec, userName: user, password: pw, budget: TEST_BUDGET })) {
const r = await admin(stmt);
if (!r.ok) throw new Error(`user DDL failed: ${stmt} -> ${r.body.slice(0, 200)}`);
}
}
const tinySpec = { sourceDatabase: DB, tenantId: 't_alpha', catalog: 't_alpha_sql', objects: OBJECTS };
for (const stmt of tenantSqlUserDdl({
...tinySpec,
userName: 't_alpha_tiny_user',
password: TINY_PW,
budget: TINY_BUDGET,
})) {
const r = await admin(stmt);
if (!r.ok) throw new Error(`tiny user DDL failed: ${stmt} -> ${r.body.slice(0, 200)}`);
}
}, 120_000);
suite('BI-P017 live — counterfactual: the data IS there and IS reachable without the layers', () => {
it('the shared base table holds both tenants, and BETA_CANARY is readable as admin', async () => {
const all = await admin(`SELECT count() FROM ${DB}.sales`);
expect(all.ok).toBe(true);
expect(Number(all.body.trim())).toBe(100);
const beta = await admin(`SELECT customer FROM ${DB}.sales WHERE tenant_id = 't_beta' LIMIT 1`);
expect(beta.body).toContain(BETA_CANARY);
const secret = await admin(`SELECT note FROM ${DB}.secret_ledger`);
expect(secret.body).toContain(SECRET_CANARY);
});
it('layer 4: the tenant view returns 50 of the 100 rows, and never the canary', async () => {
const scoped = await asAlpha(`SELECT count() FROM t_alpha_sql.sales`);
expect(scoped.ok).toBe(true);
expect(Number(scoped.body.trim())).toBe(50);
const rows = await asAlpha(`SELECT customer FROM t_alpha_sql.sales LIMIT 100`);
expect(rows.body).toContain(ALPHA_MARK);
expect(rows.body).not.toContain(BETA_CANARY);
});
});
suite('BI-P017 live — the bypass corpus WITH THE GUARD REMOVED', () => {
it('no attempt returns a foreign-tenant or ungranted-table row', async () => {
const results: Array<Record<string, unknown>> = [];
const leaks: string[] = [];
for (const attempt of [...BYPASS_CORPUS, ...GUARD_ADMITS_ENGINE_REFUSES]) {
// THE GUARD IS NOT CALLED HERE. That is the whole point.
const res = await asAlpha(attempt.sql);
const leakedBeta = res.body.includes(BETA_CANARY);
const leakedSecret = res.body.includes(SECRET_CANARY);
const chCode = /Code:\s*(\d+)/.exec(res.body)?.[1];
// MEASURED, and narrower than the obvious rule. ClickHouse filters
// `system.tables` / `system.columns` by the caller's own grants: as
// the restricted user those reads SUCCEED but return only this
// tenant's four objects — 4 rows, not the server's inventory.
// `system.query_log`, `system.processes` and `system.users` are
// ACCESS_DENIED (code 497). So "any successful system read is a leak"
// would be a false alarm; the real test is whether any FOREIGN name
// came back.
const leakedMetadata = res.ok && /\bt_beta\b|secret_ledger/.test(res.body);
if (leakedBeta || leakedSecret || leakedMetadata) {
leaks.push(`${attempt.id}: ${attempt.goal}`);
}
// For completeness the guard's own verdict is recorded alongside, so
// the evidence shows which layer caught what.
let guardVerdict = 'admitted';
try {
guardAnalystStatement(attempt.sql, {
allowedCatalog: 't_alpha_sql',
allowedObjects: ['sales', 'events'],
});
} catch (e) {
guardVerdict = `refused: ${(e as Error).message}`;
}
results.push({
id: attempt.id,
goal: attempt.goal,
engine_http_status: res.status,
engine_clickhouse_code: chCode ?? null,
engine_succeeded: res.ok,
leaked_foreign_tenant_row: leakedBeta,
leaked_ungranted_table_row: leakedSecret,
leaked_server_metadata: leakedMetadata,
guard_verdict_for_reference: guardVerdict,
engine_response_head: res.body.slice(0, 160).replace(/\s+/g, ' ').trim(),
});
}
// Legitimate work must still WORK as the restricted user, or "nothing
// leaked" would be trivially true because nothing runs.
const legitimate: Array<Record<string, unknown>> = [];
for (const l of LEGITIMATE_CORPUS) {
const res = await asAlpha(l.sql);
legitimate.push({
id: l.id,
ok: res.ok,
status: res.status,
contains_beta_canary: res.body.includes(BETA_CANARY),
});
}
fs.mkdirSync(path.dirname(EVIDENCE_PATH), { recursive: true });
fs.writeFileSync(
EVIDENCE_PATH,
`${JSON.stringify(
{
prompt: 'BI-P017',
claim:
"Every bypass attempt, executed directly against a live ClickHouse as the tenant's " +
'restricted user WITH THE STATEMENT GUARD REMOVED, fails to return a foreign-tenant ' +
'row, an ungranted-table row, or server metadata.',
clickhouse_version: version,
recorded_at: new Date().toISOString(),
base_table_rows_both_tenants: 100,
tenant_view_rows_alpha: 50,
attempts_total: results.length,
attempts_that_leaked: leaks.length,
legitimate_statements_that_succeeded: legitimate.filter((l) => l.ok).length,
legitimate_statements_total: legitimate.length,
attempts: results,
legitimate,
},
null,
2,
)}\n`,
);
expect(leaks, `LEAKS with the guard removed:\n${leaks.join('\n')}`).toEqual([]);
expect(legitimate.every((l) => l.ok)).toBe(true);
expect(legitimate.every((l) => l.contains_beta_canary === false)).toBe(true);
}, 300_000);
});
suite('BI-P017 live — layers 3 and 4 individually, each with the one above removed', () => {
it('the row policies are actually APPLIED TO THE USER, not merely present', async () => {
// The check that caught the real bug. `SHOW ROW POLICIES` listing a policy
// with the right filter is not evidence: after a user is dropped and
// re-created, `CREATE ROW POLICY IF NOT EXISTS` leaves the policy in place
// with an EMPTY apply-to list, protecting nobody while looking correct.
const res = await admin(
rowPolicyVerificationSql({
sourceDatabase: DB,
tenantId: 't_alpha',
catalog: 't_alpha_sql',
objects: OBJECTS,
userName: 't_alpha_sql_user',
password: 'unused',
}),
);
expect(res.ok).toBe(true);
const rows = JSON.parse(res.body).data as Array<{ table: string; applied_to_user: number }>;
expect(rows.length).toBe(OBJECTS.length);
for (const row of rows) {
expect(row.applied_to_user, `row policy on ${row.table} applies to nobody`).toBe(1);
}
});
it('layer 3 (row policy): the restricted user reading the SHARED BASE TABLE sees only its own rows', async () => {
// The counterfactual is in the suite above: as admin this same statement
// returns 100. Returning 100 here would be a cross-tenant read.
const res = await asAlpha(`SELECT count() FROM ${DB}.sales`);
if (res.ok) {
expect(Number(res.body.trim()), 'restricted user read BOTH tenants from the base table').toBe(50);
} else {
expect(res.status).toBeGreaterThanOrEqual(400);
}
});
it('layer 3 (row policy): the base table yields no foreign canary even when named directly', async () => {
const res = await asAlpha(`SELECT customer FROM ${DB}.sales LIMIT 1000`);
expect(res.body).not.toContain(BETA_CANARY);
});
it('BI-P012 ceilings are enforced by the SETTINGS PROFILE, not by the request', async () => {
const tiny = (sql: string) => run(sql, `t_alpha_tiny_user:${TINY_PW}`);
// Under the ceiling: succeeds.
const ok = await tiny(`SELECT count() FROM t_alpha_sql.sales`);
expect(ok.ok).toBe(true);
// Over it: ClickHouse code 158, from the profile — no setting was sent.
const over = await tiny(`SELECT count() FROM t_alpha_sql.sales a, t_alpha_sql.sales b`);
expect(over.ok).toBe(false);
expect(over.body).toContain('Code: 158');
// And it cannot be raised from the request: code 164, readonly mode.
const raise = await tiny(`SELECT count() FROM t_alpha_sql.sales`);
expect(raise.ok).toBe(true);
const raised = await run(
`SELECT count() FROM t_alpha_sql.sales a, t_alpha_sql.sales b`,
`t_alpha_tiny_user:${TINY_PW}`,
{
max_rows_to_read: '0',
},
);
expect(raised.ok).toBe(false);
expect(raised.body).toContain('Code: 164');
});
it('layer 3: the restricted user cannot read a table it was never granted', async () => {
const res = await asAlpha(`SELECT note FROM ${DB}.secret_ledger`);
expect(res.ok).toBe(false);
expect(res.body).not.toContain(SECRET_CANARY);
});
it("layer 3: the restricted user cannot read the other tenant's catalog", async () => {
const res = await asAlpha(`SELECT customer FROM t_beta_sql.sales LIMIT 5`);
expect(res.ok).toBe(false);
expect(res.body).not.toContain(BETA_CANARY);
});
it('layer 3: readonly=1 refuses a write even though the guard never saw the statement', async () => {
const res = await asAlpha(`INSERT INTO ${DB}.sales VALUES ('t_alpha', 'x', 1, now())`);
expect(res.ok).toBe(false);
const after = await admin(`SELECT count() FROM ${DB}.sales`);
expect(Number(after.body.trim())).toBe(100);
});
it('layer 3: readonly=1 refuses a statement that tries to raise its own ceiling', async () => {
const res = await asAlpha(`SELECT count() FROM t_alpha_sql.sales SETTINGS max_rows_to_read = 0`);
expect(res.ok).toBe(false);
});
it('layer 4: the tenant column the view does not project is not selectable', async () => {
// This is the case the GUARD ADMITS. It must fail here, or the honest
// note in the corpus would be covering a real hole.
const res = await asAlpha(`SELECT tenant_id FROM t_alpha_sql.sales LIMIT 1`);
expect(res.ok).toBe(false);
});
it('layer 4: a WHERE on the hidden tenant column cannot widen the view', async () => {
const res = await asAlpha(`SELECT count() FROM t_alpha_sql.sales WHERE tenant_id = 't_beta'`);
expect(res.ok).toBe(false);
});
});
@@ -0,0 +1,183 @@
/**
* BI-P005 conformance against an INDEPENDENT Arrow implementation.
*
* The unit suite (tests/analytics/arrow-ipc.test.ts) only proves 0pt's
* encoder agrees with 0pt's decoder — which it would even if both shared the
* same misreading of the spec. Here, ClickHouse's Arrow C++ implementation is
* the second opinion, in BOTH directions:
*
* ClickHouse -> Arrow -> 0pt decoder (their encoder, our reader)
* 0pt encoder -> Arrow -> ClickHouse (our encoder, their reader)
*
* The second direction is the load-bearing one: ClickHouse INSERTing our
* bytes and then answering a SELECT with the exact values back is a claim
* that cannot be satisfied by a subtly wrong buffer layout.
*
* The DoD's literal chain (ClickHouse -> Arrow -> DuckDB/Python) additionally
* ran against real pyarrow + DuckDB; that transcript is committed at
* evidence/bi-p002-p012/bi-p005-arrow-roundtrip.json.
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import {
arrowStreamSettings,
clickhouseArrowStreamFormat,
decodeArrowStream,
encodeArrowStream,
} from "@/src/analytics/arrow/ipc";
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_arrow_${Date.now().toString(36)}`;
function authHeaders(): Record<string, string> {
return CLICKHOUSE_AUTH
? { Authorization: `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString("base64")}` }
: {};
}
async function chBytes(sql: string, settings: Record<string, string> = {}): Promise<Uint8Array> {
const url = new URL(CLICKHOUSE_URL ?? "http://skipped.invalid");
url.searchParams.set("query", sql);
for (const [k, v] of Object.entries(settings)) url.searchParams.set(k, v);
const res = await fetch(url.toString(), { method: "POST", headers: authHeaders(), body: "" });
const buf = new Uint8Array(await res.arrayBuffer());
if (!res.ok) throw new Error(`CH ${res.status}: ${new TextDecoder().decode(buf).slice(0, 300)}`);
return buf;
}
async function chText(sql: string, body?: BodyInit): Promise<string> {
const url = new URL(CLICKHOUSE_URL ?? "http://skipped.invalid");
url.searchParams.set("query", sql);
const res = await fetch(url.toString(), { method: "POST", headers: authHeaders(), body: body ?? "" });
const text = await res.text();
if (!res.ok) throw new Error(`CH ${res.status}: ${text.slice(0, 400)}`);
return text;
}
run("BI-P005 Arrow IPC against a LIVE ClickHouse", () => {
beforeAll(async () => {
await chText(`CREATE DATABASE IF NOT EXISTS ${DB}`);
await chText(
`CREATE TABLE IF NOT EXISTS ${DB}.arrow_roundtrip (
tenant_id String, n Int64, v Float64, flag Bool, ts DateTime64(3, 'UTC')
) ENGINE = MergeTree() ORDER BY (tenant_id, n)`,
);
}, 60_000);
afterAll(async () => {
if (CLICKHOUSE_URL) await chText(`DROP DATABASE IF EXISTS ${DB}`);
}, 60_000);
it("THEIR encoder, OUR reader: ClickHouse ArrowStream decodes with the expected schema and row count", async () => {
const bytes = await chBytes(
`SELECT toString(t) AS tenant_id, toInt64(n) AS n, toFloat64(v) AS v, b AS flag,
toDateTime64(ts, 3, 'UTC') AS ts
FROM (
SELECT arrayJoin([
('t_alpha', 1, 1.5, true, '2026-01-01 00:00:00.000'),
('t_beta', 2, 2.5, false, '2026-06-15 08:09:10.123'),
('t_gamma', 3, 3.25, true, '2026-09-06 12:34:56.789')
]) AS tup, tup.1 AS t, tup.2 AS n, tup.3 AS v, tup.4 AS b, tup.5 AS ts
)
FORMAT ${clickhouseArrowStreamFormat()}`,
arrowStreamSettings(),
);
const info = decodeArrowStream(bytes);
expect(info.rowCount).toBe(3);
expect(info.fields.map((f) => f.name)).toEqual(["tenant_id", "n", "v", "flag", "ts"]);
// Utf8=5 (NOT Binary=4 — that is what output_format_arrow_string_as_string buys),
// Int=2, FloatingPoint=3, Bool=6, Timestamp=10.
expect(info.fields.map((f) => f.typeType)).toEqual([5, 2, 3, 6, 10]);
});
it("WITHOUT output_format_arrow_string_as_string, ClickHouse emits Binary — the semantic loss the setting prevents", async () => {
const bytes = await chBytes(`SELECT 'x' AS s FORMAT ${clickhouseArrowStreamFormat()}`, {
output_format_arrow_string_as_string: "0",
});
// Arrow Type union: Binary = 4, Utf8 = 5.
expect(decodeArrowStream(bytes).fields[0].typeType).toBe(4);
const asText = await chBytes(`SELECT 'x' AS s FORMAT ${clickhouseArrowStreamFormat()}`, arrowStreamSettings());
expect(decodeArrowStream(asText).fields[0].typeType).toBe(5);
});
it("OUR encoder, THEIR reader: ClickHouse INSERTs our Arrow and returns every value unchanged", async () => {
const bytes = encodeArrowStream([
{ name: "tenant_id", type: "utf8", values: ["t_alpha", "t_beta", "t_gamma"] },
{ name: "n", type: "int64", values: [1, 2, 3] },
{ name: "v", type: "float64", values: [1.5, 2.5, 3.25] },
{ name: "flag", type: "bool", values: [true, false, true] },
{
name: "ts",
type: "timestamp_ms",
values: [
new Date("2026-01-01T00:00:00.000Z"),
new Date("2026-06-15T08:09:10.123Z"),
new Date("2026-09-06T12:34:56.789Z"),
],
},
]);
await chText(`INSERT INTO ${DB}.arrow_roundtrip FORMAT ArrowStream`, bytes as unknown as BodyInit);
const back = await chText(
`SELECT tenant_id, n, v, flag, toString(ts) AS ts FROM ${DB}.arrow_roundtrip ORDER BY n FORMAT JSON`,
);
const rows = (JSON.parse(back) as {
data: { tenant_id: string; n: string | number; v: number | string; flag: boolean | number; ts: string }[];
}).data;
expect(rows).toHaveLength(3);
expect(rows.map((r) => r.tenant_id)).toEqual(["t_alpha", "t_beta", "t_gamma"]);
expect(rows.map((r) => Number(r.n))).toEqual([1, 2, 3]);
expect(rows.map((r) => Number(r.v))).toEqual([1.5, 2.5, 3.25]);
expect(rows.map((r) => Boolean(Number(r.flag)))).toEqual([true, false, true]);
expect(rows.map((r) => r.ts)).toEqual([
"2026-01-01 00:00:00.000",
"2026-06-15 08:09:10.123",
"2026-09-06 12:34:56.789",
]);
});
it("full circle: ClickHouse -> Arrow -> our decoder -> ClickHouse yields identical rows", async () => {
const exported = await chBytes(
`SELECT tenant_id, n, v, flag, ts FROM ${DB}.arrow_roundtrip ORDER BY n FORMAT ArrowStream`,
arrowStreamSettings(),
);
expect(decodeArrowStream(exported).rowCount).toBe(3);
await chText(`CREATE TABLE IF NOT EXISTS ${DB}.arrow_circle AS ${DB}.arrow_roundtrip`);
await chText(`INSERT INTO ${DB}.arrow_circle FORMAT ArrowStream`, exported as unknown as BodyInit);
const diff = await chText(
`SELECT count() AS c FROM (
SELECT * FROM ${DB}.arrow_roundtrip
EXCEPT
SELECT * FROM ${DB}.arrow_circle
) FORMAT JSON`,
);
expect(Number((JSON.parse(diff) as { data: { c: number | string }[] }).data[0].c)).toBe(0);
});
it("a large result survives the round trip (batching/offsets are not only correct for three rows)", async () => {
const n = 20_000;
const bytes = encodeArrowStream([
{ name: "tenant_id", type: "utf8", values: Array.from({ length: n }, (_, i) => `t_${i % 7}`) },
{ name: "n", type: "int64", values: Array.from({ length: n }, (_, i) => i) },
{ name: "v", type: "float64", values: Array.from({ length: n }, (_, i) => i / 3) },
{ name: "flag", type: "bool", values: Array.from({ length: n }, (_, i) => i % 2 === 0) },
{ name: "ts", type: "timestamp_ms", values: Array.from({ length: n }, () => new Date("2026-09-06T00:00:00Z")) },
]);
expect(decodeArrowStream(bytes).rowCount).toBe(n);
await chText(`CREATE TABLE IF NOT EXISTS ${DB}.arrow_big AS ${DB}.arrow_roundtrip`);
await chText(`INSERT INTO ${DB}.arrow_big FORMAT ArrowStream`, bytes as unknown as BodyInit);
const agg = await chText(
`SELECT count() AS c, sum(n) AS s, uniqExact(tenant_id) AS t, countIf(flag) AS f FROM ${DB}.arrow_big FORMAT JSON`,
);
const d = (JSON.parse(agg) as { data: { c: string | number; s: string | number; t: string | number; f: string | number }[] }).data[0];
expect(Number(d.c)).toBe(n);
expect(Number(d.s)).toBe((n * (n - 1)) / 2);
expect(Number(d.t)).toBe(7);
expect(Number(d.f)).toBe(n / 2);
}, 60_000);
});
@@ -0,0 +1,96 @@
/**
* REAL ClickHouse integration test (Master-DoD §48/§50) for the Analytics
* capability. Runs against CLICKHOUSE_URL (+ CLICKHOUSE_AUTH "user:pass"
* when the server requires it); SKIPS HONESTLY when unset.
*
* Proves against the real engine: schema creation with TTL retention,
* JSONEachRow ingest, the closed metric-query DSL, and — the §69-relevant
* part — that the FORCED tenant predicate isolates tenants on real data.
*/
import { describe, it, expect, beforeAll } from "vitest";
import { ClickHouseAnalytics } from "@/src/analytics/clickhouse-analytics";
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_itest_${Date.now().toString(36)}`;
run("Analytics capability against a LIVE ClickHouse", () => {
// The skip-variant still evaluates this callback body, so the constructor
// must tolerate the env-less case (the tests themselves never run then).
const analytics = new ClickHouseAnalytics({
baseUrl: CLICKHOUSE_URL ?? "http://skipped.invalid",
basicAuth: process.env.CLICKHOUSE_AUTH,
database: DB,
});
beforeAll(async () => {
expect(await analytics.health()).toBe(true);
await analytics.ensureSchema(30);
// ensureSchema is idempotent (CREATE IF NOT EXISTS).
await analytics.ensureSchema(30);
}, 60_000);
it("ingests events and answers aggregate metric queries", async () => {
const res = await analytics.ingest([
{ tenant_id: "t_alpha", dataset_id: "ds_companies", metric: "rows_ingested", value: 100 },
{ tenant_id: "t_alpha", dataset_id: "ds_companies", metric: "rows_ingested", value: 50 },
{ tenant_id: "t_alpha", dataset_id: "ds_vehicles", metric: "rows_ingested", value: 7 },
{ tenant_id: "t_beta", dataset_id: "ds_companies", metric: "rows_ingested", value: 999 },
]);
expect(res.ingested).toBe(4);
const total = await analytics.queryMetric({
tenant_id: "t_alpha",
metric: "rows_ingested",
aggregate: "sum",
});
expect(total).toEqual([{ value: 157 }]);
const perDataset = await analytics.queryMetric({
tenant_id: "t_alpha",
dataset_id: "ds_companies",
metric: "rows_ingested",
aggregate: "sum",
});
expect(perDataset).toEqual([{ value: 150 }]);
}, 30_000);
it("REAL tenant isolation: t_beta's numbers never leak into t_alpha aggregates", async () => {
const alpha = await analytics.queryMetric({ tenant_id: "t_alpha", metric: "rows_ingested", aggregate: "max" });
expect(alpha[0].value).toBe(100); // NOT 999
const beta = await analytics.queryMetric({ tenant_id: "t_beta", metric: "rows_ingested", aggregate: "sum" });
expect(beta[0].value).toBe(999);
const ghost = await analytics.queryMetric({ tenant_id: "t_gamma", metric: "rows_ingested", aggregate: "count" });
expect(ghost[0].value).toBe(0);
});
it("group-by dimension queries work through the closed DSL", async () => {
await analytics.ingest([
{ tenant_id: "t_alpha", dataset_id: "ds_x", metric: "dq_score", value: 90, dimensions: { severity: "warning" } },
{ tenant_id: "t_alpha", dataset_id: "ds_x", metric: "dq_score", value: 40, dimensions: { severity: "critical" } },
]);
const rows = await analytics.queryMetric({
tenant_id: "t_alpha",
metric: "dq_score",
aggregate: "avg",
group_by: "severity",
});
expect(rows).toHaveLength(2);
expect(rows.find((r) => r.group === "warning")?.value).toBe(90);
});
it("rejects tenant-less queries and invalid group_by identifiers (injection surface closed)", async () => {
await expect(
analytics.queryMetric({ tenant_id: " ", metric: "x", aggregate: "sum" })
).rejects.toMatchObject({ code: "INVALID_REQUEST" });
await expect(
analytics.queryMetric({
tenant_id: "t_alpha",
metric: "x",
aggregate: "sum",
group_by: "sev'; DROP TABLE opt_metric_events; --",
})
).rejects.toMatchObject({ code: "INVALID_REQUEST" });
});
});
@@ -0,0 +1,261 @@
/**
* BI-P009 (canonical OLAP provider) + BI-P010 (production schema), against a
* LIVE ClickHouse.
*
* Every one of the eight `SiaxAnalyticsEngine` capabilities is exercised for
* real here. A capability that only has a unit test with a stubbed fetch is a
* capability whose SQL has never been parsed by ClickHouse — `EXPLAIN
* ESTIMATE`, `KILL QUERY` and `OPTIMIZE ... PARTITION` in particular are
* syntax the server either accepts or does not, and no mock can tell you
* which.
*
* Gated on CLICKHOUSE_URL; skips honestly when unset. CI's `integration` job
* supplies it and hard-fails on a skipped suite.
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { ClickHouseAnalyticsEngine } from "@/src/analytics/engine/clickhouse-engine";
import { ANALYTICS_MATERIALIZED_VIEWS, ANALYTICS_TABLES } from "@/src/analytics/engine/schema";
import type { AnalyticsIdentity } from "@/src/analytics/engine/siax-analytics-engine";
/**
* Raw events carry a 30-day TTL (src/analytics/engine/schema.ts). Fixed
* historical timestamps silently expire and make live-ClickHouse suites read
* 0 rows, so seed rows are stamped relative to now (UTC, ClickHouse
* DateTime64(3) text form).
*/
const SEED_EVENT_TIME = new Date(Date.now() - 2 * 3600_000).toISOString().replace("T", " ").replace("Z", "");
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_engine_${Date.now().toString(36)}`;
const ID: AnalyticsIdentity = { tenant_id: "t_alpha", project_id: "p_main", principal_id: "usr_alpha" };
let engine: ClickHouseAnalyticsEngine;
async function raw(sql: string, body?: string): Promise<string> {
const url = new URL(CLICKHOUSE_URL ?? "http://skipped.invalid");
url.searchParams.set("query", sql);
const headers: Record<string, string> = {};
if (CLICKHOUSE_AUTH) headers["Authorization"] = `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString("base64")}`;
const res = await fetch(url.toString(), { method: "POST", headers, body: body ?? "" });
const text = await res.text();
if (!res.ok) throw new Error(`CH ${res.status}: ${text.slice(0, 300)}`);
return text;
}
run("BI-P009/BI-P010 ClickHouse provider against a LIVE server", () => {
beforeAll(async () => {
engine = new ClickHouseAnalyticsEngine({
baseUrl: CLICKHOUSE_URL!,
basicAuth: CLICKHOUSE_AUTH,
database: DB,
dimensionCatalogs: { t_alpha: { severity: "severity", make: "vehicle_make" } },
});
await engine.ensureSchema();
await engine.ensureSchema(); // idempotent, as the DDL claims
}, 120_000);
afterAll(async () => {
if (CLICKHOUSE_URL) await raw(`DROP DATABASE IF EXISTS ${DB}`);
}, 60_000);
// ── capability 1: health ────────────────────────────────────────────────
it("health() reports the live server's version", async () => {
const h = await engine.health();
expect(h.healthy).toBe(true);
expect(h.provider).toBe("clickhouse");
expect(h.version).toMatch(/^\d+\.\d+/);
});
// ── BI-P010: the schema is what it claims to be ─────────────────────────
it("BI-P010: four purpose-built tables exist, NOT one giant table", async () => {
const listed = await raw(
`SELECT name FROM system.tables WHERE database = '${DB}' AND engine != 'MaterializedView' ORDER BY name FORMAT TSV`,
);
const names = listed.trim().split("\n").filter(Boolean);
// The three this module owns, PLUS the preserved opt_metric_events.
for (const t of ANALYTICS_TABLES) expect(names).toContain(t);
expect(names).toContain("opt_metric_events");
expect(names.length).toBeGreaterThanOrEqual(4);
});
it("BI-P010: the tables use different engines and different sort keys — the split is real", async () => {
const meta = await raw(
`SELECT name, engine, sorting_key FROM system.tables WHERE database = '${DB}' ORDER BY name FORMAT JSON`,
);
const rows = (JSON.parse(meta) as { data: { name: string; engine: string; sorting_key: string }[] }).data;
const by = Object.fromEntries(rows.map((r) => [r.name, r]));
expect(by["opt_analytics_event"].engine).toBe("MergeTree");
expect(by["opt_metric_daily"].engine).toBe("AggregatingMergeTree");
expect(by["opt_dataset_projection"].engine).toBe("ReplacingMergeTree");
// Different ORDER BY keys — the reason one table cannot serve both jobs.
expect(by["opt_analytics_event"].sorting_key).not.toBe(by["opt_dataset_projection"].sorting_key);
// Every one still leads with tenant_id.
for (const t of ANALYTICS_TABLES) expect(by[t].sorting_key.startsWith("tenant_id")).toBe(true);
});
it("BI-P010: TTL and LowCardinality are actually applied, not just written in a comment", async () => {
const ddl = await raw(`SHOW CREATE TABLE ${DB}.opt_analytics_event FORMAT TSVRaw`);
expect(ddl).toContain("TTL");
expect(ddl).toContain("LowCardinality(String)");
expect(ddl).toContain("PARTITION BY toYYYYMM(event_time)");
const rollup = await raw(`SHOW CREATE TABLE ${DB}.opt_metric_daily FORMAT TSVRaw`);
expect(rollup).toContain("AggregateFunction(sum, Float64)");
});
it("BI-P010: the materialized view actually populates the rollup", async () => {
const views = await raw(
`SELECT name FROM system.tables WHERE database='${DB}' AND engine='MaterializedView' FORMAT TSV`,
);
for (const v of ANALYTICS_MATERIALIZED_VIEWS) expect(views).toContain(v);
await engine.ingestProjection(ID, { dataset_id: "warmup", rows: [{ entity_key: "w1" }] });
const rows = Array.from({ length: 20 }, (_, i) =>
JSON.stringify({
tenant_id: "t_alpha",
project_id: "p_main",
dataset_id: "ds_mv",
metric: "mv_metric",
event_id: `mv${i}`,
event_time: SEED_EVENT_TIME,
value: 2,
dim_names: [],
dim_values: [],
}),
).join("\n");
await raw(`INSERT INTO ${DB}.opt_analytics_event FORMAT JSONEachRow`, rows);
const rolled = await raw(
`SELECT sumMerge(sum_state) AS s, countMerge(count_state) AS c FROM ${DB}.opt_metric_daily ` +
`WHERE tenant_id = 't_alpha' AND metric = 'mv_metric' FORMAT JSON`,
);
const d = (JSON.parse(rolled) as { data: { s: number | string; c: number | string }[] }).data[0];
expect(Number(d.s)).toBe(40); // 20 rows x 2
expect(Number(d.c)).toBe(20);
});
// ── capability 2: executeMetric (already covered by the isolation suite) ─
it("executeMetric returns grouped rows keyed by the CALLER-FACING dimension name", async () => {
const rows = ["warning", "critical", "critical"].map((sev, i) =>
JSON.stringify({
tenant_id: "t_alpha",
project_id: "p_main",
dataset_id: "ds_g",
metric: "grouped",
event_id: `g${i}`,
event_time: SEED_EVENT_TIME,
value: 5,
dim_names: ["severity"],
dim_values: [sev],
}),
);
await raw(`INSERT INTO ${DB}.opt_analytics_event FORMAT JSONEachRow`, rows.join("\n"));
const result = await engine.executeMetric(ID, {
metric: "grouped",
aggregate: "sum",
group_by: ["severity"],
});
const critical = result.rows.find((r) => r.groups?.severity === "critical");
expect(critical?.value).toBe(10);
expect(result.stats.result_rows).toBe(2);
expect(result.query_id.startsWith("opt_")).toBe(true);
});
// ── capability 4: estimateQuery ─────────────────────────────────────────
it("estimateQuery gets a real EXPLAIN ESTIMATE from the server and compares it to the budget", async () => {
const est = await engine.estimateQuery(ID, { metric: "grouped", aggregate: "sum" });
expect(est.estimated_rows_to_read).toBeGreaterThan(0);
expect(est.within_budget).toBe(true);
expect(est.budget.maxRowsToRead).toBeGreaterThan(0);
});
it("estimateQuery REFUSES a query whose estimate exceeds a tightened quota", async () => {
const tiny: AnalyticsIdentity = { ...ID, quota: { maxRowsToRead: 1 } };
const est = await engine.estimateQuery(tiny, { metric: "grouped", aggregate: "sum" });
expect(est.within_budget).toBe(false);
expect(est.reason).toMatch(/over budget/);
});
// ── capability 6: explain ───────────────────────────────────────────────
it("explain() proves the forced predicate reaches the PRIMARY KEY, pruning parts", async () => {
const ex = await engine.explain(ID, { metric: "grouped", aggregate: "sum", group_by: ["severity"] });
expect(ex.forced_tenant_predicate).toBe("tenant_id = {tenant:String}");
expect(ex.table).toBe("opt_analytics_event");
// This is the payoff of BI-P010's tenant-first ORDER BY: the server
// reports tenant_id as a PrimaryKey key with a condition on it, i.e. the
// isolation predicate is an index range scan, not a post-read filter.
expect(ex.plan).toContain("ReadFromMergeTree");
expect(ex.plan).toContain("PrimaryKey");
expect(ex.plan).toMatch(/Keys:[\s\S]*tenant_id/);
expect(ex.plan).toMatch(/tenant_id in \['t_alpha', 't_alpha'\]/);
// The plan describes only the CALLER's own tenant; no other tenant id
// may appear in a plan handed back to them.
expect(ex.plan).not.toContain("t_beta");
});
// ── capability 5: cancelQuery ───────────────────────────────────────────
it("cancelQuery issues a real KILL QUERY the server accepts", async () => {
// Nothing is running under this id, so the honest outcome is "the KILL
// statement was valid and matched nothing" -> true, with no exception.
const ok = await engine.cancelQuery(ID, `${(await engine.executeMetric(ID, { metric: "grouped", aggregate: "count" })).query_id}`);
expect(ok).toBe(true);
});
// ── capabilities 7 + 8: ingestProjection / refreshProjection ────────────
it("ingestProjection writes the SERVING tier with the identity's tenant, ignoring any row-level claim", async () => {
const res = await engine.ingestProjection(ID, {
dataset_id: "ds_vehicles",
rows: [
{ entity_key: "VIN001", attributes: { make: "volvo" }, measures: { price: 189000 } },
{ entity_key: "VIN002", attributes: { make: "saab" }, measures: { price: 42000 } },
],
});
expect(res.ingested).toBe(2);
const stored = await raw(
`SELECT uniqExact(tenant_id) AS t FROM ${DB}.opt_dataset_projection WHERE dataset_id = 'ds_vehicles' FORMAT JSON`,
);
expect(Number((JSON.parse(stored) as { data: { t: number | string }[] }).data[0].t)).toBe(1);
});
it("refreshProjection makes a re-ingest idempotent (ReplacingMergeTree + OPTIMIZE FINAL)", async () => {
// Re-ingest the SAME entity keys at a higher version.
await engine.ingestProjection(ID, {
dataset_id: "ds_vehicles",
rows: [
{ entity_key: "VIN001", version: 9_999_999_999_999, measures: { price: 175000 } },
{ entity_key: "VIN002", version: 9_999_999_999_999, measures: { price: 41000 } },
],
});
const refreshed = await engine.refreshProjection(ID, "ds_vehicles");
expect(refreshed.row_count).toBe(2); // 2 entities, not 4 rows
expect(refreshed.dataset_id).toBe("ds_vehicles");
const winner = await raw(
`SELECT measures['price'] AS p FROM ${DB}.opt_dataset_projection FINAL ` +
`WHERE tenant_id='t_alpha' AND dataset_id='ds_vehicles' AND entity_key='VIN001' FORMAT JSON`,
);
expect(Number((JSON.parse(winner) as { data: { p: number | string }[] }).data[0].p)).toBe(175000);
});
// ── the PRESERVED path still works through the engine ───────────────────
it("the PRESERVED ClickHouseAnalytics path still ingests and answers through the engine", async () => {
await engine.legacyAnalytics.ingest([
{ tenant_id: "t_alpha", dataset_id: "ds_legacy", metric: "legacy_metric", value: 7 },
{ tenant_id: "t_beta", dataset_id: "ds_legacy", metric: "legacy_metric", value: 700 },
]);
const res = await engine.executeLegacyMetric(ID, { metric: "legacy_metric", aggregate: "sum" });
expect(res.rows[0].value).toBe(7); // NOT 707
});
});
@@ -0,0 +1,246 @@
/**
* BI-P012 DoD, against a LIVE ClickHouse:
*
* "Intentional query bomb is terminated without degrading unrelated tenant
* beyond declared SLO."
*
* Two halves, and the second is the one that is usually skipped:
*
* 1. TERMINATED — a deliberately enormous query is refused by the server,
* with the ClickHouse limit that stopped it identified by code. Each
* limit BI-P012 names is fired individually, so "some limit stopped it"
* is never mistaken for "the limit I claimed stopped it".
* 2. UNRELATED TENANT NOT DEGRADED — a second tenant's interactive query is
* timed WHILE the bomb is in flight and compared against a declared SLO,
* not merely observed to "still work".
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { ClickHouseAnalyticsEngine } from "@/src/analytics/engine/clickhouse-engine";
import { DEFAULT_BUDGETS } from "@/src/analytics/engine/resource-governance";
import type { AnalyticsIdentity } from "@/src/analytics/engine/siax-analytics-engine";
/**
* Raw events carry a 30-day TTL (src/analytics/engine/schema.ts). Fixed
* historical timestamps silently expire and make live-ClickHouse suites read
* 0 rows, so seed rows are stamped relative to now (UTC, ClickHouse
* DateTime64(3) text form).
*/
const SEED_EVENT_TIME = new Date(Date.now() - 2 * 3600_000).toISOString().replace("T", " ").replace("Z", "");
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_gov_${Date.now().toString(36)}`;
/**
* The SLO this test asserts against. Declared as a constant so the claim is
* falsifiable rather than "it still seemed to work".
*
* 5000 ms is deliberately generous for a 500-row lookup (it measures ~30 ms
* on an idle server). It is set for the SHARED CI runner, not for a quiet
* laptop: a tenant that had actually been starved by the bomb would take
* seconds or fail outright, so the assertion still discriminates, while a
* merely busy runner does not turn this gate into a flake.
*/
const UNRELATED_TENANT_SLO_MS = 5000;
const VICTIM: AnalyticsIdentity = { tenant_id: "t_victim", project_id: "p_main", principal_id: "usr_v" };
let engine: ClickHouseAnalyticsEngine;
/** Run a statement with explicit settings and report the ClickHouse code. */
async function chRun(
sql: string,
settings: Record<string, string> = {},
body?: string,
): Promise<{ ok: boolean; code?: string; text: string; ms: number }> {
const url = new URL(CLICKHOUSE_URL ?? "http://skipped.invalid");
url.searchParams.set("query", sql);
for (const [k, v] of Object.entries(settings)) url.searchParams.set(k, v);
const headers: Record<string, string> = {};
if (CLICKHOUSE_AUTH) headers["Authorization"] = `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString("base64")}`;
const t0 = Date.now();
const res = await fetch(url.toString(), { method: "POST", headers, body: body ?? "" });
const text = await res.text();
return { ok: res.ok, code: /Code: (\d+)/.exec(text)?.[1], text, ms: Date.now() - t0 };
}
run("BI-P012 resource governance against a LIVE ClickHouse", () => {
beforeAll(async () => {
engine = new ClickHouseAnalyticsEngine({
baseUrl: CLICKHOUSE_URL!,
basicAuth: CLICKHOUSE_AUTH,
database: DB,
dimensionCatalogs: { t_victim: { severity: "severity" } },
});
await engine.ensureSchema();
// A small, real dataset for the unrelated tenant.
const rows = Array.from({ length: 500 }, (_, i) =>
JSON.stringify({
tenant_id: "t_victim",
project_id: "p_main",
dataset_id: "ds_v",
metric: "victim_metric",
event_id: `v${i}`,
event_time: SEED_EVENT_TIME,
value: 1,
dim_names: ["severity"],
dim_values: ["warning"],
}),
).join("\n");
const ins = await chRun(`INSERT INTO ${DB}.opt_analytics_event FORMAT JSONEachRow`, {}, rows);
expect(ins.ok, ins.text.slice(0, 200)).toBe(true);
}, 120_000);
afterAll(async () => {
if (CLICKHOUSE_URL) await chRun(`DROP DATABASE IF EXISTS ${DB}`);
}, 60_000);
// ── each named limit, fired individually ────────────────────────────────
it("max_rows_to_read terminates a read bomb (CH code 158 TOO_MANY_ROWS)", async () => {
const r = await chRun("SELECT count() FROM numbers(1000000000) FORMAT JSON", {
readonly: "1",
max_rows_to_read: "1000",
read_overflow_mode: "throw",
});
expect(r.ok).toBe(false);
expect(r.code).toBe("158");
});
it("max_bytes_to_read terminates a scan bomb (CH code 307 TOO_MANY_BYTES)", async () => {
const r = await chRun("SELECT sum(number) FROM numbers(1000000000) FORMAT JSON", {
readonly: "1",
max_bytes_to_read: "1024",
read_overflow_mode: "throw",
});
expect(r.ok).toBe(false);
expect(r.code).toBe("307");
});
it("max_execution_time terminates a slow bomb (CH code 159 TIMEOUT_EXCEEDED)", async () => {
const r = await chRun("SELECT count() FROM numbers(50000000000) FORMAT JSON", {
readonly: "1",
max_execution_time: "1",
timeout_overflow_mode: "throw",
});
expect(r.ok).toBe(false);
expect(r.code).toBe("159");
expect(r.ms).toBeLessThan(20_000);
});
it("max_result_rows terminates a result bomb and does NOT return a partial result", async () => {
const r = await chRun("SELECT number FROM numbers(100000) FORMAT JSON", {
readonly: "1",
max_result_rows: "10",
result_overflow_mode: "throw",
});
expect(r.ok).toBe(false);
expect(r.code).toBe("396"); // TOO_MANY_ROWS_OR_BYTES
// The dangerous alternative: result_overflow_mode=break returns 10 rows
// with HTTP 200 and no indication of truncation.
const broken = await chRun("SELECT number FROM numbers(100000) FORMAT JSON", {
readonly: "1",
max_result_rows: "10",
result_overflow_mode: "break",
});
// MEASURED on ClickHouse 24.8: break mode answers HTTP 200 with 65409 of
// 100000 rows (it stops at a block boundary, not at the stated 10) and
// nothing in the payload says it is short. That is why every SELECT in
// this engine ships result_overflow_mode=throw.
expect(broken.ok).toBe(true);
const brokenRows = (JSON.parse(broken.text) as { data: unknown[] }).data.length;
expect(brokenRows).toBeGreaterThan(10);
expect(brokenRows).toBeLessThan(100_000);
});
it("max_memory_usage terminates a memory bomb (CH code 241 MEMORY_LIMIT_EXCEEDED)", async () => {
const r = await chRun(
"SELECT uniqExact(toString(number)) FROM numbers(50000000) FORMAT JSON",
{ readonly: "1", max_memory_usage: "1000000", max_execution_time: "30" },
);
expect(r.ok).toBe(false);
expect(r.code).toBe("241");
});
it("readonly=1 means the query text cannot re-raise its own limits", async () => {
const r = await chRun(
"SELECT count() FROM numbers(1000000000) SETTINGS max_rows_to_read = 10000000000 FORMAT JSON",
{ readonly: "1", max_rows_to_read: "1000", read_overflow_mode: "throw" },
);
expect(r.ok).toBe(false);
// 164 = READONLY (changing settings is forbidden); 158 = the limit still
// applied. Either proves the caller did not win — but NOT a 200.
expect(["164", "158"]).toContain(r.code);
});
it("readonly=1 blocks writes through the query surface", async () => {
const r = await chRun(`DROP TABLE ${DB}.opt_analytics_event FORMAT JSON`, { readonly: "1" });
expect(r.ok).toBe(false);
});
// ── the half that is usually skipped ────────────────────────────────────
it("an unrelated tenant stays within its declared SLO WHILE a query bomb is in flight", async () => {
// Baseline first, so "fast enough" is measured against this server, not
// against a number someone hoped for.
const baseline = await engine.executeMetric(VICTIM, { metric: "victim_metric", aggregate: "count" });
expect(baseline.rows[0].value).toBe(500);
const baselineMs = baseline.stats.duration_ms;
// Fire a genuine bomb the server must spend real CPU on. MEASURED: a bare
// `count()` over numbers() is NOT a bomb — ClickHouse answers
// numbers(20e9) in ~5s because it can skip the values entirely. Hashing
// every row cannot be short-circuited, so this one really does burn CPU
// until the limit kills it.
const bomb = chRun("SELECT sum(cityHash64(number)) FROM numbers(20000000000) FORMAT JSON", {
readonly: "1",
max_execution_time: "8",
timeout_overflow_mode: "throw",
});
// While it burns, run the unrelated tenant's interactive query repeatedly.
const samples: number[] = [];
for (let i = 0; i < 5; i++) {
const r = await engine.executeMetric(VICTIM, { metric: "victim_metric", aggregate: "count" });
expect(r.rows[0].value).toBe(500); // still CORRECT, not just fast
samples.push(r.stats.duration_ms);
}
const bombResult = await bomb;
expect(bombResult.ok, "the bomb was NOT terminated").toBe(false);
expect(bombResult.code).toBe("159");
const worst = Math.max(...samples);
expect(
worst,
`unrelated tenant degraded: baseline ${baselineMs}ms, worst under load ${worst}ms, SLO ${UNRELATED_TENANT_SLO_MS}ms`,
).toBeLessThan(UNRELATED_TENANT_SLO_MS);
}, 60_000);
// ── the local admission gate, on the real engine ────────────────────────
it("the per-tenant concurrency gate refuses the N+1st in-flight query for THAT tenant only", async () => {
const limit = DEFAULT_BUDGETS.INTERACTIVE.maxConcurrentQueries;
// Fire limit+4 concurrently; some must be refused with RATE_LIMITED
// rather than all of them reaching the server.
const attempts = Array.from({ length: limit + 4 }, () =>
engine
.executeMetric(VICTIM, { metric: "victim_metric", aggregate: "count" })
.then(() => "ok" as const)
.catch((e: { code?: string }) => e.code ?? "error"),
);
const outcomes = await Promise.all(attempts);
expect(outcomes.filter((o) => o === "RATE_LIMITED").length).toBeGreaterThan(0);
expect(outcomes.filter((o) => o === "ok").length).toBeGreaterThan(0);
// A different tenant is unaffected by the noisy one's exhausted slots.
const other = await engine.executeMetric(
{ tenant_id: "t_quiet", project_id: "p_main", principal_id: "usr_q" },
{ metric: "victim_metric", aggregate: "count" },
);
expect(other.rows[0].value).toBe(0); // its own (empty) data, and no error
}, 60_000);
});
@@ -0,0 +1,317 @@
/**
* BI-P011 — CLICKHOUSE TENANT ISOLATION, proven against a LIVE server.
*
* The shape of this proof is the estate's own convention for isolation work:
* DEMONSTRATE THE HOLE WITHOUT THE FIX, then demonstrate it CLOSED WITH the
* fix. A suite that only exercises the fixed path proves that the fixed path
* works, which is not the same claim.
*
* So each layer is tested twice:
*
* layer 2 (0pt query compiler forces tenant)
* hole: a hand-written statement WITHOUT the predicate — the same query
* minus the forcing — returns another tenant's rows. This is the
* literal regression a future refactor would cause.
* closed: the compiled statement returns only this tenant's rows.
*
* layer 3 (restricted database users + row policies)
* hole: the UNRESTRICTED admin user, issuing a statement with NO tenant
* predicate at all, sees every tenant.
* closed: the RESTRICTED per-tenant user, issuing the SAME statement,
* sees only its own tenant — the server filters, so the result
* holds even if layer 2 were removed entirely.
*
* Gated on CLICKHOUSE_URL and SKIPS HONESTLY when unset, matching
* tests/integration/analytics-clickhouse.integration.test.ts. CI's
* `integration` job sets it from a service container and hard-fails if the
* suites skip, so this is not a self-skipping green in practice.
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { ClickHouseAnalyticsEngine } from "@/src/analytics/engine/clickhouse-engine";
import {
compileMetricQuery,
dimensionCatalogFrom,
restrictedTenantUserDdl,
} from "@/src/analytics/engine/query-compiler";
import { ANALYTICS_TABLES, sortingKeySql } from "@/src/analytics/engine/schema";
import { DEFAULT_BUDGETS } from "@/src/analytics/engine/resource-governance";
import type { AnalyticsIdentity } from "@/src/analytics/engine/siax-analytics-engine";
/**
* Raw events carry a 30-day TTL (src/analytics/engine/schema.ts). Fixed
* historical timestamps silently expire and make live-ClickHouse suites read
* 0 rows, so seed rows are stamped relative to now (UTC, ClickHouse
* DateTime64(3) text form).
*/
const SEED_EVENT_TIME = new Date(Date.now() - 2 * 3600_000).toISOString().replace("T", " ").replace("Z", "");
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_isolation_${Date.now().toString(36)}`;
const RESTRICTED_USER = `opt_iso_${Date.now().toString(36)}`;
const RESTRICTED_PW = `iso_pw_${Math.random().toString(36).slice(2, 12)}`;
const ALPHA: AnalyticsIdentity = { tenant_id: "t_alpha", project_id: "p_main", principal_id: "usr_alpha" };
const BETA: AnalyticsIdentity = { tenant_id: "t_beta", project_id: "p_main", principal_id: "usr_beta" };
const catalog = dimensionCatalogFrom({ severity: "severity" });
const ALL_TABLES: readonly string[] = ANALYTICS_TABLES;
/** Raw HTTP against the live server, as a named user. */
async function chQuery(
sql: string,
auth: string | undefined,
params: Record<string, string> = {},
settings: Record<string, string> = {},
body?: string,
): Promise<{ ok: boolean; status: number; text: string }> {
const url = new URL(CLICKHOUSE_URL ?? "http://skipped.invalid");
url.searchParams.set("query", sql);
for (const [k, v] of Object.entries(settings)) url.searchParams.set(k, v);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
const headers: Record<string, string> = {};
if (auth) headers["Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
const res = await fetch(url.toString(), { method: "POST", headers, body: body ?? "" });
return { ok: res.ok, status: res.status, text: await res.text() };
}
function rowsOf(text: string): { grp?: string; value: number }[] {
if (!text.trim()) return [];
const parsed = JSON.parse(text) as { data?: { grp?: string; value: number | string }[] };
return (parsed.data ?? []).map((r) => ({ ...(r.grp !== undefined ? { grp: r.grp } : {}), value: Number(r.value) }));
}
let engine: ClickHouseAnalyticsEngine;
run("BI-P011 tenant isolation against a LIVE ClickHouse", () => {
beforeAll(async () => {
engine = new ClickHouseAnalyticsEngine({
baseUrl: CLICKHOUSE_URL!,
basicAuth: CLICKHOUSE_AUTH,
database: DB,
dimensionCatalogs: { t_alpha: { severity: "severity" }, t_beta: { severity: "severity" } },
});
const health = await engine.health();
expect(health.healthy, `ClickHouse not healthy: ${health.detail ?? ""}`).toBe(true);
await engine.ensureSchema();
// Two tenants, deliberately different magnitudes so a leak is unmistakable
// in the NUMBER, not just in the row count.
const rows: string[] = [];
for (let i = 0; i < 50; i++) {
rows.push(
JSON.stringify({
tenant_id: "t_alpha",
project_id: "p_main",
dataset_id: "ds_shared",
metric: "rows_ingested",
event_id: `a${i}`,
event_time: SEED_EVENT_TIME,
value: 1,
dim_names: ["severity"],
dim_values: [i % 2 === 0 ? "warning" : "critical"],
}),
);
rows.push(
JSON.stringify({
tenant_id: "t_beta",
project_id: "p_main",
dataset_id: "ds_shared",
metric: "rows_ingested",
event_id: `b${i}`,
event_time: SEED_EVENT_TIME,
value: 1000,
dim_names: ["severity"],
dim_values: ["critical"],
}),
);
}
const ins = await chQuery(
`INSERT INTO ${DB}.opt_analytics_event FORMAT JSONEachRow`,
CLICKHOUSE_AUTH,
{},
{},
rows.join("\n"),
);
expect(ins.ok, `seed insert failed: ${ins.text.slice(0, 200)}`).toBe(true);
}, 120_000);
afterAll(async () => {
if (!CLICKHOUSE_URL) return;
// Disposable by construction: drop the user, its policies, and the DB.
for (const table of ANALYTICS_TABLES) {
await chQuery(`DROP ROW POLICY IF EXISTS ${RESTRICTED_USER}_${table}_rp ON ${DB}.${table}`, CLICKHOUSE_AUTH);
}
await chQuery(`DROP USER IF EXISTS ${RESTRICTED_USER}`, CLICKHOUSE_AUTH);
await chQuery(`DROP DATABASE IF EXISTS ${DB}`, CLICKHOUSE_AUTH);
}, 60_000);
// ── layer 2: the compiler ────────────────────────────────────────────────
it("HOLE, layer 2 REMOVED: the same query WITHOUT the forced predicate returns t_beta's rows to t_alpha", async () => {
// This is the exact statement the compiler would produce if someone
// deleted the forcing — proof that the predicate is doing real work
// against real data, not decorating a query that was safe anyway.
const unsafeSql =
`SELECT sum(value) AS value FROM ${DB}.opt_analytics_event ` +
`WHERE metric = {metric:String} LIMIT 1 FORMAT JSON`;
const res = await chQuery(unsafeSql, CLICKHOUSE_AUTH, { param_metric: "rows_ingested" });
expect(res.ok).toBe(true);
// 50*1 (alpha) + 50*1000 (beta) = 50050 — both tenants, one result.
expect(rowsOf(res.text)[0].value).toBe(50050);
});
it("CLOSED, layer 2 PRESENT: the compiled query returns t_alpha's 50 and never t_beta's 50000", async () => {
const result = await engine.executeMetric(ALPHA, { metric: "rows_ingested", aggregate: "sum" });
expect(result.rows[0].value).toBe(50);
const beta = await engine.executeMetric(BETA, { metric: "rows_ingested", aggregate: "sum" });
expect(beta.rows[0].value).toBe(50_000);
});
it("tenant A querying tenant B's dataset id gets ZERO rows, not B's rows", async () => {
const result = await engine.executeMetric(ALPHA, {
metric: "rows_ingested",
aggregate: "count",
dataset_id: "ds_shared",
});
expect(result.rows[0].value).toBe(50); // only alpha's 50, though beta shares the dataset id
});
it("a forged dataset id yields an empty result, never an error that leaks existence", async () => {
const result = await engine.executeMetric(ALPHA, {
metric: "rows_ingested",
aggregate: "count",
dataset_id: "ds_that_does_not_exist_or_belongs_to_someone_else",
});
expect(result.rows[0].value).toBe(0);
});
it("a tenant with no data at all sees zero, not everyone's aggregate", async () => {
const ghost: AnalyticsIdentity = { tenant_id: "t_gamma", project_id: "p_main", principal_id: "usr_g" };
const result = await engine.executeMetric(ghost, { metric: "rows_ingested", aggregate: "count" });
expect(result.rows[0].value).toBe(0);
});
it("group-by results carry only this tenant's dimension values", async () => {
const result = await engine.executeMetric(ALPHA, {
metric: "rows_ingested",
aggregate: "count",
group_by: ["severity"],
});
const total = result.rows.reduce((a, r) => a + r.value, 0);
expect(total).toBe(50);
// t_beta's rows are all "critical" with value 1000; if any leaked, the
// critical bucket would exceed alpha's 25.
const critical = result.rows.find((r) => r.groups?.severity === "critical");
expect(critical?.value).toBe(25);
});
it("SQL/dimension/filter injection through the live path changes nothing", async () => {
await expect(
engine.executeMetric(ALPHA, {
metric: "rows_ingested",
aggregate: "sum",
group_by: ["severity'; SELECT tenant_id FROM system.tables; --"],
}),
).rejects.toMatchObject({ code: "INVALID_REQUEST" });
// A hostile VALUE reaches the server as a bound parameter and simply
// matches nothing.
const injected = await engine.executeMetric(ALPHA, {
metric: "rows_ingested",
aggregate: "count",
filters: { severity: "warning' OR 1=1 --" },
});
expect(injected.rows[0].value).toBe(0);
// And the table is still there afterwards.
const still = await engine.executeMetric(ALPHA, { metric: "rows_ingested", aggregate: "count" });
expect(still.rows[0].value).toBe(50);
});
it("raw SQL attempt: the analyst-SQL surface is refused, not silently executed", async () => {
await expect(
engine.executeQuery(ALPHA, { sql: `SELECT * FROM ${DB}.opt_analytics_event`, dataset_ids: [] }),
).rejects.toMatchObject({ code: "CAPABILITY_UNAVAILABLE" });
});
// ── layer 3: restricted users + row policies ─────────────────────────────
it("HOLE, layer 3 ABSENT: an unrestricted user with no predicate sees every tenant", async () => {
const res = await chQuery(
`SELECT uniqExact(tenant_id) AS value FROM ${DB}.opt_analytics_event FORMAT JSON`,
CLICKHOUSE_AUTH,
);
expect(res.ok).toBe(true);
expect(rowsOf(res.text)[0].value).toBe(2); // t_alpha AND t_beta
});
it("CLOSED, layer 3 PRESENT: the restricted user runs the SAME predicate-free statement and sees ONE tenant", async () => {
for (const stmt of restrictedTenantUserDdl({
db: DB,
tenantId: "t_alpha",
userName: RESTRICTED_USER,
password: RESTRICTED_PW,
tables: ALL_TABLES,
})) {
const r = await chQuery(stmt, CLICKHOUSE_AUTH);
expect(r.ok, `DDL failed: ${stmt.slice(0, 80)} -> ${r.text.slice(0, 200)}`).toBe(true);
}
const restrictedAuth = `${RESTRICTED_USER}:${RESTRICTED_PW}`;
// The IDENTICAL statement that leaked above, now as the restricted user.
const res = await chQuery(
`SELECT uniqExact(tenant_id) AS value FROM ${DB}.opt_analytics_event FORMAT JSON`,
restrictedAuth,
);
expect(res.ok, res.text.slice(0, 300)).toBe(true);
expect(rowsOf(res.text)[0].value).toBe(1);
const sum = await chQuery(
`SELECT sum(value) AS value FROM ${DB}.opt_analytics_event FORMAT JSON`,
restrictedAuth,
);
expect(rowsOf(sum.text)[0].value).toBe(50); // alpha's total, not 50050
});
it("the restricted user cannot write, and cannot reach a table it was not granted", async () => {
const restrictedAuth = `${RESTRICTED_USER}:${RESTRICTED_PW}`;
const write = await chQuery(
`INSERT INTO ${DB}.opt_analytics_event FORMAT JSONEachRow`,
restrictedAuth,
{},
{},
JSON.stringify({ tenant_id: "t_beta", project_id: "p", dataset_id: "d", metric: "m", event_id: "x", event_time: SEED_EVENT_TIME, value: 1, dim_names: [], dim_values: [] }),
);
expect(write.ok).toBe(false);
const foreign = await chQuery(`SELECT count() FROM system.users FORMAT JSON`, restrictedAuth);
expect(foreign.ok).toBe(false);
});
// ── the structural precondition both layers rely on ──────────────────────
it("every analytics table's sorting key LEADS with tenant_id (what makes the predicate cheap)", async () => {
for (const table of ALL_TABLES) {
const res = await chQuery(sortingKeySql(DB, table), CLICKHOUSE_AUTH);
expect(res.ok).toBe(true);
expect(res.text.trim().startsWith("tenant_id"), `${table} sorting key: ${res.text.trim()}`).toBe(true);
}
});
it("the tenant value never appears in the statement text the server receives", async () => {
const compiled = compileMetricQuery(
{ tenant_id: "t_alpha", metric: "rows_ingested", aggregate: "sum" },
DB,
catalog,
DEFAULT_BUDGETS.INTERACTIVE.maxResultRows,
);
expect(compiled.sql).not.toContain("t_alpha");
const res = await chQuery(compiled.sql, CLICKHOUSE_AUTH, compiled.params);
expect(res.ok).toBe(true);
expect(rowsOf(res.text)[0].value).toBe(50);
});
});
@@ -0,0 +1,341 @@
/**
* tests/integration/bi-p103-slo-baseline.integration.test.ts
* ===========================================================
* BI-P103 — "Measured baselines exist."
*
* `src/analytics/slo/bi-slo.ts` said the first baselines were recorded in
* `evidence/bi-p103`. There was no `evidence/bi-p103`. The catalogue and the
* evaluator were both real and both well tested — against SYNTHETIC events.
* A synthetic event carries whatever duration the test author typed, so a
* suite built only on those proves the arithmetic and nothing about the
* system: it cannot tell you a dashboard query takes 8 ms or 8 s.
*
* So this harness produces the baselines from queries that actually ran:
*
* * ~120 COLD dashboard queries, each a different filter so the BI-P020
* cache genuinely misses, executed against a live ClickHouse;
* * the same ~120 again through the SAME shipped cache, now hitting, so
* `dash.p95_cached` is a measured cache path and not an assumption;
* * 220 exploration queries, enough for `explore.p99`'s min_samples of 200
* to be met rather than reported low-confidence.
*
* Every duration is wall-clock around the real call. The telemetry goes
* through the SHIPPED producer (`biUsageEventsForExecution`) and the SHIPPED
* evaluator (`evaluateBiSlos`) — not a copy — so the evidence is produced by
* the code under test.
*
* WHAT THE BASELINE DELIBERATELY DOES NOT CONTAIN. `dash.freshness`,
* `explore.timeout` and `report.delivery_sla` are not measurable from usage
* events and the evaluator says so; `report.completion_sla` has no producer in
* 0pt at all (nothing here emits `aud0.report_generated`). They appear in the
* evidence with their real status rather than being quietly dropped, because a
* baseline table that lists only the rows that worked is how an estate comes
* to believe it measures more than it does.
*
* These numbers describe THIS fixture on THIS machine against a local
* ClickHouse with warm page cache. They are a floor for the shape of the
* distribution, not a production SLA — and the evidence file says which parts
* are narrower than production: the cached path is the in-process reference
* cache rather than Valkey, every latency is the engine round trip with no
* HTTP or authorization layer around it, and there is no concurrency.
*
* CLICKHOUSE_URL=http://127.0.0.1:28123 CLICKHOUSE_AUTH=default:test \
* pnpm vitest run tests/integration/bi-p103-slo-baseline.integration.test.ts
*/
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { ClickHouseAnalyticsEngine } from '@/src/analytics/engine/clickhouse-engine';
import { InMemoryResultCache, type CacheKeyComponents } from '@/src/analytics/cache/query-cache';
import { compiledQueryHash } from '@/src/analytics/execution/query-execution-record';
import {
biUsageEventsForExecution,
type Aud0BiEvent,
type ExecutionTelemetry,
} from '@/src/analytics/slo/usage-events';
import { BI_SLO_CATALOGUE, evaluateBiSlos, summariseSloReport } from '@/src/analytics/slo/bi-slo';
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_p103_${Date.now().toString(36)}`;
const TENANT = 't_alpha';
const ROWS = 400_000;
const COLD_DASHBOARD_QUERIES = 120;
const EXPLORE_QUERIES = 220;
const headers: Record<string, string> = CLICKHOUSE_AUTH
? { Authorization: `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString('base64')}` }
: {};
async function ch(sql: string, body?: string): Promise<string> {
const url = new URL(CLICKHOUSE_URL ?? 'http://skipped.invalid');
url.searchParams.set('query', sql);
const res = await fetch(url.toString(), { method: 'POST', headers, body: body ?? '' });
const text = await res.text();
if (!res.ok) throw new Error(`ClickHouse ${res.status}: ${text.slice(0, 300)}`);
return text;
}
interface Measured {
rows: number;
ms: number;
}
/** One real round trip, wall-clock measured. */
async function timed(sql: string): Promise<Measured> {
const started = performance.now();
const text = await ch(`${sql} FORMAT JSON`);
const ms = performance.now() - started;
const parsed = JSON.parse(text) as { data: unknown[] };
return { rows: parsed.data.length, ms };
}
const events: Aud0BiEvent[] = [];
function record(t: ExecutionTelemetry): void {
events.push(...biUsageEventsForExecution(t));
}
function keyFor(i: number, cachedShape: string): CacheKeyComponents {
return {
tenant_id: TENANT,
dataset_id: 'ds_slo',
semantic_model_version: 1,
metric_versions: { m_amount: 1 },
compiled_query_hash: compiledQueryHash(cachedShape, { i: String(i) }),
data_snapshot: 'v1',
format: 'json',
};
}
let windowFrom: Date;
let windowTo: Date;
run('BI-P103 — measured baselines, from queries that actually ran', () => {
beforeAll(async () => {
await new ClickHouseAnalyticsEngine({
baseUrl: CLICKHOUSE_URL!,
basicAuth: CLICKHOUSE_AUTH,
database: DB,
dimensionCatalogs: { [TENANT]: { region: 'region' } },
}).ensureSchema();
// A fact table large enough that a scan is not free. Generated inside
// ClickHouse so the fixture cost is not measured as query latency.
await ch(
`CREATE TABLE ${DB}.slo_fact (tenant_id LowCardinality(String), region LowCardinality(String), ` +
`bucket UInt16, ts DateTime, amount Float64) ENGINE = MergeTree ORDER BY (tenant_id, bucket, ts)`,
);
await ch(
`INSERT INTO ${DB}.slo_fact SELECT 't_alpha', ['SE','NO','DK','FI'][(number % 4) + 1], ` +
`toUInt16(number % 500), toDateTime('2026-09-01 00:00:00') + (number % 86400), ` +
`toFloat64(number % 997) FROM numbers(${ROWS})`,
);
await ch(`OPTIMIZE TABLE ${DB}.slo_fact FINAL`);
}, 300_000);
afterAll(async () => {
if (CLICKHOUSE_URL) await ch(`DROP DATABASE IF EXISTS ${DB}`);
}, 60_000);
it('measures a cold and a cached dashboard path, and an exploration path', async () => {
windowFrom = new Date();
const cache = new InMemoryResultCache();
const shape = `SELECT region, sum(amount) FROM ${DB}.slo_fact WHERE tenant_id = ? AND bucket = ? GROUP BY region`;
// ── cold: every query a different bucket, so the cache genuinely misses ──
for (let i = 0; i < COLD_DASHBOARD_QUERIES; i++) {
const components = keyFor(i, shape);
const started = new Date().toISOString();
const before = await cache.get(components);
expect(before).toBeUndefined(); // a "cold" sample served from cache is not cold
const m = await timed(
`SELECT region, sum(amount) AS total FROM ${DB}.slo_fact ` +
`WHERE tenant_id = 't_alpha' AND bucket = ${i} GROUP BY region ORDER BY region`,
);
await cache.set(components, { rows: m.rows }, { ttlSeconds: 300, rowCount: m.rows });
record({
query_id: `q_cold_${i}`,
surface: 'dashboard',
dataset_id: 'ds_slo',
engine: 'clickhouse',
state: 'succeeded',
started_at: started,
finished_at: new Date().toISOString(),
duration_ms: m.ms,
row_count: m.rows,
cache_hit: false,
});
}
// ── cached: the same questions, through the same shipped cache ──────────
for (let i = 0; i < COLD_DASHBOARD_QUERIES; i++) {
const started = new Date().toISOString();
const t0 = performance.now();
const hit = await cache.get(keyFor(i, shape));
const ms = performance.now() - t0;
expect(hit).toBeDefined(); // a miss recorded as a hit would flatter the baseline
record({
query_id: `q_hot_${i}`,
surface: 'dashboard',
dataset_id: 'ds_slo',
engine: 'clickhouse',
state: 'succeeded',
started_at: started,
finished_at: new Date().toISOString(),
duration_ms: ms,
row_count: hit?.row_count ?? 0,
cache_hit: true,
});
}
// ── exploration: wider, ad-hoc shapes, enough samples for a real p99 ────
for (let i = 0; i < EXPLORE_QUERIES; i++) {
const started = new Date().toISOString();
const m = await timed(
`SELECT region, toStartOfHour(ts) AS h, sum(amount) AS total, count() AS n ` +
`FROM ${DB}.slo_fact WHERE tenant_id = 't_alpha' AND bucket >= ${i % 400} ` +
`GROUP BY region, h ORDER BY region, h LIMIT 5000`,
);
record({
query_id: `q_explore_${i}`,
surface: 'explore',
dataset_id: 'ds_slo',
engine: 'clickhouse',
state: 'succeeded',
started_at: started,
finished_at: new Date().toISOString(),
duration_ms: m.ms,
row_count: m.rows,
cache_hit: false,
});
}
windowTo = new Date();
expect(events.length).toBeGreaterThan(2 * (COLD_DASHBOARD_QUERIES * 2 + EXPLORE_QUERIES) - 1);
}, 600_000);
it('a REAL engine error becomes a failed event and moves the error rate', async () => {
// Proves the availability and error-rate paths are not measuring silence.
// Kept OUT of the baseline window so the recorded baseline describes the
// system's normal behaviour rather than a deliberately broken query.
const started = new Date().toISOString();
let code: string | undefined;
const t0 = performance.now();
try {
await ch(`SELECT no_such_column FROM ${DB}.slo_fact LIMIT 1 FORMAT JSON`);
} catch {
code = 'ENGINE_ERROR';
}
expect(code).toBe('ENGINE_ERROR');
const failed = biUsageEventsForExecution({
query_id: 'q_fail_1',
surface: 'dashboard',
dataset_id: 'ds_slo',
engine: 'clickhouse',
state: 'failed',
started_at: started,
finished_at: new Date().toISOString(),
duration_ms: performance.now() - t0,
error_code: code,
error_message: 'Unknown expression identifier no_such_column',
});
expect(failed.map((e) => e.event_type)).toContain('aud0.analytics_query_failed');
// The engine's message never becomes telemetry.
expect(JSON.stringify(failed)).not.toContain('no_such_column');
const withFailure = evaluateBiSlos({
events: [...events, ...failed],
from: windowFrom,
to: new Date(),
});
const availability = withFailure.results.find((r) => r.objective_id === 'dash.availability');
expect(availability?.sample_size).toBeGreaterThanOrEqual(100);
expect(availability?.observed).toBeLessThan(1);
});
it('writes the baseline, including every objective it could NOT measure', async () => {
const report = evaluateBiSlos({ events, from: windowFrom, to: windowTo });
const summary = summariseSloReport(report);
// The three latency objectives must be real numbers over real samples —
// an evidence file full of insufficient_data is not a baseline.
for (const id of ['dash.p95_first_query', 'dash.p95_cached', 'explore.p95', 'explore.p99']) {
const r = report.results.find((x) => x.objective_id === id);
expect(r?.observed, `${id} produced no number`).toBeTypeOf('number');
expect(r?.low_confidence, `${id} was computed from too few samples`).not.toBe(true);
}
// ...and the cached path must actually be faster than the cold one, or the
// two were not measuring different things.
const cold = report.results.find((r) => r.objective_id === 'dash.p95_first_query')?.observed ?? 0;
const cached = report.results.find((r) => r.objective_id === 'dash.p95_cached')?.observed ?? 0;
expect(cached).toBeLessThan(cold);
const dir = path.join(process.cwd(), 'evidence', 'bi-p103');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, 'baseline.json'),
`${JSON.stringify(
{
prompt: 'BI-P103',
title: 'First measured BI SLO baselines',
recorded_at: new Date().toISOString(),
host_note:
'One idle host, local ClickHouse, warm page cache, single-threaded client. A floor for the ' +
'shape of the distribution on this fixture — not a production SLA.',
clickhouse_version: JSON.parse(await ch('SELECT version() AS v FORMAT JSON')).data[0].v,
fixture: {
rows: ROWS,
table: 'slo_fact',
partitions: 'MergeTree ORDER BY (tenant_id, bucket, ts)',
},
workload: {
cold_dashboard_queries: COLD_DASHBOARD_QUERIES,
cached_dashboard_queries: COLD_DASHBOARD_QUERIES,
exploration_queries: EXPLORE_QUERIES,
report_queries: 0,
},
window: { from: windowFrom.toISOString(), to: windowTo.toISOString() },
catalogue_size: BI_SLO_CATALOGUE.length,
fully_measured: report.fully_measured,
unresolved_queries: report.unresolved_queries,
summary,
results: report.results.map((r) => ({
objective_id: r.objective_id,
workload: r.workload,
kind: r.kind,
status: r.status,
target: r.target,
unit: r.unit,
observed: r.observed,
sample_size: r.sample_size,
low_confidence: r.low_confidence ?? false,
detail: r.detail,
})),
measured_but_narrower_than_production: [
'dash.p95_cached is the IN-PROCESS reference cache (InMemoryResultCache). A Valkey ' +
'deployment adds a network round trip, so 0.03 ms here is a floor and not the number a ' +
'user will see.',
'Every latency is the ENGINE round trip only: no HTTP layer, no CL0UD authorization, no ' +
'serialization to the caller. The end-to-end p95 is larger by whatever those cost.',
'One tenant, one client, no concurrency. Contention is not represented.',
],
not_measured_and_why: [
'dash.freshness — a property of the DATASET (BI-P026 watermark), not of a usage event',
'explore.timeout — the configured BI-P012 ceiling, not an observation',
'report.completion_sla — nothing in 0pt emits aud0.report_generated yet, so the sample is 0',
"report.delivery_sla — delivery is N0TIFY's receipt; aud0 has no delivery event",
],
},
null,
2,
)}\n`,
);
// The file must be honest about the unmeasured half.
expect(report.fully_measured).toBe(false);
});
});
@@ -0,0 +1,344 @@
/**
* tests/integration/bi-p104-benchmark.integration.test.ts
* ========================================================
* BI-P104 — the benchmark itself, against real engines. Skips honestly when
* CLICKHOUSE_URL is unset; DuckDB additionally needs DUCKDB_PYTHON (an
* interpreter with the `duckdb` package), matching
* tests/duckdb/duckdb-provider.live.test.ts.
*
* Six dataset profiles, one representative question each, the same logical
* question on both engines. Deliberately NO engine-specific functions in the
* geospatial case (bounding box + grid arithmetic rather than each engine's
* GIS library) so the comparison is about the storage and execution engine
* rather than about who ships the nicer geo function.
*
* Statistics come from src/analytics/bench/benchmark-harness.ts — the shipped
* code, not a copy — so the evidence file is produced by the thing under test.
*
* Trino, Superset, native charts and Perspective are NOT exercised, and each
* appears in the evidence with its reason. An engine omitted from a benchmark
* table reads as a choice, so nothing is omitted.
*
* CLICKHOUSE_URL=http://127.0.0.1:28123 CLICKHOUSE_AUTH=default:test \
* DUCKDB_PYTHON=/path/to/venv/bin/python \
* pnpm vitest run tests/integration/bi-p104-benchmark.integration.test.ts
*
* It CREATEs and DROPs its own ClickHouse database and uses an in-memory
* DuckDB. Never point it at the b0ts ClickHouse or any quarantined data.
*/
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import {
buildEvidence,
compareDistributions,
describeComparison,
summarizeSamples,
type BenchDatasetId,
type BenchmarkRun,
type EngineAvailability,
} from '@/src/analytics/bench/benchmark-harness';
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
const DUCKDB_PYTHON = process.env.DUCKDB_PYTHON;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_p104_${Date.now().toString(36)}`;
const WARMUPS = 2;
const REPETITIONS = 9;
const WIDE_COLUMNS = 50;
const headers: Record<string, string> = CLICKHOUSE_AUTH
? { Authorization: `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString('base64')}` }
: {};
async function ch(query: string): Promise<string> {
const res = await fetch(CLICKHOUSE_URL ?? 'http://skipped.invalid', {
method: 'POST',
headers,
body: query,
});
const text = await res.text();
if (!res.ok) throw new Error(`ClickHouse ${res.status}: ${text.slice(0, 300)}`);
return text;
}
/** The six questions, one per profile, phrased for each engine. */
const QUERIES: Record<BenchDatasetId, { label: string; clickhouse: string; duckdb: string }> = {
small_saas: {
label: 'revenue by day',
clickhouse: `SELECT d, sum(amount) AS revenue, count() AS n FROM ${DB}.small_saas WHERE tenant_id='t_1' GROUP BY d ORDER BY d`,
duckdb: `SELECT d, sum(amount) AS revenue, count(*) AS n FROM small_saas WHERE tenant_id='t_1' GROUP BY d ORDER BY d`,
},
medium_business: {
label: 'revenue by month and region for one tenant',
clickhouse: `SELECT toStartOfMonth(d) AS m, region, sum(amount) AS revenue FROM ${DB}.medium_business WHERE tenant_id='t_2' GROUP BY m, region ORDER BY m, region`,
duckdb: `SELECT date_trunc('month', d) AS m, region, sum(amount) AS revenue FROM medium_business WHERE tenant_id='t_2' GROUP BY m, region ORDER BY m, region`,
},
vehiq_market: {
label: 'average asking price by make and model year',
clickhouse: `SELECT make, model_year, avg(price) AS avg_price, count() AS listings FROM ${DB}.vehiq_market WHERE mileage < 150000 GROUP BY make, model_year ORDER BY make, model_year`,
duckdb: `SELECT make, model_year, avg(price) AS avg_price, count(*) AS listings FROM vehiq_market WHERE mileage < 150000 GROUP BY make, model_year ORDER BY make, model_year`,
},
large_event: {
label: 'hourly event volume for one event type',
clickhouse: `SELECT toStartOfHour(ts) AS h, count() AS n, uniqExact(user_id) AS users FROM ${DB}.large_event WHERE event_type='checkout' GROUP BY h ORDER BY h`,
duckdb: `SELECT date_trunc('hour', ts) AS h, count(*) AS n, count(DISTINCT user_id) AS users FROM large_event WHERE event_type='checkout' GROUP BY h ORDER BY h`,
},
wide_table: {
label: 'three columns of fifty, grouped',
clickhouse: `SELECT grp, sum(c7) AS a, sum(c23) AS b, sum(c41) AS c FROM ${DB}.wide_table GROUP BY grp ORDER BY grp`,
duckdb: `SELECT grp, sum(c7) AS a, sum(c23) AS b, sum(c41) AS c FROM wide_table GROUP BY grp ORDER BY grp`,
},
geospatial: {
label: 'bounding box, aggregated to a grid cell',
clickhouse: `SELECT floor(lat*10)/10 AS cell_lat, floor(lon*10)/10 AS cell_lon, count() AS n FROM ${DB}.geospatial WHERE lat BETWEEN 57.5 AND 59.5 AND lon BETWEEN 11.5 AND 18.5 GROUP BY cell_lat, cell_lon ORDER BY cell_lat, cell_lon`,
duckdb: `SELECT floor(lat*10)/10 AS cell_lat, floor(lon*10)/10 AS cell_lon, count(*) AS n FROM geospatial WHERE lat BETWEEN 57.5 AND 59.5 AND lon BETWEEN 11.5 AND 18.5 GROUP BY cell_lat, cell_lon ORDER BY cell_lat, cell_lon`,
},
};
const CH_DDL: Array<[BenchDatasetId, string]> = [
[
'small_saas',
`CREATE TABLE ${DB}.small_saas ENGINE = MergeTree ORDER BY (tenant_id, d) AS
SELECT concat('t_', toString(number % 3)) AS tenant_id,
toDate('2026-01-01') + toIntervalDay(number % 365) AS d,
['free','pro','enterprise'][(number % 3) + 1] AS plan,
toDecimal64((number % 499) + 9, 2) AS amount
FROM numbers(100000)`,
],
[
'medium_business',
`CREATE TABLE ${DB}.medium_business ENGINE = MergeTree ORDER BY (tenant_id, d) AS
SELECT concat('t_', toString(number % 8)) AS tenant_id,
toDate('2025-01-01') + toIntervalDay(number % 730) AS d,
['SE','NO','DK','FI','DE'][(number % 5) + 1] AS region,
toDecimal64((number % 977) + 13, 2) AS amount
FROM numbers(2000000)`,
],
[
'vehiq_market',
`CREATE TABLE ${DB}.vehiq_market ENGINE = MergeTree ORDER BY (make, model_year) AS
SELECT ['Volvo','VW','Toyota','BMW','Kia','Tesla'][(number % 6) + 1] AS make,
toUInt16(2005 + (number % 20)) AS model_year,
toUInt32(30000 + (number % 900000)) AS price,
toUInt32((number * 7) % 400000) AS mileage,
['diesel','petrol','hybrid','electric'][(number % 4) + 1] AS fuel
FROM numbers(1000000)`,
],
[
'large_event',
`CREATE TABLE ${DB}.large_event ENGINE = MergeTree ORDER BY (event_type, ts) AS
SELECT toDateTime('2026-08-01 00:00:00') + toIntervalSecond(number % 2592000) AS ts,
toUInt32(number % 250000) AS user_id,
['view','click','checkout','signup'][(number % 4) + 1] AS event_type,
toFloat64(number % 1000) AS value
FROM numbers(5000000)`,
],
[
'wide_table',
`CREATE TABLE ${DB}.wide_table ENGINE = MergeTree ORDER BY grp AS
SELECT toUInt16(number % 500) AS grp,
${Array.from({ length: WIDE_COLUMNS }, (_, i) => `toFloat64((number + ${i}) % 1000) AS c${i}`).join(',\n ')}
FROM numbers(200000)`,
],
[
'geospatial',
`CREATE TABLE ${DB}.geospatial ENGINE = MergeTree ORDER BY (lat, lon) AS
SELECT 55.0 + (number % 10000) / 1000.0 AS lat,
10.0 + ((number * 13) % 10000) / 1000.0 AS lon,
toUInt32(number) AS point_id
FROM numbers(500000)`,
],
];
/** Runs all six DuckDB measurements inside ONE python process. */
const DUCKDB_PROGRAM = `
import duckdb, json, time, sys
con = duckdb.connect()
# The progress bar writes to STDOUT and corrupts the JSON transcript. It cost
# one run to find, so it is turned off explicitly rather than filtered out.
con.execute("SET enable_progress_bar=false")
WIDE = ${WIDE_COLUMNS}
wide_cols = ", ".join(f"(i + {j}) % 1000.0 AS c{j}" for j in range(WIDE))
ddl = {
"small_saas": "CREATE TABLE small_saas AS SELECT 't_' || (i % 3) AS tenant_id, DATE '2026-01-01' + INTERVAL (i % 365) DAY AS d, ['free','pro','enterprise'][(i % 3) + 1] AS plan, ((i % 499) + 9)::DECIMAL(18,2) AS amount FROM range(100000) t(i)",
"medium_business": "CREATE TABLE medium_business AS SELECT 't_' || (i % 8) AS tenant_id, DATE '2025-01-01' + INTERVAL (i % 730) DAY AS d, ['SE','NO','DK','FI','DE'][(i % 5) + 1] AS region, ((i % 977) + 13)::DECIMAL(18,2) AS amount FROM range(2000000) t(i)",
"vehiq_market": "CREATE TABLE vehiq_market AS SELECT ['Volvo','VW','Toyota','BMW','Kia','Tesla'][(i % 6) + 1] AS make, (2005 + (i % 20))::USMALLINT AS model_year, (30000 + (i % 900000))::UINTEGER AS price, ((i * 7) % 400000)::UINTEGER AS mileage, ['diesel','petrol','hybrid','electric'][(i % 4) + 1] AS fuel FROM range(1000000) t(i)",
"large_event": "CREATE TABLE large_event AS SELECT TIMESTAMP '2026-08-01 00:00:00' + INTERVAL (i % 2592000) SECOND AS ts, (i % 250000)::UINTEGER AS user_id, ['view','click','checkout','signup'][(i % 4) + 1] AS event_type, (i % 1000)::DOUBLE AS value FROM range(5000000) t(i)",
"wide_table": f"CREATE TABLE wide_table AS SELECT (i % 500)::USMALLINT AS grp, {wide_cols} FROM range(200000) t(i)",
"geospatial": "CREATE TABLE geospatial AS SELECT 55.0 + (i % 10000) / 1000.0 AS lat, 10.0 + ((i * 13) % 10000) / 1000.0 AS lon, i::UINTEGER AS point_id FROM range(500000) t(i)",
}
queries = json.loads(sys.stdin.read())
out = {"version": duckdb.__version__, "runs": {}}
for name, sql in ddl.items():
con.execute(sql)
for name, q in queries.items():
warm = []
for _ in range(${WARMUPS}):
t0 = time.perf_counter(); rows = con.execute(q).fetchall(); warm.append((time.perf_counter() - t0) * 1000)
samples = []
for _ in range(${REPETITIONS}):
t0 = time.perf_counter(); rows = con.execute(q).fetchall(); samples.append((time.perf_counter() - t0) * 1000)
out["runs"][name] = {"warmup_ms": warm, "samples_ms": samples, "rows": len(rows)}
sys.stdout.write("<<<BENCH>>>" + json.dumps(out))
`;
const runs: BenchmarkRun[] = [];
const engines: EngineAvailability[] = [];
let duckdbResult:
| { version: string; runs: Record<string, { warmup_ms: number[]; samples_ms: number[]; rows: number }> }
| undefined;
run('BI-P104 benchmark harness against real engines', () => {
beforeAll(async () => {
const version = (await ch('SELECT version()')).trim();
engines.push({ engine: 'clickhouse', available: true, version });
await ch(`CREATE DATABASE IF NOT EXISTS ${DB}`);
for (const [, ddl] of CH_DDL) await ch(ddl);
}, 900_000);
afterAll(async () => {
if (!CLICKHOUSE_URL) return;
try {
await ch(`DROP DATABASE IF EXISTS ${DB}`);
} finally {
const comparisons = duckdbResult
? (Object.keys(QUERIES) as BenchDatasetId[]).flatMap((dataset) => {
const chRun = runs.find((r) => r.engine === 'clickhouse' && r.dataset === dataset);
const duckRun = runs.find((r) => r.engine === 'duckdb' && r.dataset === dataset);
if (!chRun || !duckRun) return [];
const c = compareDistributions(chRun.distribution, duckRun.distribution);
return [
{
dataset,
query_label: QUERIES[dataset].label,
description: describeComparison(c, `duckdb vs clickhouse (${dataset})`),
...c,
},
];
})
: [];
const evidence = buildEvidence({
host_note:
'One idle host, warm caches, both engines local, single-threaded client. These numbers ' +
'describe these query shapes on this data on this machine. They are not engine rankings.',
engines,
runs,
comparisons,
});
const dir = path.join(process.cwd(), 'evidence/bi-p104');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'benchmark.json'), `${JSON.stringify(evidence, null, 2)}\n`);
}
}, 120_000);
it('measures all six dataset profiles on ClickHouse', async () => {
for (const dataset of Object.keys(QUERIES) as BenchDatasetId[]) {
const q = QUERIES[dataset];
const warmup_ms: number[] = [];
const samples_ms: number[] = [];
let rows = 0;
for (let i = 0; i < WARMUPS; i += 1) {
const t0 = performance.now();
await ch(`${q.clickhouse} FORMAT JSONCompact`);
warmup_ms.push(performance.now() - t0);
}
for (let i = 0; i < REPETITIONS; i += 1) {
const t0 = performance.now();
const text = await ch(`${q.clickhouse} FORMAT JSONCompact`);
samples_ms.push(performance.now() - t0);
rows = (JSON.parse(text) as { rows: number }).rows;
}
runs.push({
engine: 'clickhouse',
dataset,
query_label: q.label,
warmup_ms,
samples_ms,
distribution: summarizeSamples(samples_ms),
rows_returned: rows,
});
}
expect(runs.filter((r) => r.engine === 'clickhouse')).toHaveLength(6);
for (const r of runs) {
expect(r.distribution.n).toBe(REPETITIONS);
expect(r.distribution.stability).not.toBe('insufficient_samples');
}
}, 900_000);
it('measures the same six on DuckDB, or records why it did not', async () => {
if (!DUCKDB_PYTHON) {
engines.push({
engine: 'duckdb',
available: false,
reason: 'DUCKDB_PYTHON not set on this runner',
});
expect(engines.find((e) => e.engine === 'duckdb')?.reason).toBeTruthy();
return;
}
const payload = Object.fromEntries(
(Object.keys(QUERIES) as BenchDatasetId[]).map((d) => [d, QUERIES[d].duckdb]),
);
const stdout = execFileSync(DUCKDB_PYTHON, ['-c', DUCKDB_PROGRAM], {
input: JSON.stringify(payload),
encoding: 'utf8',
maxBuffer: 32 * 1024 * 1024,
timeout: 900_000,
});
// Parse from the sentinel: anything DuckDB writes to stdout before it
// (a progress bar, a warning) must not be able to corrupt the transcript.
const marker = stdout.lastIndexOf('<<<BENCH>>>');
expect(marker, 'duckdb transcript marker missing').toBeGreaterThanOrEqual(0);
duckdbResult = JSON.parse(stdout.slice(marker + '<<<BENCH>>>'.length));
engines.push({ engine: 'duckdb', available: true, version: duckdbResult!.version });
for (const [dataset, r] of Object.entries(duckdbResult!.runs)) {
runs.push({
engine: 'duckdb',
dataset: dataset as BenchDatasetId,
query_label: QUERIES[dataset as BenchDatasetId].label,
warmup_ms: r.warmup_ms,
samples_ms: r.samples_ms,
distribution: summarizeSamples(r.samples_ms),
rows_returned: r.rows,
});
}
expect(runs.filter((r) => r.engine === 'duckdb')).toHaveLength(6);
}, 900_000);
it('records the engines BI-P104 names that nothing measured, with reasons', () => {
engines.push(
{
engine: 'trino',
available: false,
reason:
'a Trino is running on this host but belongs to another lane (st0re-verify-trino); ' +
'benchmarking through someone else’s container would measure their configuration',
},
{
engine: 'semantic_query',
available: false,
reason: 'MetricFlow has never been executed in 0pt (BI-P029 honest status)',
},
{ engine: 'superset', available: false, reason: 'no Superset deployment in the estate yet' },
{ engine: 'native_charts', available: false, reason: 'render-side; DES1GN owns it (BI-P051..P057)' },
{ engine: 'perspective', available: false, reason: 'not deployed' },
);
const evidence = buildEvidence({ host_note: 'x', engines, runs });
for (const e of evidence.not_exercised) expect(e.reason, e.engine).toBeTruthy();
expect(evidence.engines).toHaveLength(7);
});
it('reports every comparison as a range with its stability, never a bare figure', () => {
if (!duckdbResult) return;
for (const dataset of Object.keys(QUERIES) as BenchDatasetId[]) {
const a = runs.find((r) => r.engine === 'clickhouse' && r.dataset === dataset)!;
const b = runs.find((r) => r.engine === 'duckdb' && r.dataset === dataset)!;
const sentence = describeComparison(compareDistributions(a.distribution, b.distribution), dataset);
expect(sentence).toMatch(/n=9\/9/);
expect(sentence).toMatch(/INDISTINGUISHABLE|x to /);
}
});
});
@@ -0,0 +1,244 @@
/**
* tests/integration/data-quality-clickhouse.integration.test.ts
* ==============================================================
* BI-P025 — the native quality provider against a live ClickHouse.
*
* The unit suite proves the provider's LOGIC (an empty dataset is a failure, a
* missing dbt result is a failure). This suite proves the part a fake runner
* cannot: that the compiled expressions are valid ClickHouse and count the
* right rows, including the empty-dataset case where a real engine returns
* zero violations over zero rows and every naive implementation reports green.
*
* It also re-proves BI-P011's forced tenant predicate on this path: a quality
* run executes on an ADMINISTRATIVE credential (it must read the base table),
* so if the predicate were missing here, one tenant's dirty rows would
* quarantine another tenant's projection.
*
* Gated on CLICKHOUSE_URL. With the variable set and the server down, this
* suite FAILS rather than skipping.
*/
import fs from 'node:fs';
import path from 'node:path';
import { beforeAll, describe, expect, it } from 'vitest';
import { NativeQualityProvider, type QualityRuleSpec } from '@/src/analytics/quality/quality-provider';
import { ClickHouseQualityRunner } from '@/src/analytics/quality/clickhouse-quality-runner';
import { InMemoryQuarantineStore, QualityGate } from '@/src/analytics/quality/quarantine';
const BASE_URL = process.env.CLICKHOUSE_URL ?? '';
const AUTH = process.env.CLICKHOUSE_AUTH ?? 'default:';
const suite = BASE_URL ? describe : describe.skip;
const DB = 'opt_quality_test';
const EVIDENCE_PATH = path.join(process.cwd(), 'evidence/bi-p025/native-quality-live.json');
async function admin(sql: string): Promise<{ ok: boolean; body: string }> {
const url = new URL(BASE_URL);
url.searchParams.set('query', sql);
const res = await fetch(url.toString(), {
method: 'POST',
headers: { Authorization: `Basic ${Buffer.from(AUTH).toString('base64')}` },
body: '',
signal: AbortSignal.timeout(60_000),
});
return { ok: res.ok, body: await res.text() };
}
const runner = new ClickHouseQualityRunner({
baseUrl: BASE_URL || 'http://unset',
basicAuth: AUTH,
database: DB,
tables: { ds_sales: 'sales', ds_empty: 'empty_sales' },
});
const provider = new NativeQualityProvider(runner);
const evidence: Record<string, unknown> = {};
function rule(over: Partial<QualityRuleSpec>): QualityRuleSpec {
return {
rule_id: 'q1',
tenant_id: 't_alpha',
dataset_id: 'ds_sales',
rule: 'not_null',
field: 'customer',
severity: 'block',
params: {},
...over,
};
}
beforeAll(async () => {
if (!BASE_URL) return;
const v = await admin('SELECT version()');
if (!v.ok) throw new Error('CLICKHOUSE_URL is set but ClickHouse is not answering');
evidence.clickhouse_version = v.body.trim();
evidence.recorded_at = new Date().toISOString();
await admin(`DROP DATABASE IF EXISTS ${DB}`);
await admin(`CREATE DATABASE ${DB}`);
await admin(
`CREATE TABLE ${DB}.sales (tenant_id String, dataset_id String, customer String, amount Float64, ` +
`channel String, event_time DateTime) ENGINE = MergeTree ORDER BY (tenant_id, event_time)`,
);
await admin(
`CREATE TABLE ${DB}.empty_sales (tenant_id String, dataset_id String, customer String, amount Float64, ` +
`channel String, event_time DateTime) ENGINE = MergeTree ORDER BY (tenant_id, event_time)`,
);
// t_alpha: 100 clean rows, then deliberate defects.
await admin(
`INSERT INTO ${DB}.sales SELECT 't_alpha', 'ds_sales', 'cust_' || toString(number), number, 'web', now() ` +
`FROM numbers(100)`,
);
// 5 rows with an empty customer (the not_null violation).
await admin(
`INSERT INTO ${DB}.sales SELECT 't_alpha', 'ds_sales', '', number, 'web', now() FROM numbers(5)`,
);
// 3 rows out of range (amount > 1000).
await admin(
`INSERT INTO ${DB}.sales SELECT 't_alpha', 'ds_sales', 'big_' || toString(number), 5000, 'web', now() ` +
`FROM numbers(3)`,
);
// 4 rows with an unaccepted channel.
await admin(
`INSERT INTO ${DB}.sales SELECT 't_alpha', 'ds_sales', 'ch_' || toString(number), 1, 'carrier_pigeon', now() ` +
`FROM numbers(4)`,
);
// 6 rows sharing two duplicate keys (3 each) — the unique violation.
await admin(
`INSERT INTO ${DB}.sales SELECT 't_alpha', 'ds_sales', 'dup_' || toString(number % 2), number, 'web', now() ` +
`FROM numbers(6)`,
);
// t_beta: FILTHY. Every rule fails here. If the tenant predicate is missing,
// t_alpha's counts jump and this tenant quarantines the other one.
await admin(
`INSERT INTO ${DB}.sales SELECT 't_beta', 'ds_sales', '', 999999, 'carrier_pigeon', now() FROM numbers(500)`,
);
}, 120_000);
suite('BI-P025 live — the compiled expressions are valid SQL and count the right rows', () => {
it("not_null finds exactly the 5 empty-customer rows, out of t_alpha's 118", async () => {
const verdict = await provider.evaluate(rule({ rule: 'not_null', field: 'customer' }));
expect(verdict.evaluated_rows).toBe(118);
expect(verdict.violation_count).toBe(5);
expect(verdict.passed).toBe(false);
evidence.not_null = { evaluated: verdict.evaluated_rows, violations: verdict.violation_count };
});
it('range finds exactly the 3 rows over the maximum', async () => {
const verdict = await provider.evaluate(
rule({ rule: 'range', field: 'amount', params: { min: 0, max: 1000 } }),
);
expect(verdict.violation_count).toBe(3);
evidence.range = { violations: verdict.violation_count };
});
it('distribution finds exactly the 4 rows outside the accepted values', async () => {
const verdict = await provider.evaluate(
rule({ rule: 'distribution', field: 'channel', params: { accepted_values: ['web', 'retail'] } }),
);
expect(verdict.violation_count).toBe(4);
evidence.distribution = { violations: verdict.violation_count };
});
it('unique counts ROWS sitting on a duplicated key, not the number of keys', async () => {
const verdict = await provider.evaluate(rule({ rule: 'unique', field: 'customer' }));
// 11, and the arithmetic is worth writing down because the first version
// of this test asserted 6 and the engine disagreed:
// * `dup_0` and `dup_1` appear 3 times each -> 6 rows
// * the five EMPTY customers are all the same key '' -> 5 rows
// The empty strings are duplicates of one another, so `not_null` and
// `unique` overlap on the same defect. That is the engine being right and
// the fixture arithmetic being wrong, not a rule that over-counts.
expect(verdict.violation_count).toBe(11);
evidence.unique = {
violations: verdict.violation_count,
breakdown: '6 rows on dup_0/dup_1, plus 5 rows sharing the empty-string key',
};
});
it('freshness finds no violation for rows written just now', async () => {
const verdict = await provider.evaluate(
rule({ rule: 'freshness', params: { timestamp_field: 'event_time', max_age_seconds: 3600 } }),
);
expect(verdict.violation_count).toBe(0);
expect(verdict.passed).toBe(true);
});
it('a hostile accepted-value is bound, not executed', async () => {
const verdict = await provider.evaluate(
rule({
rule: 'distribution',
field: 'channel',
params: { accepted_values: ['web', 'retail', "'); DROP TABLE sales; --"] },
}),
);
expect(verdict.violation_count).toBe(4);
// The table is still there, with its rows.
const after = await admin(`SELECT count() FROM ${DB}.sales`);
expect(Number(after.body.trim())).toBe(618);
});
});
suite('BI-P025 live — the EMPTY dataset false green, against a real engine', () => {
it('a real ClickHouse returns 0 violations over 0 rows, and the provider calls it a FAILURE', async () => {
// The counterfactual first: the raw counts genuinely look clean.
const raw = await runner.count({
tenant_id: 't_alpha',
dataset_id: 'ds_empty',
violationExpression: "customer IS NULL OR customer = ''",
params: {},
});
expect(raw).toEqual({ violations: 0, evaluated: 0 });
// A naive implementation reports green here. This one does not.
const verdict = await provider.evaluate(rule({ dataset_id: 'ds_empty' }));
expect(verdict.passed).toBe(false);
expect(verdict.detail).toContain('EMPTY');
evidence.empty_dataset = {
raw_counts_from_clickhouse: raw,
verdict_passed: verdict.passed,
note: 'a real engine returns zero violations over zero rows; the provider refuses to call that a pass',
};
});
});
suite("BI-P025 live — a quality run cannot read another tenant's rows", () => {
it("t_alpha's counts are unaffected by t_beta's 500 filthy rows", async () => {
const all = await admin(`SELECT count() FROM ${DB}.sales`);
expect(Number(all.body.trim())).toBe(618); // 118 alpha + 500 beta
const alpha = await provider.evaluate(
rule({ tenant_id: 't_alpha', rule: 'not_null', field: 'customer' }),
);
const beta = await provider.evaluate(rule({ tenant_id: 't_beta', rule: 'not_null', field: 'customer' }));
expect(alpha.evaluated_rows).toBe(118);
expect(alpha.violation_count).toBe(5);
expect(beta.evaluated_rows).toBe(500);
expect(beta.violation_count).toBe(500);
evidence.tenant_isolation = {
base_table_rows: 618,
alpha_evaluated: alpha.evaluated_rows,
alpha_violations: alpha.violation_count,
beta_evaluated: beta.evaluated_rows,
beta_violations: beta.violation_count,
};
});
it("t_beta's blocking failure quarantines t_beta only", async () => {
const gate = new QualityGate(new InMemoryQuarantineStore());
const beta = await provider.evaluate(rule({ tenant_id: 't_beta', rule: 'not_null', field: 'customer' }));
await gate.apply('t_beta', 'ds_sales', [beta]);
await expect(gate.assertProjectionReadable('t_beta', 'ds_sales')).rejects.toThrow(/QUARANTINED/);
await expect(gate.assertProjectionReadable('t_alpha', 'ds_sales')).resolves.toBeUndefined();
});
it('refuses a dataset with no registered physical table rather than guessing one', async () => {
await expect(provider.evaluate(rule({ dataset_id: 'ds_unregistered' }))).rejects.toThrow();
});
it('writes the evidence file', () => {
fs.mkdirSync(path.dirname(EVIDENCE_PATH), { recursive: true });
fs.writeFileSync(EVIDENCE_PATH, `${JSON.stringify(evidence, null, 2)}\n`);
expect(fs.existsSync(EVIDENCE_PATH)).toBe(true);
});
});
@@ -0,0 +1,348 @@
/**
* tests/integration/materialization-drift-clickhouse.integration.test.ts
* =======================================================================
* BI-P105 against a LIVE ClickHouse. Skips honestly when CLICKHOUSE_URL is
* unset; with it set and the server down, it FAILS rather than skipping.
*
* BI-P105's DoD is "performance improvement measured and freshness semantics
* documented", and both halves are done here against real data rather than
* asserted. What the DoD does not say, and what this file is really about, is
* that a pre-aggregate fails SILENTLY: it answers instantly and wrongly.
*
* The drill drives a real ClickHouse materialized view through the exact
* sequence that produces a confident wrong number in production:
*
* 1. 2M source rows, a SummingMergeTree target and a materialized view.
* 2. Backfill, verify with the SHIPPED detector: verdict `match`.
* 3. Measure both paths repeatedly, and report the DISTRIBUTION — a single
* speed-up figure quoted as a system property is misleading (BI-P104).
* 4. `ALTER TABLE ... DELETE` on the source: a GDPR erasure, the single most
* common real cause of pre-aggregate drift. A ClickHouse materialized
* view is an INSERT trigger; it does not see mutations, so the target
* keeps the deleted revenue forever and nothing errors.
* 5. The detector must catch it, and `selectQuerySource` must refuse to
* serve. The counterfactual — a router that checks only staleness — is
* run on the same state and MUST serve, with the wrong number recorded
* in kronor.
*
* Everything measured lands in evidence/bi-p105/materialization-drift.json.
*
* docker run -d --name ch -p 28123:8123 -e CLICKHOUSE_PASSWORD=test \
* clickhouse/clickhouse-server:26.3
* CLICKHOUSE_URL=http://127.0.0.1:28123 CLICKHOUSE_AUTH=default:test \
* pnpm vitest run tests/integration/materialization-drift-clickhouse.integration.test.ts
*
* It CREATEs and DROPs its own database. Never point it at the b0ts
* ClickHouse or any quarantined market data.
*/
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import {
applyDriftReport,
detectDrift,
type AggregateBucket,
type DriftReport,
} from '@/src/analytics/materialization/drift-detector';
import {
materializationStaleness,
selectQuerySource,
type MaterializationSpec,
type MaterializationStatus,
} from '@/src/analytics/materialization/materialization';
import type { AnalyticsQueryRequest } from '@/src/analytics/contract/query-request';
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_p105_${Date.now().toString(36)}`;
const ROWS = 2_000_000;
const REPETITIONS = 9;
const headers: Record<string, string> = CLICKHOUSE_AUTH
? { Authorization: `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString('base64')}` }
: {};
async function ch(query: string): Promise<string> {
const res = await fetch(CLICKHOUSE_URL ?? 'http://skipped.invalid', {
method: 'POST',
headers,
body: query,
});
const text = await res.text();
if (!res.ok) throw new Error(`ClickHouse ${res.status}: ${text.slice(0, 400)}`);
return text;
}
/** Rows as buckets keyed "date|region", which is what the detector compares. */
async function bucketsFrom(query: string): Promise<AggregateBucket[]> {
const text = await ch(`${query} FORMAT JSONEachRow`);
return text
.trim()
.split('\n')
.filter(Boolean)
.map((line) => {
const r = JSON.parse(line) as { d: string; region: string; revenue: number; orders: number };
return { key: `${r.d}|${r.region}`, values: { revenue: Number(r.revenue), orders: Number(r.orders) } };
});
}
/** Median and the spread around it. A single number is not a system property. */
function distribution(samples: number[]): {
n: number;
min: number;
p50: number;
p95: number;
max: number;
spread_ratio: number;
} {
const s = [...samples].sort((a, b) => a - b);
const at = (q: number) => s[Math.min(s.length - 1, Math.floor(q * s.length))];
return {
n: s.length,
min: s[0],
p50: at(0.5),
p95: at(0.95),
max: s[s.length - 1],
spread_ratio: Number((s[s.length - 1] / Math.max(s[0], 1e-9)).toFixed(2)),
};
}
async function timeQuery(query: string): Promise<number> {
const t0 = performance.now();
await ch(`${query} FORMAT JSONEachRow`);
return performance.now() - t0;
}
const SOURCE_AGG = `
SELECT toString(order_date) AS d, region, sum(amount) AS revenue, count() AS orders
FROM ${DB}.sales WHERE tenant_id = 't_alpha' GROUP BY d, region ORDER BY d, region`;
const TARGET_AGG = `
SELECT toString(order_date) AS d, region, sum(revenue) AS revenue, sum(orders) AS orders
FROM ${DB}.sales_daily WHERE tenant_id = 't_alpha' GROUP BY d, region ORDER BY d, region`;
const SPEC: MaterializationSpec = {
materialization_id: 'mv_sales_daily',
tenant_id: 't_alpha',
project_id: 'p_main',
dataset: 'ds_sales',
strategy: 'clickhouse_materialized_view',
target_ref: `${DB}.sales_daily`,
metrics: ['revenue', 'orders'],
dimensions: ['order_date', 'region'],
time_dimension: 'order_date',
grain: 'day',
max_staleness_seconds: 3600,
drift_check_interval_seconds: 86_400,
tolerance: { absolute: 0.5, relative: 0.0001 },
};
const REQUEST: AnalyticsQueryRequest = {
dataset: 'ds_sales',
metrics: ['revenue'],
dimensions: ['order_date'],
filters: [],
timeRange: { grain: 'day' },
};
const evidence: Record<string, unknown> = {};
let status: MaterializationStatus;
run('BI-P105 materialization against a LIVE ClickHouse', () => {
beforeAll(async () => {
evidence.clickhouse_version = (await ch('SELECT version()')).trim();
evidence.recorded_at = new Date().toISOString();
evidence.source_rows = ROWS;
await ch(`CREATE DATABASE IF NOT EXISTS ${DB}`);
await ch(`
CREATE TABLE ${DB}.sales (
tenant_id LowCardinality(String),
order_date Date,
region LowCardinality(String),
customer_id UInt32,
amount Decimal(18, 2)
) ENGINE = MergeTree ORDER BY (tenant_id, order_date, region)`);
await ch(`
INSERT INTO ${DB}.sales
SELECT
if(number % 5 = 0, 't_beta', 't_alpha') AS tenant_id,
toDate('2026-08-01') + toIntervalDay(number % 30) AS order_date,
['SE','NO','DK','FI'][(number % 4) + 1] AS region,
toUInt32(number % 5000) AS customer_id,
toDecimal64((number % 977) + 13, 2) AS amount
FROM numbers(${ROWS})`);
await ch(`
CREATE TABLE ${DB}.sales_daily (
tenant_id LowCardinality(String),
order_date Date,
region LowCardinality(String),
revenue Decimal(38, 2),
orders UInt64
) ENGINE = SummingMergeTree ORDER BY (tenant_id, order_date, region)`);
await ch(`
CREATE MATERIALIZED VIEW ${DB}.sales_daily_mv TO ${DB}.sales_daily AS
SELECT tenant_id, order_date, region, sum(amount) AS revenue, count() AS orders
FROM ${DB}.sales GROUP BY tenant_id, order_date, region`);
// The MV is an INSERT trigger: it saw nothing that was already there, so
// the backfill is explicit. (This is drift cause #1, and it is why the
// first check below has to be able to fail.)
await ch(`
INSERT INTO ${DB}.sales_daily
SELECT tenant_id, order_date, region, sum(amount) AS revenue, count() AS orders
FROM ${DB}.sales GROUP BY tenant_id, order_date, region`);
await ch(`OPTIMIZE TABLE ${DB}.sales_daily FINAL`);
status = {
materialization_id: SPEC.materialization_id,
state: 'serving',
data_watermark: new Date().toISOString(),
last_refresh_at: new Date().toISOString(),
};
}, 300_000);
afterAll(async () => {
if (!CLICKHOUSE_URL) return;
try {
await ch(`DROP DATABASE IF EXISTS ${DB}`);
} finally {
const dir = path.join(process.cwd(), 'evidence/bi-p105');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, 'materialization-drift.json'),
`${JSON.stringify(evidence, null, 2)}\n`,
);
}
}, 60_000);
it('the freshly backfilled aggregate MATCHES its source', async () => {
const report = detectDrift({
fromSource: await bucketsFrom(SOURCE_AGG),
fromAggregate: await bucketsFrom(TARGET_AGG),
tolerance: SPEC.tolerance,
metrics: ['revenue', 'orders'],
});
expect(report.buckets_compared).toBeGreaterThan(0); // an empty compare proves nothing
expect(report.verdict).toBe('match');
status = applyDriftReport(status, report);
evidence.after_backfill = {
verdict: report.verdict,
buckets_compared: report.buckets_compared,
revenue_total: report.totals.revenue,
};
}, 120_000);
it('measures the improvement as a DISTRIBUTION, not a single number', async () => {
const base: number[] = [];
const agg: number[] = [];
for (let i = 0; i < REPETITIONS; i += 1) {
// Interleaved so a machine that gets busy halfway through penalises both.
base.push(await timeQuery(SOURCE_AGG));
agg.push(await timeQuery(TARGET_AGG));
}
const baseD = distribution(base);
const aggD = distribution(agg);
evidence.performance = {
note:
'ClickHouse caches marks and pages between repetitions, so these are WARM numbers on one host ' +
'with nothing else running. They describe this shape of query on this data, not a system property.',
repetitions: REPETITIONS,
base_table_ms: baseD,
pre_aggregate_ms: aggD,
speedup_p50: Number((baseD.p50 / Math.max(aggD.p50, 1e-9)).toFixed(1)),
speedup_range_min_max: [
Number((baseD.min / Math.max(aggD.max, 1e-9)).toFixed(1)),
Number((baseD.max / Math.max(aggD.min, 1e-9)).toFixed(1)),
],
};
// The claim under test is only that the pre-aggregate is not SLOWER; the
// magnitude is reported, never asserted as a threshold.
expect(aggD.p50).toBeLessThanOrEqual(baseD.p50);
}, 300_000);
it('a GDPR erasure on the source DRIFTS the aggregate, and the drift is caught', async () => {
const before = await bucketsFrom(TARGET_AGG);
// The mutation a right-to-erasure request produces. A materialized view is
// an insert trigger — it never sees this.
await ch(
`ALTER TABLE ${DB}.sales DELETE WHERE tenant_id = 't_alpha' AND customer_id < 250 SETTINGS mutations_sync = 2`,
);
const fromSource = await bucketsFrom(SOURCE_AGG);
const fromAggregate = await bucketsFrom(TARGET_AGG);
expect(fromAggregate).toEqual(before); // the aggregate genuinely did not move
const report: DriftReport = detectDrift({
fromSource,
fromAggregate,
tolerance: SPEC.tolerance,
metrics: ['revenue', 'orders'],
});
expect(report.verdict).toBe('drifted');
expect(report.worst).toBeDefined();
const drifted = applyDriftReport(status, report);
const guarded = selectQuerySource({ request: REQUEST, spec: SPEC, status: drifted, now: new Date() });
expect(guarded.source).toBe('base_table');
// COUNTERFACTUAL: a router that checks only staleness serves it, and this
// is the number a dashboard would have shown.
const stalenessOnlyServes =
(materializationStaleness(drifted, new Date()) ?? 0) <= SPEC.max_staleness_seconds;
expect(stalenessOnlyServes).toBe(true);
evidence.gdpr_erasure_drill = {
mutation: "ALTER TABLE sales DELETE WHERE tenant_id='t_alpha' AND customer_id < 250",
verdict: report.verdict,
buckets_compared: report.buckets_compared,
revenue_true_after_erasure: report.totals.revenue.source,
revenue_pre_aggregate_would_report: report.totals.revenue.aggregate,
revenue_overstatement: report.totals.revenue.delta,
revenue_overstatement_pct: Number(
((report.totals.revenue.delta / report.totals.revenue.source) * 100).toFixed(3),
),
worst_bucket: report.worst,
guarded_router_decision: guarded,
staleness_only_router_would_serve: stalenessOnlyServes,
staleness_seconds_at_decision: materializationStaleness(drifted, new Date()),
note:
'The aggregate was NOT stale by any clock: it had just been refreshed, and every freshness check ' +
'passed. Only the source comparison caught it. This is why staleness alone is not a correctness ' +
'guarantee.',
};
status = drifted;
}, 300_000);
it('and a refresh that re-derives the aggregate clears the drift', async () => {
await ch(`TRUNCATE TABLE ${DB}.sales_daily`);
await ch(`
INSERT INTO ${DB}.sales_daily
SELECT tenant_id, order_date, region, sum(amount) AS revenue, count() AS orders
FROM ${DB}.sales GROUP BY tenant_id, order_date, region`);
await ch(`OPTIMIZE TABLE ${DB}.sales_daily FINAL`);
const report = detectDrift({
fromSource: await bucketsFrom(SOURCE_AGG),
fromAggregate: await bucketsFrom(TARGET_AGG),
tolerance: SPEC.tolerance,
metrics: ['revenue', 'orders'],
});
expect(report.verdict).toBe('match');
const healed: MaterializationStatus = applyDriftReport(
{ ...status, state: 'serving', data_watermark: new Date().toISOString() },
report,
);
const decision = selectQuerySource({ request: REQUEST, spec: SPEC, status: healed, now: new Date() });
expect(decision.source).toBe('materialization');
evidence.after_rebuild = {
verdict: report.verdict,
revenue_total: report.totals.revenue,
routing: decision,
};
}, 300_000);
});
@@ -0,0 +1,259 @@
/**
* tests/integration/query-cancellation-budget.integration.test.ts
* ================================================================
* BI-P019 (cancellation) and BI-P021 (cost/budget) against a live ClickHouse.
*
* Both prompts are only real if something ACTUALLY STOPS. So both are tested
* by starting a genuine CPU bomb and requiring the server to stop working:
*
* * the query must disappear from `system.processes`;
* * `system.query_log` must record it as ExceptionWhileProcessing with
* ClickHouse code 394 (QUERY_WAS_CANCELLED) — the server's own account of
* what happened, not ours;
* * and the COUNTERFACTUAL must hold: an identical bomb left alone for the
* same interval is still running. Without that, "the query was gone after
* we cancelled it" is equally consistent with "the query was short".
*
* BI-P021's in-flight enforcement gets the same treatment: a tenant window
* budget of one million rows, a query that scans far more, and the requirement
* that the enforcer cancels it MID-FLIGHT with `rows_read` already non-zero —
* i.e. it was running, it was observed running, and it was stopped.
*
* Gated on CLICKHOUSE_URL. With the variable set and the server down, this
* suite FAILS; it does not degrade to a skip.
*/
import fs from 'node:fs';
import path from 'node:path';
import { beforeAll, describe, expect, it } from 'vitest';
import { ClickHouseProcessControl } from '@/src/analytics/execution/clickhouse-process-control';
import { cancelAndVerify, cancelOrThrow } from '@/src/analytics/execution/cancellation';
import {
DEFAULT_QUERY_BUDGET,
InMemoryWindowStore,
QueryBudgetEnforcer,
} from '@/src/analytics/cost/query-budget';
const BASE_URL = process.env.CLICKHOUSE_URL ?? '';
const AUTH = process.env.CLICKHOUSE_AUTH ?? 'default:';
const suite = BASE_URL ? describe : describe.skip;
const EVIDENCE_PATH = path.join(process.cwd(), 'evidence/bi-p019-p021/cancellation-and-budget.json');
/** Big enough that it cannot finish inside any of the windows below. */
const BOMB = 'SELECT sum(number) AS s FROM numbers_mt(200000000000)';
interface Res {
ok: boolean;
status: number;
body: string;
}
async function send(sql: string, opts: { queryId?: string; timeoutMs?: number } = {}): Promise<Res> {
const url = new URL(BASE_URL);
url.searchParams.set('query', sql);
if (opts.queryId) url.searchParams.set('query_id', opts.queryId);
try {
const res = await fetch(url.toString(), {
method: 'POST',
headers: { Authorization: `Basic ${Buffer.from(AUTH).toString('base64')}` },
body: '',
signal: AbortSignal.timeout(opts.timeoutMs ?? 120_000),
});
return { ok: res.ok, status: res.status, body: await res.text() };
} catch (e) {
return { ok: false, status: 0, body: String(e) };
}
}
/** Fire and forget: the bomb runs on the server while the test carries on. */
function launch(queryId: string): Promise<Res> {
return send(BOMB, { queryId, timeoutMs: 120_000 });
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const control = new ClickHouseProcessControl({ baseUrl: BASE_URL || 'http://unset', basicAuth: AUTH });
const evidence: Record<string, unknown> = {};
async function waitUntilRunning(queryId: string, timeoutMs = 10_000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (await control.isRunning(queryId)) return true;
await sleep(50);
}
return false;
}
/** ClickHouse's own verdict, from its query log. 394 = QUERY_WAS_CANCELLED. */
async function queryLogVerdict(
queryId: string,
): Promise<{ type: string; exception_code: number } | undefined> {
await send('SYSTEM FLUSH LOGS');
const res = await send(
`SELECT type, exception_code FROM system.query_log WHERE query_id = '${queryId}' ` +
`AND type != 'QueryStart' ORDER BY event_time_microseconds DESC LIMIT 1 FORMAT JSON`,
);
if (!res.ok) return undefined;
const row = (JSON.parse(res.body) as { data: Array<{ type: string; exception_code: number | string }> })
.data[0];
return row ? { type: row.type, exception_code: Number(row.exception_code) } : undefined;
}
beforeAll(async () => {
if (!BASE_URL) return;
const v = await send('SELECT version()');
if (!v.ok) throw new Error(`CLICKHOUSE_URL is set but ClickHouse is not answering: ${v.status}`);
evidence.clickhouse_version = v.body.trim();
evidence.recorded_at = new Date().toISOString();
}, 60_000);
suite('BI-P019 — cancellation stops an expensive query, and it is VERIFIED', () => {
it('counterfactual: an identical bomb left alone is still running after the same interval', async () => {
const queryId = `opt_cf_${Date.now()}`;
void launch(queryId);
expect(await waitUntilRunning(queryId)).toBe(true);
await sleep(2_000);
const stillRunning = await control.isRunning(queryId);
evidence.counterfactual_still_running_after_2s = stillRunning;
expect(stillRunning, 'the bomb finished on its own — it is not expensive enough to prove anything').toBe(
true,
);
// Clean up, and incidentally exercise the same path.
await cancelAndVerify(control, queryId, { timeoutMs: 10_000 });
}, 90_000);
it("cancellation is observed to stop it, and ClickHouse's own log agrees", async () => {
const queryId = `opt_cancel_${Date.now()}`;
void launch(queryId);
expect(await waitUntilRunning(queryId)).toBe(true);
// Let it accumulate real work so "it stopped" is a statement about a
// running query, not about one that had barely begun.
await sleep(1_000);
const progressBefore = await control.progress(queryId);
expect(progressBefore?.rows_read ?? 0).toBeGreaterThan(0);
const outcome = await cancelAndVerify(control, queryId, { timeoutMs: 10_000, pollIntervalMs: 100 });
expect(outcome.kill_accepted).toBe(true);
expect(outcome.verified_stopped, 'the query outlived its cancellation deadline').toBe(true);
expect(outcome.already_finished).toBe(false);
expect(outcome.elapsed_ms).toBeLessThan(10_000);
expect(await control.isRunning(queryId)).toBe(false);
const verdict = await queryLogVerdict(queryId);
evidence.cancellation = {
rows_read_before_cancel: progressBefore?.rows_read,
elapsed_ms_to_verified_stop: outcome.elapsed_ms,
verified_stopped: outcome.verified_stopped,
clickhouse_query_log_type: verdict?.type,
clickhouse_exception_code: verdict?.exception_code,
};
// 394 = QUERY_WAS_CANCELLED. The server saying it, not us.
expect(verdict?.exception_code, `query_log verdict was ${JSON.stringify(verdict)}`).toBe(394);
}, 90_000);
it('cancelling a query that already finished reports already_finished, not a false stop', async () => {
const queryId = `opt_done_${Date.now()}`;
const res = await send('SELECT 1', { queryId });
expect(res.ok).toBe(true);
const outcome = await cancelAndVerify(control, queryId, { timeoutMs: 2_000 });
expect(outcome.already_finished).toBe(true);
expect(outcome.verified_stopped).toBe(true);
});
it('cancelOrThrow raises when the query is not observed to stop in time', async () => {
const queryId = `opt_deadline_${Date.now()}`;
void launch(queryId);
expect(await waitUntilRunning(queryId)).toBe(true);
// A deadline shorter than ClickHouse can plausibly unwind in, with the
// kill request suppressed so the query genuinely keeps running. The
// point is that the module REPORTS a failure to stop rather than
// returning a cheerful boolean.
const noKill = {
engine: 'clickhouse',
isRunning: (id: string) => control.isRunning(id),
requestKill: async () => false,
progress: (id: string) => control.progress(id),
};
await expect(cancelOrThrow(noKill, queryId, { timeoutMs: 300, pollIntervalMs: 50 })).rejects.toThrow(
/not observed to stop/,
);
await cancelAndVerify(control, queryId, { timeoutMs: 10_000 });
}, 90_000);
});
suite('BI-P021 — the budget actually stops a running query', () => {
it('an in-flight window breach cancels the query mid-scan, with the cancellation verified', async () => {
const store = new InMemoryWindowStore();
const settled: unknown[] = [];
const enforcer = new QueryBudgetEnforcer({
budget: { ...DEFAULT_QUERY_BUDGET, maxRowsScanned: 1_000_000, maxCostUnits: 1e9 },
store,
ledger: { record: (e) => void settled.push(e) },
control,
enforceInFlight: true,
pollIntervalMs: 100,
storeIsShared: false,
});
const queryId = `opt_budget_${Date.now()}`;
void launch(queryId);
expect(await waitUntilRunning(queryId)).toBe(true);
const outcome = await enforcer.enforceInFlight('t_alpha', queryId);
expect(outcome.terminated, 'the budget watched the query run past its window and did nothing').toBe(true);
expect(outcome.reason).toBe('rows');
// It was RUNNING when it was stopped — not stopped before it started.
expect(outcome.observed.rows_read).toBeGreaterThan(1_000_000);
expect(outcome.cancellation?.verified_stopped).toBe(true);
expect(await control.isRunning(queryId)).toBe(false);
const verdict = await queryLogVerdict(queryId);
expect(verdict?.exception_code).toBe(394);
await enforcer.settle({
tenant_id: 't_alpha',
principal_id: 'u_1',
query_id: queryId,
cost: {
rows_scanned: outcome.observed.rows_read,
bytes_scanned: outcome.observed.bytes_read,
execution_ms: outcome.observed.elapsed_ms,
engine: 'clickhouse',
},
terminated_by_budget: true,
});
expect(settled).toHaveLength(1);
evidence.budget_in_flight = {
budget_max_rows_scanned: 1_000_000,
observed_rows_read_at_cancel: outcome.observed.rows_read,
observed_elapsed_ms_at_cancel: outcome.observed.elapsed_ms,
polls_before_breach: outcome.polls,
overshoot_factor: Math.round(outcome.observed.rows_read / 1_000_000),
overshoot_note:
'in-flight enforcement is granular to the poll interval; the query overshot the window ' +
'by this factor before the poll that caught it. A bound, not a hard cap.',
cancellation_verified: outcome.cancellation?.verified_stopped,
clickhouse_exception_code: verdict?.exception_code,
charged_for_work_done_before_cancel: true,
};
}, 120_000);
it('admission-only mode reports itself as advisory rather than as a control', () => {
const enforcer = new QueryBudgetEnforcer({
budget: DEFAULT_QUERY_BUDGET,
store: new InMemoryWindowStore(),
ledger: { record: () => undefined },
enforceInFlight: false,
});
const described = enforcer.describeEnforcement();
expect(described.binding).toBe(false);
expect(described.in_flight).toContain('NOT ENFORCED');
evidence.advisory_posture_is_declared = described;
});
it('writes the evidence file', () => {
fs.mkdirSync(path.dirname(EVIDENCE_PATH), { recursive: true });
fs.writeFileSync(EVIDENCE_PATH, `${JSON.stringify(evidence, null, 2)}\n`);
expect(fs.existsSync(EVIDENCE_PATH)).toBe(true);
});
});
@@ -0,0 +1,117 @@
import fs from "node:fs";
import path from "node:path";
import postgres from "postgres";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { closeRepositorySqlForTests, getRepositorySql } from "@/src/repositories/db";
import { PostgresSearchDefinitionRepository } from "@/src/repositories/search-definition-repository";
import { HttpOpenSearchAdapter } from "@/src/search/opensearch-adapter";
import { SearchService, type DocumentSource } from "@/src/search/search-service";
import type { SearchDocument } from "@/src/search/search-types";
const OPENSEARCH_URL = process.env.OPENSEARCH_URL;
const DATABASE_URL = process.env.SEARCH_DEFINITION_TEST_DATABASE_URL;
const run = OPENSEARCH_URL && DATABASE_URL ? describe : describe.skip;
let admin: ReturnType<typeof postgres> | undefined;
let reachable = false;
let reason = "";
beforeAll(async () => {
if (!OPENSEARCH_URL || !DATABASE_URL) return;
try {
admin = postgres(DATABASE_URL, { max: 1, prepare: false, onnotice: () => undefined });
await admin`SELECT 1`;
await admin.unsafe(fs.readFileSync(path.join(process.cwd(), "sql", "013_search_index_definitions.sql"), "utf8"));
const health = await new HttpOpenSearchAdapter({ baseUrl: OPENSEARCH_URL }).health();
if (!(["green", "yellow"] as string[]).includes(health.status)) throw new Error(`OpenSearch ${health.status}`);
reachable = true;
} catch (error) {
reason = error instanceof Error ? error.message : String(error);
}
}, 30_000);
afterAll(async () => {
await admin?.end({ timeout: 5 });
await closeRepositorySqlForTests();
});
run("durable SearchDefinitionRepository + live OpenSearch", () => {
it("reloads a definition after a fresh SearchService and rebuilds/querys the projection", async (ctx) => {
if (!reachable) {
console.warn(`[realinfra] search durable definition dependencies unavailable (${reason}) — skipping honestly`);
ctx.skip();
return;
}
const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`.replace(/[^a-z0-9_]/gi, "_");
const indexName = `companies_${stamp}`.slice(0, 60);
const tenant = `t_${stamp}`;
const repo = new PostgresSearchDefinitionRepository(getRepositorySql(DATABASE_URL!));
const adapter = new HttpOpenSearchAdapter({ baseUrl: OPENSEARCH_URL! });
const writer = new SearchService(adapter, { definitionRepository: repo });
await writer.registerIndexDefinitionDurable({
index_name: indexName,
version: 1,
fields: { name: "text", org_nr: "keyword" },
default_search_fields: ["name"],
}, "realinfra-test");
// New instance, empty in-memory cache — this is the restart condition.
const reader = new SearchService(adapter, { definitionRepository: repo });
const loaded = await reader.resolveIndexDefinition(indexName);
expect(loaded.version).toBe(1);
expect(loaded.fields.name).toBe("text");
const docs: SearchDocument[] = [{
doc_id: "company-1",
tenant_id: tenant,
purpose_tags: ["company_enrichment"],
rights_tags: ["internal"],
source_refs: ["0pt:dataset:companies@1"],
payload: { name: "Acme Aktiebolag", org_nr: "5560000000" },
}];
const source: DocumentSource = {
name: "0pt:dataset:companies@1",
async *iterate() { for (const doc of docs) yield doc; },
};
const rebuilt = await reader.rebuild(indexName, source, { tenant_id: tenant });
expect(rebuilt.docs_indexed).toBe(1);
expect(rebuilt.switched).toBe(true);
const result = await reader.query(indexName, {
tenant_id: tenant,
purpose: "company_enrichment",
rights_tag: "internal",
text: "Acme",
});
expect(result.total).toBe(1);
expect(result.hits[0].doc_id).toBe("company-1");
// A foreign tenant sees no hit even though it queries the same physical alias.
const foreign = await reader.query(indexName, {
tenant_id: `foreign_${tenant}`,
purpose: "company_enrichment",
rights_tag: "internal",
text: "Acme",
});
expect(foreign.total).toBe(0);
});
it("enforces sequential schema versions and rejects same-version drift", async (ctx) => {
if (!reachable) return ctx.skip();
const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`.replace(/[^a-z0-9_]/gi, "_");
const indexName = `schema_${stamp}`.slice(0, 60);
const repo = new PostgresSearchDefinitionRepository(getRepositorySql(DATABASE_URL!));
const v1 = { index_name: indexName, version: 1, fields: { name: "text" as const }, default_search_fields: ["name"] };
const first = await repo.save(v1, "test");
const replay = await repo.save(v1, "test");
expect(first.created).toBe(true);
expect(replay.created).toBe(false);
expect(replay.created_at).toBe(first.created_at);
await expect(repo.save({ ...v1, fields: { name: "keyword" } }, "test")).rejects.toMatchObject({ code: "CONFLICT" });
await expect(repo.save({ ...v1, version: 3 }, "test")).rejects.toMatchObject({ code: "CONFLICT" });
expect((await repo.save({ ...v1, version: 2 }, "test")).definition.version).toBe(2);
});
});
@@ -0,0 +1,172 @@
/**
* REAL OpenSearch integration test (Master-DoD §48 "Mocks alone count as
* insufficient", §50 Integration level) for the Search capability.
*
* Runs against a live OpenSearch named by OPENSEARCH_URL (CI: a service
* container; locally: `docker run -e discovery.type=single-node
* -e DISABLE_SECURITY_PLUGIN=true opensearchproject/opensearch:2.11.1`).
* Without OPENSEARCH_URL the suite SKIPS HONESTLY — it never fabricates a
* pass (same convention as tests/p0/iceberg-write-service.realinfra.test.ts).
*
* What it proves against the real engine:
* - index creation with 0pt envelope mappings + bulk indexing
* - tenant isolation and purpose/rights filtering through real queries
* - generation rebuild + atomic alias switch + rollback (§42)
* - full projection-disaster recovery: delete EVERYTHING, rebuild from
* the canonical source, identical results (§68-style, scoped to 0pt)
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { HttpOpenSearchAdapter } from "@/src/search/opensearch-adapter";
import { SearchService, type DocumentSource } from "@/src/search/search-service";
import type { SearchDocument } from "@/src/search/search-types";
const OPENSEARCH_URL = process.env.OPENSEARCH_URL;
const run = OPENSEARCH_URL ? describe : describe.skip;
const INDEX = `itest-${Date.now().toString(36)}`;
const DOCS: SearchDocument[] = [
{
doc_id: "c1",
tenant_id: "t_alpha",
purpose_tags: ["company_enrichment"],
rights_tags: ["internal", "customer_deliverable"],
source_refs: ["0pt:source:src_bolagsverket"],
payload: { name: "Volvo Personvagnar AB", org_nr: "5561074967", employees: 20000 },
},
{
doc_id: "c2",
tenant_id: "t_alpha",
purpose_tags: ["compliance"],
rights_tags: ["internal"],
payload: { name: "Volvo Lastvagnar AB", org_nr: "5560135508", employees: 15000 },
},
{
doc_id: "c3",
tenant_id: "t_beta",
purpose_tags: ["company_enrichment"],
rights_tags: ["internal"],
payload: { name: "Volvo Cars Retail", org_nr: "5569999999", employees: 300 },
},
];
function source(docs: SearchDocument[]): DocumentSource {
return {
name: "itest:canonical-array",
async *iterate() {
yield* docs;
},
};
}
run("Search capability against a LIVE OpenSearch", () => {
// The skip-variant still evaluates this callback body, so the constructor
// must tolerate the env-less case (the tests themselves never run then).
const adapter = new HttpOpenSearchAdapter({ baseUrl: OPENSEARCH_URL ?? "http://skipped.invalid" });
const search = new SearchService(adapter);
beforeAll(async () => {
const health = await adapter.health();
expect(["green", "yellow"]).toContain(health.status);
search.registerIndexDefinition({
index_name: INDEX,
version: 1,
fields: { name: "text", org_nr: "keyword", employees: "long" },
default_search_fields: ["name"],
});
}, 30_000);
afterAll(async () => {
for (const idx of await adapter.listIndices(`opt-${INDEX}--g*`)) {
await adapter.deleteIndex(idx);
}
});
it("rebuild g1 from canonical source; alias serves it", async () => {
const result = await search.rebuild(INDEX, source(DOCS));
expect(result.new_generation).toBe(1);
expect(result.docs_indexed).toBe(3);
expect(result.switched).toBe(true);
const state = await search.generationState(INDEX);
expect(state.active_generation).toBe(1);
}, 60_000);
it("REAL tenant isolation: t_alpha never sees t_beta documents", async () => {
const alpha = await search.query(INDEX, {
tenant_id: "t_alpha",
purpose: "company_enrichment",
text: "volvo",
});
expect(alpha.hits.map((h) => h.doc_id)).toEqual(["c1"]); // c2 wrong purpose, c3 wrong tenant
const beta = await search.query(INDEX, {
tenant_id: "t_beta",
purpose: "company_enrichment",
text: "volvo",
});
expect(beta.hits.map((h) => h.doc_id)).toEqual(["c3"]);
// Cross-tenant attack shape: a filter cannot break out of the tenant term.
const attack = await search.query(INDEX, {
tenant_id: "t_beta",
purpose: "company_enrichment",
filters: { org_nr: "5561074967" }, // t_alpha's org_nr
});
expect(attack.total).toBe(0);
});
it("purpose + rights filtering hold on the real engine", async () => {
const compliance = await search.query(INDEX, { tenant_id: "t_alpha", purpose: "compliance" });
expect(compliance.hits.map((h) => h.doc_id)).toEqual(["c2"]);
const deliverable = await search.query(INDEX, {
tenant_id: "t_alpha",
purpose: "company_enrichment",
rights_tag: "customer_deliverable",
});
expect(deliverable.hits.map((h) => h.doc_id)).toEqual(["c1"]);
});
it("generation rebuild + switch + rollback (§42)", async () => {
const updated = DOCS.map((d) =>
d.doc_id === "c1" ? { ...d, payload: { ...d.payload, name: "Volvo Personvagnar AB (uppdaterad)" } } : d
);
const r2 = await search.rebuild(INDEX, source(updated));
expect(r2.new_generation).toBe(2);
let res = await search.query(INDEX, { tenant_id: "t_alpha", purpose: "company_enrichment", text: "uppdaterad" });
expect(res.total).toBe(1);
// Rollback to g1 — the old generation still exists and serves the alias.
await search.switchGeneration(INDEX, 1);
res = await search.query(INDEX, { tenant_id: "t_alpha", purpose: "company_enrichment", text: "uppdaterad" });
expect(res.total).toBe(0);
await search.switchGeneration(INDEX, 2);
}, 60_000);
it("projection disaster: delete ALL generations, rebuild from canonical, results identical (§68)", async () => {
for (const idx of await adapter.listIndices(`opt-${INDEX}--g*`)) {
await adapter.deleteIndex(idx);
}
expect(await adapter.listIndices(`opt-${INDEX}--g*`)).toEqual([]);
const rebuilt = await search.rebuild(INDEX, source(DOCS));
expect(rebuilt.docs_indexed).toBe(3);
const res = await search.query(INDEX, { tenant_id: "t_alpha", purpose: "company_enrichment", text: "volvo" });
expect(res.hits.map((h) => h.doc_id)).toEqual(["c1"]);
}, 60_000);
it("incremental indexDocuments into the active generation", async () => {
const out = await search.indexDocuments(INDEX, [
{
doc_id: "c4",
tenant_id: "t_alpha",
purpose_tags: ["company_enrichment"],
rights_tags: ["internal"],
payload: { name: "Polestar Performance AB", org_nr: "5568100000", employees: 2500 },
},
]);
expect(out.indexed).toBe(1);
const state = await search.generationState(INDEX);
await adapter.refresh(search.physicalIndexFor(INDEX, state.active_generation!));
const res = await search.query(INDEX, { tenant_id: "t_alpha", purpose: "company_enrichment", text: "polestar" });
expect(res.total).toBe(1);
});
});
@@ -0,0 +1,487 @@
/**
* tests/integration/semantic-parity.integration.test.ts
* ======================================================
* BI-P029 — the parity test `src/analytics/metrics/semantic-provider.ts` has
* been citing.
*
* IT DID NOT EXIST. The provider's header named this path as the proof of the
* one DoD surface it claimed was closed, and `providerReadiness().proven`
* asserted that "0pt's metric compiler and an independent spec-driven renderer
* return the same number for the golden metric against live ClickHouse data".
* Nothing in the repository executed that comparison. A citation to a file
* that is not there is the same failure as a green check that gates nothing:
* it survives review because the sentence reads like evidence.
*
* So this file is the comparison, run for real:
*
* PATH A parseAnalyticsQueryRequest -> resolveAnalyticsQuery ->
* compileRequestToClickHouse -> live ClickHouse.
* PATH B the same ResolvedQuery -> compileRequestToSemantic ->
* MetricFlowProvider.compile -> `renderIndependently` below, which
* reads ONLY the provider's structured query object and the registry
* model, writes its own SQL with its own quoting, and shares no line
* of code with compile-clickhouse.ts -> the same live ClickHouse.
*
* The two paths must return the same numbers. `renderIndependently` inlines
* literals where compile-clickhouse binds parameters, groups by the physical
* column expression rather than by a compiler alias, and orders in SQL rather
* than by alias — so the SQL strings genuinely differ, and the test asserts
* that they do. Two identical strings would make the parity claim vacuous.
*
* WHAT THIS STILL DOES NOT PROVE, and `providerReadiness()` still says so:
* MetricFlow itself is not executed here (no Python runtime is provisioned for
* this repo), and neither the Superset path nor the AI Analyst path is
* compared. Three of BI-P029's four DoD surfaces remain open. This closes the
* first one honestly rather than closing all four by assertion.
*
* CLICKHOUSE_URL=http://127.0.0.1:28123 CLICKHOUSE_AUTH=default:test \
* pnpm vitest run tests/integration/semantic-parity.integration.test.ts
*
* It CREATEs and DROPs its own database. Never point it at the b0ts
* ClickHouse or at any quarantined dataset.
*/
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { ClickHouseAnalyticsEngine } from '@/src/analytics/engine/clickhouse-engine';
import {
parseAnalyticsQueryRequest,
queryResolutionFrom,
resolveAnalyticsQuery,
type ResolvedQuery,
} from '@/src/analytics/contract/query-request';
import { compileRequestToClickHouse } from '@/src/analytics/contract/compile-clickhouse';
import { compileRequestToSemantic } from '@/src/analytics/contract/compile-semantic';
import { MetricFlowProvider } from '@/src/analytics/metrics/semantic-provider';
import {
InMemorySemanticModelStore,
SemanticModelRegistry,
type SemanticModelVersion,
} from '@/src/analytics/metrics/semantic-registry';
import type { MetricSpec } from '@/src/analytics/metrics/metric-model';
/**
* Raw events carry a 30-day TTL (src/analytics/engine/schema.ts). Fixed
* historical timestamps silently expire and make live-ClickHouse suites read
* 0 rows, so seed rows are stamped relative to now (UTC, ClickHouse
* DateTime64(3) text form).
*/
const SEED_EVENT_TIME = new Date(Date.now() - 2 * 3600_000).toISOString().replace("T", " ").replace("Z", "");
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL;
const CLICKHOUSE_AUTH = process.env.CLICKHOUSE_AUTH;
// Collection-time, never inside a hook: `describe.skipIf(flagSetInBeforeAll)`
// evaluates its flag before any hook has run and therefore skips ALWAYS.
const run = CLICKHOUSE_URL ? describe : describe.skip;
const DB = `opt_parity_${Date.now().toString(36)}`;
const TENANT = 't_alpha';
const PROJECT = 'p_main';
/**
* The golden metric. It carries a DEFINITION FILTER (`channel != 'internal'`)
* on purpose: a metric whose meaning is only "sum this column" cannot tell a
* parity test anything, because every compiler agrees about a bare sum. The
* business meaning of net revenue is that internal transfers are not revenue,
* and that meaning has to survive both compile paths or the two paths are
* answering different questions with the same metric id.
*/
const REVENUE: MetricSpec = {
id: 'm_revenue',
name: 'net_revenue',
description: 'Invoiced revenue net of credit notes, in SEK, recognised on invoice date.',
type: 'simple',
measure: 'amount_sek',
aggregation: 'sum',
dimensions: ['country', 'channel'],
filters: [{ dimension: 'channel', operator: 'ne', values: ['internal'] }],
timeDimension: 'invoiced_at',
unit: 'SEK',
currency: 'SEK',
format: 'currency',
owner: 'finance@siax.io',
version: 3,
status: 'ACTIVE',
};
/** dimension name -> the key stored in `dim_names`. One mapping, both paths. */
const FIELD_OF: Record<string, string> = { country: 'country_code', channel: 'sales_channel' };
function semanticModel(version = 1): Omit<SemanticModelVersion, 'hash'> {
return {
model_id: 'sm_sales',
version,
tenant_id: TENANT,
datasets: ['ds_sales'],
relationships: [],
metrics: [REVENUE],
dimensions: [
{ id: 'd_country', name: 'country', dataset_id: 'ds_sales', kind: 'categorical' },
{ id: 'd_channel', name: 'channel', dataset_id: 'ds_sales', kind: 'categorical' },
{ id: 'd_invoiced', name: 'invoiced_at', dataset_id: 'ds_sales', kind: 'time' },
],
valid_from: '2026-09-01T00:00:00Z',
status: 'draft',
};
}
/**
* The fixture. Deliberately arranged so that dropping the metric's definition
* filter changes the answer for EVERY country — a fixture where internal rows
* happen to sum to zero would let a broken compiler pass.
*/
const ROWS: Array<{ country: string; channel: string; amount: number }> = [
{ country: 'SE', channel: 'direct', amount: 1000 },
{ country: 'SE', channel: 'partner', amount: 250 },
{ country: 'SE', channel: 'internal', amount: 9999 },
{ country: 'NO', channel: 'direct', amount: 400 },
{ country: 'NO', channel: 'internal', amount: 7777 },
{ country: 'DK', channel: 'partner', amount: 125.5 },
{ country: 'DK', channel: 'internal', amount: 3333 },
];
/** What the metric MEANS, computed in TypeScript, independent of any SQL. */
const EXPECTED: Record<string, number> = ROWS.filter((r) => r.channel !== 'internal').reduce(
(acc, r) => ({ ...acc, [r.country]: (acc[r.country] ?? 0) + r.amount }),
{} as Record<string, number>,
);
interface ChRow {
[column: string]: string | number;
}
async function chQuery(sql: string, params: Record<string, string> = {}): Promise<ChRow[]> {
const url = new URL(CLICKHOUSE_URL ?? 'http://skipped.invalid');
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
const headers: Record<string, string> = {};
if (CLICKHOUSE_AUTH) headers.Authorization = `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString('base64')}`;
const res = await fetch(url.toString(), { method: 'POST', headers, body: sql });
const text = await res.text();
if (!res.ok) throw new Error(`ClickHouse ${res.status}: ${text.slice(0, 400)}`);
if (!text.trim()) return [];
return (JSON.parse(text) as { data: ChRow[] }).data;
}
async function chExec(sql: string, body?: string): Promise<void> {
const url = new URL(CLICKHOUSE_URL ?? 'http://skipped.invalid');
url.searchParams.set('query', sql);
const headers: Record<string, string> = {};
if (CLICKHOUSE_AUTH) headers.Authorization = `Basic ${Buffer.from(CLICKHOUSE_AUTH).toString('base64')}`;
const res = await fetch(url.toString(), { method: 'POST', headers, body: body ?? '' });
if (!res.ok) throw new Error(`ClickHouse ${res.status}: ${(await res.text()).slice(0, 400)}`);
}
// ── PATH B: the independent renderer ───────────────────────────────────────
/** Single-quote escaping, written here because this renderer shares nothing. */
function lit(value: string): string {
return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
}
function predicate(field: string, operator: string, values: string[]): string {
const lhs = `dim_values[indexOf(dim_names, ${lit(field)})]`;
switch (operator) {
case 'eq':
return `${lhs} = ${lit(values[0])}`;
case 'ne':
return `${lhs} <> ${lit(values[0])}`;
case 'in':
return `${lhs} IN (${values.map(lit).join(',')})`;
case 'not_in':
return `${lhs} NOT IN (${values.map(lit).join(',')})`;
default:
throw new Error(`independent renderer does not implement operator ${operator}`);
}
}
/**
* Render the provider's structured query into SQL, reading ONLY that object
* and the registry model. It never sees the ResolvedQuery, the ClickHouse
* compiler's output, or its parameter map.
*
* The aggregate is deliberately expressed differently from compile-clickhouse:
* a `sum(if(...))` rather than a `sumIf(...)`, grouped by the raw expression
* rather than by an alias. Same arithmetic, different SQL — which is the only
* way the comparison means anything.
*/
function renderIndependently(
compiled: ReturnType<MetricFlowProvider['compile']>,
model: SemanticModelVersion,
): string {
const query = compiled.query as {
metrics: string[];
group_by: string[];
where: Array<{ dimension: string; operator: string; values: string[] }>;
limit: number;
metric_filters?: Record<string, Array<{ dimension: string; operator: string; values: string[] }>>;
};
const byId = new Map(model.metrics.map((m) => [m.id, m]));
const selects: string[] = [];
const groups: string[] = [];
for (const dimension of query.group_by) {
const expr = `dim_values[indexOf(dim_names, ${lit(FIELD_OF[dimension])})]`;
selects.push(`${expr} AS ${dimension}`);
groups.push(expr);
}
for (const metricId of query.metrics) {
const spec = byId.get(metricId);
if (!spec) throw new Error(`metric ${metricId} is not in the model version`);
// The metric's own definition filters. The provider query carries them
// already resolved onto physical keys; the registry model states them in
// dimension names. Either way they are the metric's MEANING, and a
// renderer that ignored them would compute a different number.
const own = query.metric_filters?.[metricId]
? query.metric_filters[metricId].map((f) => ({
field: f.dimension,
operator: f.operator,
values: f.values,
}))
: spec.filters.map((f) => ({
field: FIELD_OF[f.dimension],
operator: f.operator,
values: f.values ?? [],
}));
const conditions = [
`metric = ${lit(spec.measure)}`,
...own.map((f) => predicate(f.field, f.operator, f.values)),
];
selects.push(`sum(if(${conditions.join(' AND ')}, value, 0)) AS ${spec.id}`);
}
const where = [
`tenant_id = ${lit(TENANT)}`,
`project_id = ${lit(PROJECT)}`,
`dataset_id = ${lit('ds_sales')}`,
...query.where.map((w) => predicate(FIELD_OF[w.dimension], w.operator, w.values ?? [])),
];
return (
`SELECT ${selects.join(', ')} FROM ${DB}.opt_analytics_event ` +
`WHERE ${where.join(' AND ')} ` +
(groups.length ? `GROUP BY ${groups.join(', ')} ORDER BY ${groups.join(', ')} ` : '') +
`LIMIT ${query.limit} FORMAT JSON`
);
}
// ── the suite ──────────────────────────────────────────────────────────────
let model: SemanticModelVersion;
let resolved: ResolvedQuery;
/** Filled by the regression test below; recorded in the evidence file. */
let preFix: Record<string, number> = {};
run('BI-P029 — one golden metric, two independent compilers, one live ClickHouse', () => {
beforeAll(async () => {
const engine = new ClickHouseAnalyticsEngine({
baseUrl: CLICKHOUSE_URL!,
basicAuth: CLICKHOUSE_AUTH,
database: DB,
dimensionCatalogs: { [TENANT]: FIELD_OF },
});
await engine.ensureSchema();
const body = ROWS.map((r, i) =>
JSON.stringify({
tenant_id: TENANT,
project_id: PROJECT,
dataset_id: 'ds_sales',
metric: 'amount_sek',
event_id: `e${i}`,
event_time: SEED_EVENT_TIME,
value: r.amount,
dim_names: ['country_code', 'sales_channel'],
dim_values: [r.country, r.channel],
}),
).join('\n');
await chExec(`INSERT INTO ${DB}.opt_analytics_event FORMAT JSONEachRow`, body);
model = await new SemanticModelRegistry(new InMemorySemanticModelStore()).publish(semanticModel(1));
resolved = resolveAnalyticsQuery(
parseAnalyticsQueryRequest({
dataset: 'ds_sales',
metrics: ['net_revenue'],
dimensions: ['country'],
orderBy: [{ ref: 'country', direction: 'asc' }],
}),
queryResolutionFrom({
dataset_id: 'ds_sales',
semantic_model_version: 1,
metrics: [
{
name: 'net_revenue',
metric_id: 'm_revenue',
event_metric_key: 'amount_sek',
aggregation: 'sum',
allowed_dimensions: ['country', 'channel'],
// The metric's OWN filters, resolved onto physical field names.
definition_filters: REVENUE.filters.map((f) => ({
field_name: FIELD_OF[f.dimension],
operator: f.operator,
values: f.values ?? [],
})),
},
],
dimensions: [
{ name: 'country', dimension_id: 'd_country', field_name: 'country_code' },
{ name: 'channel', dimension_id: 'd_channel', field_name: 'sales_channel' },
],
}),
);
}, 120_000);
afterAll(async () => {
if (CLICKHOUSE_URL) await chExec(`DROP DATABASE IF EXISTS ${DB}`);
}, 60_000);
it('the fixture is arranged so a dropped definition filter CHANGES every answer', () => {
const withInternal = ROWS.reduce(
(acc, r) => ({ ...acc, [r.country]: (acc[r.country] ?? 0) + r.amount }),
{} as Record<string, number>,
);
for (const country of Object.keys(EXPECTED)) {
expect(withInternal[country]).not.toBe(EXPECTED[country]);
}
});
it('PATH A — 0pt’s ClickHouse compiler returns the metric’s meaning', async () => {
const compiled = compileRequestToClickHouse(resolved, {
tenant_id: TENANT,
project_id: PROJECT,
database: DB,
maxResultRows: 1000,
});
const rows = await chQuery(compiled.sql, compiled.params);
const got = Object.fromEntries(rows.map((r) => [String(r.dim_0), Number(r.metric_0)]));
expect(got).toEqual(EXPECTED);
});
it('PATH B — an independent renderer driven only by the provider spec agrees', async () => {
const spec = compileRequestToSemantic(resolved);
const compiled = new MetricFlowProvider().compile(spec, model);
expect(compiled.canonical_metric_ids).toEqual(['m_revenue']);
const rows = await chQuery(renderIndependently(compiled, model));
const got = Object.fromEntries(rows.map((r) => [String(r.country), Number(r.m_revenue)]));
expect(got).toEqual(EXPECTED);
});
/**
* The regression this suite was written for. Until BI-P029's gap review,
* `compileRequestToClickHouse` had no notion of a metric's own filters:
* `ResolvedMetric` did not carry them and the compiler never asked. The
* metric definition said "excluding internal transfers" and the executed
* SQL did not, so `net_revenue` returned a number that looked plausible and
* was ~9x too large for this fixture.
*
* Re-run here by stripping the definition filters from the resolution, so
* the number the bug produced is measured by the committed test rather than
* remembered from a console.
*/
it('a resolution WITHOUT the definition filters produces the pre-fix (wrong) number', async () => {
const stripped: ResolvedQuery = {
...resolved,
metrics: resolved.metrics.map((m) => ({ ...m, definition_filters: undefined })),
};
const compiled = compileRequestToClickHouse(stripped, {
tenant_id: TENANT,
project_id: PROJECT,
database: DB,
maxResultRows: 1000,
});
const rows = await chQuery(compiled.sql, compiled.params);
preFix = Object.fromEntries(rows.map((r) => [String(r.dim_0), Number(r.metric_0)]));
// Not merely different — OVERSTATED, on every country, by the internal
// transfers the definition excludes.
for (const country of Object.keys(EXPECTED)) {
expect(preFix[country]).toBeGreaterThan(EXPECTED[country]);
}
expect(compiled.sql).not.toContain('mf0_0');
});
it('the golden metric returns the SAME number on both paths, within tolerance', async () => {
const a = await chQuery(
...(() => {
const c = compileRequestToClickHouse(resolved, {
tenant_id: TENANT,
project_id: PROJECT,
database: DB,
maxResultRows: 1000,
});
return [c.sql, c.params] as const;
})(),
);
const b = await chQuery(
renderIndependently(new MetricFlowProvider().compile(compileRequestToSemantic(resolved), model), model),
);
const left = Object.fromEntries(a.map((r) => [String(r.dim_0), Number(r.metric_0)]));
const right = Object.fromEntries(b.map((r) => [String(r.country), Number(r.m_revenue)]));
expect(Object.keys(left).sort()).toEqual(Object.keys(right).sort());
for (const key of Object.keys(left)) {
// Relative tolerance, because two different aggregate expressions over
// Float64 may associate the additions differently.
const denominator = Math.max(Math.abs(left[key]), 1);
expect(Math.abs(left[key] - right[key]) / denominator).toBeLessThan(1e-9);
}
// Parity between two identical strings proves nothing.
const sqlA = compileRequestToClickHouse(resolved, {
tenant_id: TENANT,
project_id: PROJECT,
database: DB,
maxResultRows: 1000,
}).sql;
const sqlB = renderIndependently(
new MetricFlowProvider().compile(compileRequestToSemantic(resolved), model),
model,
);
expect(sqlA).not.toBe(sqlB);
expect(sqlA).toContain('sumIf(');
expect(sqlB).toContain('sum(if(');
fs.mkdirSync(path.join(process.cwd(), 'evidence', 'bi-p029'), { recursive: true });
fs.writeFileSync(
path.join(process.cwd(), 'evidence', 'bi-p029', 'semantic-parity.json'),
`${JSON.stringify(
{
prompt: 'BI-P029',
title: 'Golden metric parity: 0pt metric compiler vs an independent spec-driven renderer',
recorded_at: new Date().toISOString(),
clickhouse_version: (await chQuery('SELECT version() AS v FORMAT JSON'))[0]?.v,
golden_metric: {
id: REVENUE.id,
name: REVENUE.name,
definition_filters: REVENUE.filters,
semantic_model: { model_id: model.model_id, version: model.version, hash: model.hash },
},
expected_from_typescript: EXPECTED,
regression_guarded: {
description:
'the same request compiled WITHOUT the metric definition filters — what 0pt returned before this change',
result: preFix,
},
path_a: { compiler: '0pt compileRequestToClickHouse', aggregate: 'sumIf', result: left },
path_b: {
compiler: 'MetricFlowProvider.compile + independent renderer',
aggregate: 'sum(if(...))',
result: right,
},
tolerance: '1e-9 relative',
verdict: 'PASS',
still_open: [
'MetricFlow itself was not executed (no Python runtime provisioned for this repo)',
'the Superset integration path is not implemented',
'the AI Analyst path (inf0#29) has not been compared against this provider',
],
},
null,
2,
)}\n`,
);
});
});