feat(analytics): BI-P002..BI-P012 analytics core — domain model, tiers, contracts, Arrow, ClickHouse engine, isolation, governance
CI (SIAX Cloud) / security (push) Successful in 41s
Security Scan (SIAX Cloud) / security (push) Successful in 40s
CI (SIAX Cloud) / integration (push) Successful in 52s
CI (SIAX Cloud) / quality (push) Successful in 1m5s
CI (SIAX Cloud) / security (pull_request) Successful in 31s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 29s
CI (SIAX Cloud) / integration (pull_request) Successful in 45s
CI (SIAX Cloud) / quality (pull_request) Successful in 53s
CI (SIAX Cloud) / security (push) Successful in 41s
Security Scan (SIAX Cloud) / security (push) Successful in 40s
CI (SIAX Cloud) / integration (push) Successful in 52s
CI (SIAX Cloud) / quality (push) Successful in 1m5s
CI (SIAX Cloud) / security (pull_request) Successful in 31s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 29s
CI (SIAX Cloud) / integration (pull_request) Successful in 45s
CI (SIAX Cloud) / quality (pull_request) Successful in 53s
Implements the eight BI program prompts that make 0pt the canonical SIAX
analytics capability. Every file is NEW: not one existing file is modified,
and src/analytics/clickhouse-analytics.ts is byte-identical to main.
BI-P002 — the nineteen canonical entities, verbatim, with tenant_id +
project_id on every tenant-owned record. sql/008 gives each one a table.
The four version entities BI-P002 names as immutable are enforced by BEFORE
UPDATE/DELETE triggers, not by a TypeScript `readonly` — proven by direct SQL
against a live Postgres.
BI-P003 — RAW/NORMALIZED/CURATED/SERVING with the read rule enforced:
assertReadableByBiSurface refuses a RAW dataset to a dashboard unless a
recorded exception exists. All eight required declarations are NOT NULL.
BI-P004 — DatasetContract and a fail-closed compatibility gate. Fifteen
breaking-change classes are each tested twice: refused under a minor bump,
accepted under a major one.
BI-P005 — Arrow IPC alongside JSON, with a hand-written FlatBuffers writer so
no npm dependency (or CVE surface) is added. Conformance comes from three
independent implementations, not from self-agreement: pyarrow 25.0.1 and
DuckDB 1.5.5 read identical values from both ClickHouse's Arrow and ours, and
ClickHouse's own Arrow C++ ingests our 20,000-row batch with exact aggregates.
BI-P009 — SiaxAnalyticsEngine with all eight capabilities. The existing
ClickHouseAnalytics is COMPOSED, never replaced. executeQuery (analyst SQL) is
declared and deliberately refused with CAPABILITY_UNAVAILABLE until BI-P017 and
BI-P033 land, rather than opening the raw-SQL hole BI-P011 enumerates.
BI-P010 — four purpose-built tables, not one giant one, and the difference is
measured against the counterfactual: 48.8ms/40,960 rows vs 174.4ms/5,400,000
rows for the same question; 5/660 granules vs 660/1149.
BI-P011 — layered isolation, each layer proven with the layer above removed.
Without the forced predicate the same statement returns 50,050 (both tenants);
with it, t_alpha gets 50. Without a row policy an unrestricted user sees 2
tenants; the restricted user running the IDENTICAL statement sees 1.
BI-P012 — every named limit, fired individually and identified by ClickHouse
error code, plus the half usually skipped: an unrelated tenant is timed while
a real CPU bomb is in flight and must still return the CORRECT answer.
Three defects found by writing tests that can fail:
* `CHECK (array_length(purposes,1) >= 1)` can NEVER fail — array_length is
NULL for '{}' and a NULL CHECK passes. Fixed with coalesce(); the test
that caught it is pinned.
* EXPLAIN ESTIMATE run under the caller's own max_rows_to_read fails with
code 158 exactly when the estimate would be over budget. Planner calls now
use a narrower envelope.
* result_overflow_mode=break returns HTTP 200 with 65,409 of 100,000 rows
and no indication it is short. Every SELECT ships `throw`.
Verified rather than assumed: server7's ClickHouse holds `opt_scraped` (51
tables, 407,793,471 rows, `persons`/`cz_owners` included) — the b0ts plane this
module is prohibited from touching — has no `opt_analytics` database, zero
tenant_id columns and zero row policies. Nothing there was modified; every
proof ran against disposable containers.
Evidence: evidence/bi-p002-p012/{test-transcript.txt,bi-p010-benchmark.json,
bi-p005-arrow-roundtrip.json,server7-clickhouse-probe.md}
Docs: docs/analytics/BI_ANALYTICS_CORE.md
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -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,252 @@
|
||||
/**
|
||||
* 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";
|
||||
|
||||
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: "2026-09-03 12:00:00.000",
|
||||
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: "2026-09-04 09:00:00.000",
|
||||
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,237 @@
|
||||
/**
|
||||
* 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";
|
||||
|
||||
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: "2026-09-05 08:00:00.000",
|
||||
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,308 @@
|
||||
/**
|
||||
* 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";
|
||||
|
||||
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: "2026-09-01 10:00:00.000",
|
||||
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: "2026-09-01 10:00:00.000",
|
||||
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: "2026-09-01 00:00:00.000", 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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user