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,362 @@
/**
* tests/analytics/analyst-sql-bypass-corpus.ts
* =============================================
* BI-P017 — the bypass attempts, in one place, so the SAME corpus can be run
* twice: once against the guard (unit) and once against a LIVE ClickHouse with
* the guard REMOVED (integration), where the grants and the view predicate
* must refuse it anyway.
*
* Running it only against the guard would prove the guard, not the system.
* This estate has repeatedly shipped guards that were never tested against a
* real attempt: INF0's tenant-from-body hole was exploitable against LIVE
* production, and ST0RE turned out to have FOUR cross-tenant paths, not the
* one reported.
*
* The integration test asserts that with the guard removed the engine either
* ERRORS or returns zero foreign rows — never that "the guard said no", which
* is the assertion that would keep passing while the system was open.
*
* Session under test: tenant `t_alpha`, catalog `t_alpha_sql`, objects
* `sales` and `events`. The targets are `t_beta_sql`, the shared base database
* `opt_analytics`, and `system`.
*/
export interface BypassAttempt {
id: string;
/** What the attacker is trying to do. */
goal: string;
sql: string;
}
export const BYPASS_CORPUS: BypassAttempt[] = [
// ── reach another tenant's catalog ──────────────────────────────────────
{
id: 'cross-catalog-direct',
goal: "read the other tenant's catalog",
sql: 'SELECT * FROM t_beta_sql.sales',
},
{
id: 'cross-catalog-union',
goal: 'union in the other tenant',
sql: 'SELECT customer FROM t_alpha_sql.sales UNION ALL SELECT customer FROM t_beta_sql.sales',
},
{
id: 'cross-catalog-subquery',
goal: 'subquery on the other tenant',
sql: 'SELECT (SELECT count() FROM t_beta_sql.sales) AS n FROM t_alpha_sql.sales LIMIT 1',
},
{
id: 'cross-catalog-join',
goal: 'join the other tenant',
sql: 'SELECT a.customer FROM t_alpha_sql.sales a JOIN t_beta_sql.sales b ON a.customer = b.customer',
},
{
id: 'cross-catalog-cte',
goal: 'hide the other tenant in a CTE',
sql: 'WITH other AS (SELECT * FROM t_beta_sql.sales) SELECT count() AS n FROM other',
},
{
id: 'cross-catalog-quoted',
goal: 'quote the identifier to dodge the scan',
sql: 'SELECT * FROM "t_beta_sql"."sales"',
},
{
id: 'cross-catalog-backtick',
goal: 'backtick the identifier',
sql: 'SELECT * FROM `t_beta_sql`.`sales`',
},
// ── reach the unfiltered base table ─────────────────────────────────────
{
id: 'base-table-direct',
goal: 'read the shared base table, which holds every tenant',
sql: 'SELECT * FROM opt_analytics.opt_analytics_event',
},
{
id: 'base-table-in-cte',
goal: 'base table behind a CTE',
sql: 'WITH raw AS (SELECT * FROM opt_analytics.opt_analytics_event) SELECT count() AS n FROM raw',
},
{
id: 'base-table-union',
goal: 'union the base table in',
sql: 'SELECT customer FROM t_alpha_sql.sales UNION ALL SELECT tenant_id FROM opt_analytics.opt_analytics_event',
},
// ── system / metadata catalogs ──────────────────────────────────────────
{
id: 'system-tables',
goal: 'enumerate every table on the server',
sql: 'SELECT database, name FROM system.tables',
},
{ id: 'system-columns', goal: 'enumerate columns', sql: 'SELECT * FROM system.columns' },
{ id: 'system-users', goal: 'enumerate users', sql: 'SELECT * FROM system.users' },
{
id: 'system-processes',
goal: "read other tenants' running queries",
sql: 'SELECT query FROM system.processes',
},
{
id: 'system-query-log',
goal: "read other tenants' statement text out of the log",
sql: 'SELECT query FROM system.query_log',
},
{
id: 'information-schema',
goal: 'metadata via the ANSI schema',
sql: 'SELECT * FROM information_schema.tables',
},
{ id: 'one-table', goal: 'the always-present one-row table', sql: 'SELECT * FROM system.one' },
// ── table functions: these need NO table privilege at all ───────────────
{
id: 'tf-url',
goal: 'exfiltrate over HTTP',
sql: "SELECT * FROM url('http://127.0.0.1:1/x', 'JSONEachRow', 'a String')",
},
{
id: 'tf-file',
goal: 'read the server filesystem',
sql: "SELECT * FROM file('/etc/passwd', 'LineAsString', 'l String')",
},
{
id: 'tf-s3',
goal: 'read object storage directly',
sql: "SELECT * FROM s3('http://minio/b/*', 'CSV', 'a String')",
},
{
id: 'tf-remote',
goal: 'query another ClickHouse server',
sql: "SELECT * FROM remote('127.0.0.1:9000', 'opt_analytics', 'opt_analytics_event')",
},
{
id: 'tf-mysql',
goal: 'reach an external database',
sql: "SELECT * FROM mysql('h:3306', 'db', 't', 'u', 'p')",
},
{ id: 'tf-executable', goal: 'run a program', sql: "SELECT * FROM executable('sh', 'TSV', 'a String')" },
{
id: 'tf-numbers',
goal: 'a CPU bomb that touches no table',
sql: 'SELECT count() FROM numbers_mt(100000000000)',
},
{ id: 'tf-generate', goal: 'unbounded synthetic scan', sql: "SELECT * FROM generateRandom('a String')" },
{
id: 'tf-merge',
goal: 'merge() glob across a database',
sql: "SELECT * FROM merge('opt_analytics', '.*')",
},
{
id: 'tf-cluster',
goal: 'fan out across the cluster',
sql: "SELECT * FROM cluster('default', 'opt_analytics', 'opt_analytics_event')",
},
{
id: 'tf-view',
goal: 'wrap a subquery in view()',
sql: 'SELECT * FROM view(SELECT * FROM opt_analytics.opt_analytics_event)',
},
{
id: 'fn-dictget',
goal: 'read a dictionary, bypassing table grants',
sql: "SELECT dictGet('d', 'v', toUInt64(1)) AS x FROM t_alpha_sql.sales",
},
// ── write / DDL / privilege escalation ──────────────────────────────────
{
id: 'stacked-drop',
goal: 'stacked statement',
sql: 'SELECT 1 FROM t_alpha_sql.sales; DROP TABLE opt_analytics.opt_analytics_event',
},
{ id: 'insert', goal: 'write', sql: "INSERT INTO t_alpha_sql.sales VALUES ('x')" },
{
id: 'insert-select',
goal: 'write from a read',
sql: 'INSERT INTO t_alpha_sql.sales SELECT * FROM t_alpha_sql.sales',
},
{ id: 'alter-delete', goal: 'mutate', sql: 'ALTER TABLE opt_analytics.opt_analytics_event DELETE WHERE 1' },
{
id: 'create-view-escape',
goal: 'create an unfiltered view to read later',
sql: 'CREATE VIEW t_alpha_sql.escape AS SELECT * FROM opt_analytics.opt_analytics_event',
},
{ id: 'grant-self', goal: 'grant itself more', sql: 'GRANT SELECT ON opt_analytics.* TO CURRENT_USER' },
{ id: 'system-command', goal: 'operate the server', sql: 'SYSTEM RELOAD DICTIONARIES' },
{ id: 'kill-query', goal: "kill another tenant's query", sql: 'KILL QUERY WHERE 1' },
{ id: 'truncate', goal: 'destroy data', sql: 'TRUNCATE TABLE t_alpha_sql.sales' },
{
id: 'optimize',
goal: 'trigger heavy background work',
sql: 'OPTIMIZE TABLE opt_analytics.opt_analytics_event FINAL',
},
{
id: 'outfile',
goal: 'write to the filesystem',
sql: "SELECT * FROM t_alpha_sql.sales INTO OUTFILE '/tmp/x.csv'",
},
// ── lift the governance ceiling from inside the statement ───────────────
{
id: 'settings-raise-rows',
goal: 'raise max_rows_to_read',
sql: 'SELECT count() AS n FROM t_alpha_sql.sales SETTINGS max_rows_to_read = 0',
},
{
id: 'settings-readonly-off',
goal: 'turn readonly off',
sql: 'SELECT 1 FROM t_alpha_sql.sales SETTINGS readonly = 0',
},
{ id: 'set-statement', goal: 'SET before the query', sql: 'SET max_execution_time = 0' },
{
id: 'format-override',
goal: 'choose the wire format',
sql: 'SELECT * FROM t_alpha_sql.sales FORMAT Native',
},
// ── lexical evasion of the keyword scan ─────────────────────────────────
{
id: 'comment-split-name',
goal: 'hide a catalog boundary behind a comment',
sql: 'SELECT * FROM opt_analytics/**/.opt_analytics_event',
},
{
id: 'comment-line-hide',
goal: 'hide the tail after a -- comment',
sql: 'SELECT customer FROM t_alpha_sql.sales -- \nUNION ALL SELECT name FROM system.tables',
},
{
id: 'comment-hash-hide',
goal: 'hide the tail after a # comment',
sql: 'SELECT customer FROM t_alpha_sql.sales # \nUNION ALL SELECT name FROM system.tables',
},
{
id: 'unterminated-comment',
goal: 'run off the end of a comment',
sql: 'SELECT * FROM t_alpha_sql.sales /* x',
},
{
id: 'unterminated-string',
goal: 'run off the end of a literal',
sql: "SELECT * FROM t_alpha_sql.sales WHERE customer = 'x",
},
{
id: 'unicode-homoglyph',
// U+0430 CYRILLIC SMALL LETTER A in place of the ASCII "a".
goal: 'cyrillic homoglyph inside the catalog name',
sql: 'SELECT * FROM t_\u0430lpha_sql.sales',
},
{
id: 'zero-width',
// U+200B ZERO WIDTH SPACE inside "system".
goal: 'zero-width space inside a reserved catalog name',
sql: 'SELECT * FROM sys\u200btem.tables',
},
{
id: 'nul-byte',
goal: 'NUL truncation between two halves of a statement',
sql: 'SELECT customer FROM t_alpha_sql.sales \u0000 UNION ALL SELECT name FROM system.tables',
},
{ id: 'case-mixing', goal: 'mixed case keywords and names', sql: 'SeLeCt * FrOm SyStEm.TaBlEs' },
{
id: 'whitespace-newlines',
goal: 'newlines and tabs between tokens',
sql: 'SELECT\n\t*\nFROM\n\tsystem.tables',
},
{
id: 'describe-subquery',
goal: 'DESCRIBE a base table from inside a subquery, where the FROM-scan sees only a paren',
sql: 'SELECT * FROM (DESCRIBE TABLE opt_analytics.opt_analytics_event)',
},
{
id: 'desc-subquery-short',
goal: 'the same, using the DESC abbreviation',
sql: 'SELECT * FROM (DESC TABLE opt_analytics.opt_analytics_event)',
},
{
id: 'current-user',
goal: "identify the session's ClickHouse principal",
sql: 'SELECT currentUser() AS u FROM t_alpha_sql.sales',
},
{ id: 'three-part-name', goal: 'a three-part name', sql: 'SELECT * FROM a.b.c' },
{
id: 'unqualified-table',
goal: "unqualified name resolved by the connection's default database",
sql: 'SELECT * FROM opt_analytics_event',
},
{
id: 'cte-shadow',
goal: 'shadow a legitimate name with a CTE while also reading the real base table',
sql: 'WITH sales AS (SELECT 1 AS x) SELECT count() AS n FROM opt_analytics.opt_analytics_event',
},
{ id: 'no-from', goal: 'a statement that reads no table at all', sql: 'SELECT 1' },
{
id: 'object-not-granted',
goal: 'an object in the right catalog that the session was not given',
sql: 'SELECT * FROM t_alpha_sql.secret_ledger',
},
];
/**
* Attempts the GUARD ADMITS — and which only layers 3 and 4 refuse.
*
* This list exists because the first run of the corpus found one, and hiding
* it by quietly deleting the case would have been the dishonest fix. The guard
* reasons about statement STRUCTURE; it does not know which columns a view
* projects, and teaching it would mean giving it a schema cache that goes
* stale — a hardcoded list, which is how api0's container job died this week.
*
* `SELECT tenant_id FROM t_alpha_sql.sales` is structurally a legitimate read
* of an allowed object. It fails at the ENGINE, because the view does not
* project `tenant_id` at all (tenant-catalog.ts refuses to build one that
* does). The integration test asserts that engine-side refusal directly, so
* this case is covered by evidence rather than by an assumption.
*/
export const GUARD_ADMITS_ENGINE_REFUSES: BypassAttempt[] = [
{
id: 'hidden-tenant-column',
goal: 'select the tenant column the view does not project',
sql: 'SELECT tenant_id FROM t_alpha_sql.sales',
},
{
id: 'hidden-column-star-then-filter',
goal: 'filter on a column the view does not expose',
sql: "SELECT count() AS n FROM t_alpha_sql.sales WHERE tenant_id = 't_beta'",
},
];
/** Statements that MUST be admitted — a guard that refuses everything is useless. */
export const LEGITIMATE_CORPUS: Array<{ id: string; sql: string }> = [
{ id: 'simple', sql: 'SELECT customer, amount FROM t_alpha_sql.sales LIMIT 10' },
{
id: 'aggregate',
sql: 'SELECT customer, sum(amount) AS total FROM t_alpha_sql.sales GROUP BY customer ORDER BY total DESC LIMIT 5',
},
{
id: 'cte',
sql:
'WITH top AS (SELECT customer, sum(amount) AS total FROM t_alpha_sql.sales GROUP BY customer) ' +
'SELECT customer, total FROM top ORDER BY total DESC LIMIT 3',
},
{
id: 'self-join',
sql: 'SELECT a.customer FROM t_alpha_sql.sales a JOIN t_alpha_sql.events b ON a.customer = b.customer LIMIT 10',
},
{
id: 'literal-with-quotes',
sql: "SELECT count() AS n FROM t_alpha_sql.sales WHERE customer = 'O''Brien'",
},
{
id: 'literal-containing-sql-text',
sql: "SELECT count() AS n FROM t_alpha_sql.sales WHERE customer = 'DROP TABLE system.tables'",
},
{ id: 'comment-then-query', sql: '-- daily revenue\nSELECT sum(amount) AS total FROM t_alpha_sql.sales' },
{
id: 'subquery',
sql: 'SELECT customer FROM t_alpha_sql.sales WHERE amount > (SELECT avg(amount) FROM t_alpha_sql.sales)',
},
{
id: 'union-own-catalog',
sql: 'SELECT customer FROM t_alpha_sql.sales UNION ALL SELECT customer FROM t_alpha_sql.events',
},
{ id: 'trailing-semicolon', sql: 'SELECT count() AS n FROM t_alpha_sql.sales;' },
];
@@ -0,0 +1,108 @@
/**
* tests/analytics/analyst-sql-evidence.test.ts
* =============================================
* BI-P017 — the test that does NOT skip.
*
* The live suite (tests/integration/analyst-sql-clickhouse.integration.test.ts)
* only runs when `CLICKHOUSE_URL` is set. On a runner without ClickHouse it
* contributes nothing, and a suite that contributes nothing while reporting
* green is how l0re's 28 Postgres tests stayed silently skipped for months.
*
* So the live run WRITES its result to
* `evidence/bi-p017/analyst-sql-live-bypass.json`, that file is committed, and
* this test — which always runs — checks it against the corpus:
*
* * every attempt in the corpus must appear in the evidence, so adding an
* attack without re-running the live suite BREAKS THE BUILD rather than
* quietly going untested;
* * zero attempts may have leaked;
* * the legitimate statements must all have succeeded, so the evidence
* cannot be a recording of a database that refuses everything;
* * the counterfactual numbers must be present, so the evidence cannot be a
* recording of an EMPTY database, where "no foreign row came back" is
* true and meaningless.
*/
import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { BYPASS_CORPUS, GUARD_ADMITS_ENGINE_REFUSES, LEGITIMATE_CORPUS } from './analyst-sql-bypass-corpus';
const EVIDENCE_PATH = path.join(process.cwd(), 'evidence/bi-p017/analyst-sql-live-bypass.json');
interface Evidence {
clickhouse_version: string;
recorded_at: string;
base_table_rows_both_tenants: number;
tenant_view_rows_alpha: number;
attempts_total: number;
attempts_that_leaked: number;
legitimate_statements_that_succeeded: number;
legitimate_statements_total: number;
attempts: Array<{
id: string;
engine_http_status: number;
engine_succeeded: boolean;
leaked_foreign_tenant_row: boolean;
leaked_ungranted_table_row: boolean;
leaked_server_metadata: boolean;
guard_verdict_for_reference: string;
}>;
legitimate: Array<{ id: string; ok: boolean; contains_beta_canary: boolean }>;
}
describe('BI-P017 — the committed live evidence covers the current corpus', () => {
it('the evidence file exists', () => {
expect(
fs.existsSync(EVIDENCE_PATH),
'evidence/bi-p017/analyst-sql-live-bypass.json is missing — run the live suite with CLICKHOUSE_URL set',
).toBe(true);
});
const evidence: Evidence = fs.existsSync(EVIDENCE_PATH)
? (JSON.parse(fs.readFileSync(EVIDENCE_PATH, 'utf8')) as Evidence)
: ({ attempts: [], legitimate: [] } as unknown as Evidence);
it('was recorded against a real ClickHouse, named by version', () => {
expect(evidence.clickhouse_version).toMatch(/^\d+\.\d+/);
expect(Date.parse(evidence.recorded_at)).toBeGreaterThan(0);
});
it("records the counterfactual, so 'nothing leaked' is not a statement about an empty database", () => {
expect(evidence.base_table_rows_both_tenants).toBe(100);
expect(evidence.tenant_view_rows_alpha).toBe(50);
});
it('covers EVERY attempt in the corpus — a new attack without a re-run fails here', () => {
const recorded = new Set(evidence.attempts.map((a) => a.id));
const missing = [...BYPASS_CORPUS, ...GUARD_ADMITS_ENGINE_REFUSES]
.map((a) => a.id)
.filter((id) => !recorded.has(id));
expect(missing, `attempts never run against a live engine: ${missing.join(', ')}`).toEqual([]);
expect(evidence.attempts_total).toBe(BYPASS_CORPUS.length + GUARD_ADMITS_ENGINE_REFUSES.length);
});
it('no attempt leaked a foreign-tenant row, an ungranted row, or a foreign object name', () => {
const leaked = evidence.attempts.filter(
(a) => a.leaked_foreign_tenant_row || a.leaked_ungranted_table_row || a.leaked_server_metadata,
);
expect(leaked.map((a) => a.id)).toEqual([]);
expect(evidence.attempts_that_leaked).toBe(0);
});
it('records which attempts the ENGINE alone stopped, with the guard removed', () => {
// The interesting number: attempts that the guard would have admitted and
// the engine refused anyway. If it were zero, the layered claim would rest
// entirely on the guard.
const engineOnly = evidence.attempts.filter((a) => a.guard_verdict_for_reference === 'admitted');
expect(engineOnly.length).toBeGreaterThan(0);
for (const a of engineOnly) {
expect(a.engine_succeeded, `${a.id} was admitted by the guard AND succeeded at the engine`).toBe(false);
}
});
it('legitimate analyst work succeeded — the evidence is not a recording of a database that refuses everything', () => {
expect(evidence.legitimate_statements_total).toBe(LEGITIMATE_CORPUS.length);
expect(evidence.legitimate_statements_that_succeeded).toBe(LEGITIMATE_CORPUS.length);
expect(evidence.legitimate.every((l) => l.contains_beta_canary === false)).toBe(true);
});
});
+380
View File
@@ -0,0 +1,380 @@
/**
* tests/analytics/analyst-sql-guard.test.ts
* ==========================================
* BI-P017 — layer 2 (statement admission) against the bypass corpus.
*
* BI-P017's DoD: "INSERT, UPDATE, DROP, unsafe functions and unauthorized
* catalogs fail." That is the floor. This file tests the floor and then keeps
* going, because the interesting attacks are not `DROP TABLE` — they are
* `url()`, `merge()`, a quoted identifier, a homoglyph, and a comment placed
* where the guard and the engine might disagree about where the query ends.
*
* What this file does NOT prove: that the SYSTEM is safe. It proves the guard
* refuses these statements. The system claim is
* tests/integration/analyst-sql-clickhouse.integration.test.ts, which runs the
* same corpus against a live ClickHouse with this layer REMOVED.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
guardAnalystStatement,
stripSqlText,
type StatementGuardOptions,
} from '@/src/analytics/sql/statement-guard';
import {
AnalyticsSQLSession,
ANALYST_SQL_ROLE,
type AnalystStatementRecord,
type ReadOnlySqlEndpoint,
} from '@/src/analytics/sql/analyst-sql-session';
import { tenantSqlCatalogDdl, tenantSqlUserDdl } from '@/src/analytics/sql/tenant-catalog';
import { BYPASS_CORPUS, GUARD_ADMITS_ENGINE_REFUSES, LEGITIMATE_CORPUS } from './analyst-sql-bypass-corpus';
const OPTS: StatementGuardOptions = {
allowedCatalog: 't_alpha_sql',
allowedObjects: ['sales', 'events'],
};
describe('BI-P017 layer 2 — the bypass corpus is refused', () => {
it('covers every attack family the DoD names, and more', () => {
// A corpus that shrank silently would make this suite pass by testing
// nothing. Pin the size and the presence of the named families.
expect(BYPASS_CORPUS.length).toBeGreaterThanOrEqual(55);
const ids = new Set(BYPASS_CORPUS.map((a) => a.id));
for (const required of [
'insert',
'alter-delete',
'create-view-escape',
'tf-url',
'system-tables',
'cross-catalog-direct',
]) {
expect(ids.has(required)).toBe(true);
}
expect(new Set(BYPASS_CORPUS.map((a) => a.sql)).size).toBe(BYPASS_CORPUS.length);
});
it.each(BYPASS_CORPUS.map((a) => [a.id, a.goal, a.sql] as const))('refuses %s (%s)', (_id, _goal, sql) => {
let thrown: unknown;
try {
guardAnalystStatement(sql, OPTS);
} catch (e) {
thrown = e;
}
expect(thrown, 'statement was ADMITTED — this is a bypass').toBeInstanceOf(SiaxError);
const err = thrown as SiaxError;
expect(['AUTHORIZATION_DENIED', 'INVALID_REQUEST']).toContain(err.code);
// A refusal with an empty reason is unreviewable.
expect(err.message.length).toBeGreaterThan(20);
});
});
describe('BI-P017 layer 2 — what the guard honestly does NOT catch', () => {
// Recorded, not hidden. The guard admits these; the engine refuses them
// because the view does not project the column. The claim is proven in
// tests/integration/analyst-sql-clickhouse.integration.test.ts, not here.
it.each(GUARD_ADMITS_ENGINE_REFUSES.map((a) => [a.id, a.sql] as const))(
'the guard admits %s — layers 3/4 are what refuse it',
(_id, sql) => {
expect(() => guardAnalystStatement(sql, OPTS)).not.toThrow();
},
);
});
describe('BI-P017 layer 2 — legitimate analyst work is admitted', () => {
it.each(LEGITIMATE_CORPUS.map((a) => [a.id, a.sql] as const))('admits %s', (_id, sql) => {
const guarded = guardAnalystStatement(sql, OPTS);
expect(guarded.referencedObjects.length).toBeGreaterThan(0);
for (const obj of guarded.referencedObjects) {
expect(obj.startsWith('t_alpha_sql.')).toBe(true);
}
});
it('a guard that refused everything would fail this file', () => {
// Stated explicitly because "all tests pass" is compatible with a guard
// that throws unconditionally, and that guard would be useless.
expect(LEGITIMATE_CORPUS.length).toBeGreaterThanOrEqual(10);
});
});
describe("BI-P017 — literal and comment handling matches ClickHouse's lexer", () => {
it('does not see keywords that are inside a string literal', () => {
const g = guardAnalystStatement(
"SELECT count() AS n FROM t_alpha_sql.sales WHERE customer = 'DROP TABLE system.tables'",
OPTS,
);
expect(g.stripped).not.toContain('DROP');
expect(g.stripped).not.toContain('system');
});
it('masks literals in the normalized form so statement history is not a data dump', () => {
const g = guardAnalystStatement(
"SELECT customer FROM t_alpha_sql.sales WHERE customer = 'Anna Andersson, 19850101-1234'",
OPTS,
);
expect(g.normalized).not.toContain('Andersson');
expect(g.normalized).toContain('?');
expect(g.raw).toContain('Andersson'); // the raw form is retained deliberately
});
it('handles doubled and backslash-escaped quotes without losing the statement end', () => {
expect(stripSqlText("SELECT 'a''b'").stripped).toBe("SELECT ''");
expect(stripSqlText("SELECT 'a\\'b'").stripped).toBe("SELECT ''");
// The classic: an escaped quote that a naive stripper would treat as the
// close, leaving `; DROP …` outside a literal in the guard's view but
// inside one in the engine's. Both must agree it stays inside.
expect(stripSqlText("SELECT 'a\\'; DROP TABLE x; --'").stripped).toBe("SELECT ''");
});
it('refuses rather than guesses when a literal or comment never ends', () => {
expect(() => guardAnalystStatement("SELECT * FROM t_alpha_sql.sales WHERE c = 'x", OPTS)).toThrowError(
SiaxError,
);
expect(() => guardAnalystStatement('SELECT * FROM t_alpha_sql.sales /* x', OPTS)).toThrowError(SiaxError);
});
it('treats a comment as whitespace, so it cannot glue two identifiers together', () => {
// `a/**/b` must not become `ab`.
expect(stripSqlText('a/**/b').stripped).toBe('a b');
// A line comment leaves its terminating newline in place, so the result is
// "a \nb" — separated, which is the property that matters.
expect(stripSqlText('a--x\nb').stripped).toMatch(/^a\s+b$/);
expect(stripSqlText('a--x\nb').stripped).not.toContain('ab');
});
});
describe('BI-P017 — session role gate', () => {
const endpoint: ReadOnlySqlEndpoint = {
engine: 'clickhouse',
async execute() {
return { columns: ['n'], rows: [[1]] };
},
async cancel() {
return true;
},
};
const audit = {
records: [] as AnalystStatementRecord[],
record(e: AnalystStatementRecord) {
this.records.push(e);
},
};
const open = (roles: string[] | undefined) =>
new AnalyticsSQLSession({
identity: { tenant_id: 't_alpha', principal_id: 'u_1', roles },
endpoint,
catalog: 't_alpha_sql',
objects: ['sales', 'events'],
audit,
});
it('refuses to open without the analyst role', () => {
for (const roles of [undefined, [], ['analytics.reader'], ['admin'], ['analytics.sql.analystX']]) {
try {
open(roles as string[] | undefined);
throw new Error(`session opened with roles=${JSON.stringify(roles)} — role gate is not closed`);
} catch (e) {
expect(e).toBeInstanceOf(SiaxError);
expect((e as SiaxError).code).toBe('AUTHORIZATION_DENIED');
}
}
});
it('opens with the analyst role', () => {
expect(open([ANALYST_SQL_ROLE])).toBeInstanceOf(AnalyticsSQLSession);
});
it('refuses to open without a verified tenant or principal', () => {
for (const identity of [
{ tenant_id: '', principal_id: 'u_1', roles: [ANALYST_SQL_ROLE] },
{ tenant_id: ' ', principal_id: 'u_1', roles: [ANALYST_SQL_ROLE] },
{ tenant_id: 't_alpha', principal_id: '', roles: [ANALYST_SQL_ROLE] },
]) {
expect(
() =>
new AnalyticsSQLSession({
identity,
endpoint,
catalog: 't_alpha_sql',
objects: ['sales'],
audit,
}),
).toThrowError(SiaxError);
}
});
});
describe('BI-P017 — audit and statement history', () => {
function makeSession(opts?: { retainRaw?: boolean }) {
const records: AnalystStatementRecord[] = [];
const session = new AnalyticsSQLSession({
identity: {
tenant_id: 't_alpha',
principal_id: 'u_1',
roles: [ANALYST_SQL_ROLE],
correlation_id: 'c_1',
},
endpoint: {
engine: 'clickhouse',
async execute() {
return { columns: ['n'], rows: [[7]], rows_read: 42, bytes_read: 4242 };
},
async cancel() {
return true;
},
},
catalog: 't_alpha_sql',
objects: ['sales', 'events'],
audit: { record: (e) => void records.push(e) },
retainRawStatements: opts?.retainRaw,
});
return { session, records };
}
it('records a REFUSAL, not only a success — a guard whose rejections are invisible cannot be reviewed', async () => {
const { session, records } = makeSession();
await expect(session.query('SELECT * FROM system.tables')).rejects.toBeInstanceOf(SiaxError);
expect(records).toHaveLength(1);
expect(records[0].outcome).toBe('refused');
expect(records[0].error_code).toBe('AUTHORIZATION_DENIED');
expect(records[0].refusal_reason).toBeTruthy();
// Even a refused statement is masked before it is stored.
expect(records[0].normalized).not.toContain("'");
});
it('records the executed statement with objects, timings and byte counts', async () => {
const { session, records } = makeSession();
const out = await session.query('SELECT count() AS n FROM t_alpha_sql.sales');
expect(out.rows).toEqual([[7]]);
expect(records).toHaveLength(1);
expect(records[0].outcome).toBe('succeeded');
expect(records[0].referenced_objects).toEqual(['t_alpha_sql.sales']);
expect(records[0].rows_read).toBe(42);
expect(records[0].bytes_read).toBe(4242);
expect(records[0].statement_hash).toMatch(/^[0-9a-f]{64}$/);
expect(records[0].correlation_id).toBe('c_1');
});
it('omits the raw statement when retention is off, but never the normalized one', async () => {
const { session, records } = makeSession({ retainRaw: false });
await session.query("SELECT count() AS n FROM t_alpha_sql.sales WHERE customer = 'Anna'");
expect(records[0].raw).toBeUndefined();
expect(records[0].normalized).toContain('?');
expect(records[0].normalized).not.toContain('Anna');
});
it('applies every limit BI-P017 names, with readonly=1 (not 2, which permits SETTINGS changes)', async () => {
let seen: Record<string, string> = {};
const session = new AnalyticsSQLSession({
identity: { tenant_id: 't_alpha', principal_id: 'u_1', roles: [ANALYST_SQL_ROLE] },
endpoint: {
engine: 'clickhouse',
async execute(args) {
seen = args.settings;
return { columns: [], rows: [] };
},
async cancel() {
return true;
},
},
catalog: 't_alpha_sql',
objects: ['sales'],
audit: { record: () => undefined },
});
await session.query('SELECT count() AS n FROM t_alpha_sql.sales');
expect(seen.readonly).toBe('1');
for (const key of [
'max_execution_time',
'max_result_rows',
'max_rows_to_read',
'max_bytes_to_read',
'max_memory_usage',
]) {
expect(Number(seen[key])).toBeGreaterThan(0);
}
// A limit that returns a PARTIAL result silently is a false green.
expect(seen.timeout_overflow_mode).toBe('throw');
expect(seen.result_overflow_mode).toBe('throw');
expect(seen.read_overflow_mode).toBe('throw');
});
it('a CL0UD quota may only tighten the budget, never loosen it', () => {
const session = new AnalyticsSQLSession({
identity: {
tenant_id: 't_alpha',
principal_id: 'u_1',
roles: [ANALYST_SQL_ROLE],
quota: { maxRowsToRead: 10, maxExecutionTimeSec: 999_999 },
},
endpoint: {
engine: 'clickhouse',
async execute() {
return { columns: [], rows: [] };
},
async cancel() {
return true;
},
},
catalog: 't_alpha_sql',
objects: ['sales'],
audit: { record: () => undefined },
});
expect(session.resourceBudget.maxRowsToRead).toBe(10);
expect(session.resourceBudget.maxExecutionTimeSec).toBeLessThanOrEqual(60);
});
it('refuses to cancel a statement belonging to another session', async () => {
const { session } = makeSession();
await expect(session.cancel('sql_deadbeefcafe_notmine')).rejects.toBeInstanceOf(SiaxError);
});
});
describe('BI-P017 layers 3 and 4 — the DDL that holds when the guard does not', () => {
const spec = {
sourceDatabase: 'opt_analytics',
tenantId: 't_alpha',
catalog: 't_alpha_sql',
objects: [{ table: 'opt_analytics_event', columns: ['event_id', 'metric', 'value', 'event_time'] }],
};
it('bakes the tenant predicate into every view definition', () => {
const ddl = tenantSqlCatalogDdl(spec);
const view = ddl.find((s) => s.startsWith('CREATE OR REPLACE VIEW'));
expect(view).toContain("WHERE tenant_id = 't_alpha'");
expect(view).toContain('FROM opt_analytics.opt_analytics_event');
});
it('refuses to project tenant_id into a single-tenant view', () => {
expect(() =>
tenantSqlCatalogDdl({ ...spec, objects: [{ table: 'x', columns: ['tenant_id', 'v'] }] }),
).toThrowError(SiaxError);
});
it('refuses a tenant id that is not catalog-safe rather than embedding it', () => {
for (const bad of ["t_alpha'; DROP", 't alpha', "'", '', "t_alpha' OR '1'='1"]) {
expect(() => tenantSqlCatalogDdl({ ...spec, tenantId: bad })).toThrowError(SiaxError);
}
});
it('refuses to point the tenant catalog at the shared source database', () => {
expect(() => tenantSqlCatalogDdl({ ...spec, catalog: 'opt_analytics' })).toThrowError(SiaxError);
});
it('grants SELECT only on the tenant catalog and pins a row policy to the base table', () => {
const ddl = tenantSqlUserDdl({ ...spec, userName: 't_alpha_sql_user', password: 'x' });
expect(ddl.some((s) => s.includes('GRANT SELECT ON t_alpha_sql.* TO t_alpha_sql_user'))).toBe(true);
// The wide grant that would make the whole design pointless:
expect(ddl.some((s) => s.includes('GRANT SELECT ON opt_analytics.* '))).toBe(false);
expect(
ddl.some((s) => s.includes('CREATE ROW POLICY') && s.includes("USING tenant_id = 't_alpha'")),
).toBe(true);
expect(ddl[0]).toContain('readonly = 1');
});
it('never embeds a password containing a quote or a backslash', () => {
for (const bad of ["a'b", 'a\\b']) {
expect(() => tenantSqlUserDdl({ ...spec, userName: 'u', password: bad })).toThrowError(SiaxError);
}
});
});
@@ -0,0 +1,194 @@
/**
* BI-P002 (domain model) + BI-P003 (data tiers), the parts provable without
* infrastructure. The Postgres half — real tables, real immutability
* triggers, real tenant scoping — is
* tests/analytics/analytics-domain-postgres.realinfra.test.ts.
*
* The registry-vs-migration test below is the one that earns its place: it
* reads sql/008_analytics_domain_model.sql from disk and asserts a CREATE
* TABLE exists for every one of the nineteen canonical entities. A future
* rename, or an entity quietly dropped from the migration, fails HERE rather
* than at 3am against a database that turns out to be missing a table.
*/
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import {
ANALYTICS_DOMAIN_ENTITIES,
ANALYTICS_ENTITY_TABLES,
IMMUTABLE_VERSION_ENTITIES,
} from '@/src/analytics/domain/entities';
import {
ANALYTICS_TIERS,
assertReadableByBiSurface,
assertTierLineageSane,
BI_READABLE_TIERS,
isAnalyticsTier,
TIER_RANK,
} from '@/src/analytics/domain/tiers';
const MIGRATION = fs.readFileSync(path.join(process.cwd(), 'sql', '008_analytics_domain_model.sql'), 'utf8');
describe('BI-P002 canonical entity set', () => {
it('lists exactly the nineteen entities the program names, verbatim', () => {
expect(ANALYTICS_DOMAIN_ENTITIES).toEqual([
'AnalyticsDataset',
'DatasetVersion',
'DatasetField',
'DatasetGrant',
'MetricDefinition',
'MetricVersion',
'DimensionDefinition',
'SemanticModel',
'AnalyticsQuery',
'QueryExecution',
'QueryResult',
'DashboardDefinition',
'DashboardVersion',
'ReportDefinition',
'ReportRun',
'DataQualityRule',
'DataQualityRun',
'LineageReference',
'BIApplicationBinding',
]);
expect(ANALYTICS_DOMAIN_ENTITIES).toHaveLength(19);
});
it('sql/008 defines a table for every entity (no entity is a type without storage)', () => {
const missing: string[] = [];
for (const entity of ANALYTICS_DOMAIN_ENTITIES) {
const table = ANALYTICS_ENTITY_TABLES[entity];
if (!new RegExp(`CREATE TABLE IF NOT EXISTS ${table}\\b`).test(MIGRATION)) {
missing.push(`${entity} -> ${table}`);
}
}
expect(missing).toEqual([]);
});
it('every tenant-owned table carries tenant_id AND project_id', () => {
// Split on the table definitions and check each block.
const blocks = MIGRATION.split(/CREATE TABLE IF NOT EXISTS /).slice(1);
const offenders: string[] = [];
for (const block of blocks) {
const name = block.split(/[\s(]/)[0];
if (!Object.values(ANALYTICS_ENTITY_TABLES).includes(name)) continue;
const body = block.slice(0, block.indexOf(');'));
if (!/\btenant_id TEXT NOT NULL\b/.test(body) || !/\bproject_id TEXT NOT NULL\b/.test(body)) {
offenders.push(name);
}
}
expect(offenders).toEqual([]);
});
it('the four immutable version entities have a BEFORE UPDATE OR DELETE trigger in sql/008', () => {
expect(IMMUTABLE_VERSION_ENTITIES).toEqual([
'DatasetVersion',
'MetricVersion',
'SemanticModel',
'DashboardVersion',
]);
for (const entity of IMMUTABLE_VERSION_ENTITIES) {
const table = ANALYTICS_ENTITY_TABLES[entity];
expect(
new RegExp(`BEFORE UPDATE OR DELETE ON ${table}\\b`).test(MIGRATION),
`${entity} (${table}) has no immutability trigger`,
).toBe(true);
}
});
it('BIApplicationBinding storage carries NO credential column — the ownership boundary is structural', () => {
const block = MIGRATION.split('CREATE TABLE IF NOT EXISTS opt_analytics_bi_application_binding')[1] ?? '';
const body = block.slice(0, block.indexOf(');'));
for (const forbidden of ['password', 'dsn', 'secret', 'connection_string', 'clickhouse_url', 'token']) {
expect(body.toLowerCase()).not.toContain(forbidden);
}
});
it('sql/008 is idempotent-shaped: every CREATE is IF NOT EXISTS / OR REPLACE', () => {
const creates =
MIGRATION.match(/^CREATE (TABLE|INDEX|TRIGGER|FUNCTION|OR REPLACE FUNCTION)[^\n]*/gm) ?? [];
const nonIdempotent = creates.filter(
(line) => !/IF NOT EXISTS/.test(line) && !/OR REPLACE/.test(line) && !/^CREATE TRIGGER/.test(line),
);
expect(nonIdempotent).toEqual([]);
// Triggers cannot take IF NOT EXISTS in Postgres, so each one must be
// preceded by a DROP TRIGGER IF EXISTS to stay replayable.
const triggers = MIGRATION.match(/^CREATE TRIGGER (\w+)/gm) ?? [];
for (const t of triggers) {
const name = t.replace('CREATE TRIGGER ', '');
expect(MIGRATION).toContain(`DROP TRIGGER IF EXISTS ${name}`);
}
});
});
describe('BI-P003 analytics data tiers', () => {
it('canonicalizes exactly RAW / NORMALIZED / CURATED / SERVING', () => {
expect(ANALYTICS_TIERS).toEqual(['RAW', 'NORMALIZED', 'CURATED', 'SERVING']);
expect(isAnalyticsTier('CURATED')).toBe(true);
expect(isAnalyticsTier('raw')).toBe(false);
expect(isAnalyticsTier('BRONZE')).toBe(false);
});
it('no business dashboard reads a RAW/NORMALIZED dataset by default', () => {
expect(BI_READABLE_TIERS).toEqual(['SERVING', 'CURATED']);
for (const tier of ['RAW', 'NORMALIZED'] as const) {
expect(() =>
assertReadableByBiSurface({ dataset_id: 'ds_1', tier }, 'dashboard:exec-overview'),
).toThrowError(/may not read/);
}
for (const tier of ['SERVING', 'CURATED'] as const) {
expect(() => assertReadableByBiSurface({ dataset_id: 'ds_1', tier }, 'dashboard:x')).not.toThrow();
}
});
it('a recorded exception is the only way a RAW dataset reaches a BI surface', () => {
expect(() =>
assertReadableByBiSurface(
{
dataset_id: 'ds_1',
tier: 'RAW',
raw_access_exception: 'INC-2026-09-06 forensic review, expires 2026-10-01',
},
'dashboard:incident',
),
).not.toThrow();
// An empty/whitespace "exception" is not an exception.
expect(() =>
assertReadableByBiSurface(
{ dataset_id: 'ds_1', tier: 'RAW', raw_access_exception: ' ' },
'dashboard:x',
),
).toThrowError(/may not read/);
});
it('tier order is enforced: a CURATED dataset cannot be built from SERVING', () => {
expect(TIER_RANK.RAW).toBeLessThan(TIER_RANK.NORMALIZED);
expect(TIER_RANK.NORMALIZED).toBeLessThan(TIER_RANK.CURATED);
expect(TIER_RANK.CURATED).toBeLessThan(TIER_RANK.SERVING);
expect(() => assertTierLineageSane('CURATED', 'SERVING')).toThrowError(/tier order/);
expect(() => assertTierLineageSane('SERVING', 'CURATED')).not.toThrow();
expect(() => assertTierLineageSane('CURATED', 'CURATED')).not.toThrow();
});
it('sql/008 constrains tier at the DATABASE level, not only in TypeScript', () => {
expect(MIGRATION).toContain("CHECK (tier IN ('RAW','NORMALIZED','CURATED','SERVING'))");
});
it("BI-P003's eight required declarations are all NOT NULL in sql/008", () => {
const block = MIGRATION.split('CREATE TABLE IF NOT EXISTS opt_analytics_dataset ')[1] ?? '';
const body = block.slice(0, block.indexOf(');'));
for (const col of [
'tier',
'schema_contract_id',
'owner_id',
'source_ref',
'freshness_slo_seconds',
'retention_days',
'classification',
'quality_rule_ids',
]) {
expect(new RegExp(`\\b${col}\\b[^,]*NOT NULL`).test(body), `${col} is nullable`).toBe(true);
}
});
});
@@ -0,0 +1,369 @@
/**
* BI-P002 DoD: "Database migrations + persistence + tenant isolation +
* restore tests."
*
* REAL Postgres, same honest-degrade convention as
* tests/p0/source-registry-postgres.realinfra.test.ts: gated on
* ANALYTICS_TEST_DATABASE_URL, SKIPS HONESTLY when unset, never fabricates.
*
* docker run -d --name opt-bi-pg -p 15455:5432 \
* -e POSTGRES_USER=opt -e POSTGRES_PASSWORD=opt_bi_throwaway \
* -e POSTGRES_DB=opt_bi_test postgres:16-alpine
* ANALYTICS_TEST_DATABASE_URL=postgres://opt:opt_bi_throwaway@localhost:15455/opt_bi_test \
* pnpm vitest run tests/analytics/analytics-domain-postgres.realinfra.test.ts
*
* The RESTORE half is the part that catches migration-chain rot: it replays
* sql/001..008 in order into a FRESH database, exactly as
* docs/runbook/backup-restore.md describes, and only then runs the
* persistence assertions. sql/003_datasets.sql exists because that same drill
* found a table no file ever created; this suite keeps that class of defect
* from coming back through sql/008.
*/
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import postgres from 'postgres';
import {
ANALYTICS_DOMAIN_ENTITIES,
ANALYTICS_ENTITY_TABLES,
IMMUTABLE_VERSION_ENTITIES,
} from '@/src/analytics/domain/entities';
import { AnalyticsDomainRepository } from '@/src/analytics/repositories/analytics-domain-repository';
import { contractHash, type DatasetContract } from '@/src/analytics/domain/contract';
const TEST_DATABASE_URL = process.env.ANALYTICS_TEST_DATABASE_URL;
const run = TEST_DATABASE_URL ? describe : describe.skip;
/** A schema of its own so the drill starts from genuinely nothing. */
const SCHEMA = `bi_p002_${Date.now().toString(36)}`;
let sql: ReturnType<typeof postgres> | undefined;
let reachable = false;
let unreachableReason = '';
/** Which sql/*.sql files the restore drill actually applied. */
const applied: string[] = [];
const ALPHA = { tenant_id: 't_alpha', project_id: 'p_main' };
const BETA = { tenant_id: 't_beta', project_id: 'p_main' };
function repo(): AnalyticsDomainRepository {
return new AnalyticsDomainRepository(sql!);
}
function contract(datasetId: string): DatasetContract {
return {
dataset_id: datasetId,
version: '1.0.0',
tier: 'CURATED',
fields: [{ name: 'id', type: 'string', nullable: false, role: 'identifier', primary_identifier: true }],
primary_identifiers: ['id'],
dimensions: [],
measures: [],
freshness_slo_seconds: 3600,
retention_days: 365,
pii_classification: 'none',
source_lineage: ['src_x'],
quality_rules: [],
allowed_purposes: ['analytics'],
};
}
beforeAll(async () => {
if (!TEST_DATABASE_URL) {
console.warn(
'[realinfra] ANALYTICS_TEST_DATABASE_URL not set — skipping honestly, not fabricating success.',
);
return;
}
try {
sql = postgres(TEST_DATABASE_URL, { prepare: false, ssl: false, max: 3 });
await Promise.race([
sql`SELECT 1`,
new Promise((_, reject) => setTimeout(() => reject(new Error('connect timeout')), 5000)),
]);
// RESTORE DRILL: a brand-new schema, then every migration in order.
await sql.unsafe(`CREATE SCHEMA ${SCHEMA}`);
await sql.unsafe(`SET search_path TO ${SCHEMA}, public`);
const dir = path.join(process.cwd(), 'sql');
for (const file of fs
.readdirSync(dir)
.filter((f) => f.endsWith('.sql'))
.sort()) {
const body = fs.readFileSync(path.join(dir, file), 'utf8');
try {
await sql.unsafe(`SET search_path TO ${SCHEMA}, public; ${body}`);
applied.push(file);
} catch (err) {
// 001 needs the `vector` extension, which a stock postgres:16-alpine
// does not carry. Record the skip rather than hiding it — the files
// sql/008 actually depends on must still apply.
applied.push(`${file} (FAILED: ${String(err).slice(0, 120)})`);
}
}
reachable = true;
} catch (err) {
reachable = false;
unreachableReason = err instanceof Error ? err.message : String(err);
}
}, 60_000);
afterAll(async () => {
if (sql && reachable) {
await sql.unsafe(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`).catch(() => undefined);
}
await sql?.end({ timeout: 5 });
});
run('BI-P002 analytics domain model against a LIVE Postgres', () => {
it('restore drill: sql/008 applies cleanly on top of the replayed chain', (ctx) => {
if (!reachable) ctx.skip();
expect(unreachableReason).toBe('');
const p008 = applied.find((f) => f.startsWith('008_'));
expect(p008, `sql/008 was not applied. Applied: ${applied.join(', ')}`).toBe(
'008_analytics_domain_model.sql',
);
});
it('all nineteen entity tables really exist after the restore', async (ctx) => {
if (!reachable) ctx.skip();
const rows = await sql!<{ table_name: string }[]>`
SELECT table_name FROM information_schema.tables WHERE table_schema = ${SCHEMA}`;
const present = new Set(rows.map((r) => r.table_name));
const missing = ANALYTICS_DOMAIN_ENTITIES.filter((e) => !present.has(ANALYTICS_ENTITY_TABLES[e]));
expect(missing).toEqual([]);
});
it('replaying sql/008 a second time is a no-op, not an error', async (ctx) => {
if (!reachable) ctx.skip();
const body = fs.readFileSync(path.join(process.cwd(), 'sql', '008_analytics_domain_model.sql'), 'utf8');
await expect(sql!.unsafe(`SET search_path TO ${SCHEMA}, public; ${body}`)).resolves.toBeDefined();
});
it('persists a dataset and reads it back through the repository', async (ctx) => {
if (!reachable) ctx.skip();
const r = repo();
const created = await r.createDataset(ALPHA, {
dataset_id: 'ds_alpha_1',
name: 'Alpha listings',
tier: 'CURATED',
schema_contract_id: 'dc_alpha',
schema_contract_version: '1.0.0',
owner_id: 'team_data',
source_ref: 'src_feed',
freshness_slo_seconds: 3600,
quality_rule_ids: [],
retention_days: 365,
classification: 'none',
status: 'active',
created_by: 'usr_1',
});
expect(created.tenant_id).toBe('t_alpha');
const read = await r.getDataset(ALPHA, 'ds_alpha_1');
expect(read?.name).toBe('Alpha listings');
expect(read?.freshness_slo_seconds).toBe(3600);
// Cross-check with direct SQL — proving the row is really in the table,
// not an artifact of the repository's own bookkeeping.
const direct = await sql!<{ c: string }[]>`
SELECT count(*)::text AS c FROM opt_analytics_dataset WHERE dataset_id = 'ds_alpha_1'`;
expect(Number(direct[0].c)).toBe(1);
});
it("TENANT ISOLATION: t_beta cannot read t_alpha's dataset, even with the exact id", async (ctx) => {
if (!reachable) ctx.skip();
const r = repo();
expect(await r.getDataset(BETA, 'ds_alpha_1')).toBeUndefined();
expect(await r.listDatasets(BETA)).toEqual([]);
// And the row IS there — the empty result is scoping, not absence.
const direct = await sql!<{ c: string }[]>`SELECT count(*)::text AS c FROM opt_analytics_dataset`;
expect(Number(direct[0].c)).toBeGreaterThanOrEqual(1);
});
it("TENANT ISOLATION: a version cannot be minted against another tenant's dataset", async (ctx) => {
if (!reachable) ctx.skip();
await expect(
repo().createDatasetVersion(BETA, {
dataset_id: 'ds_alpha_1',
contract_hash: 'deadbeef',
schema_contract_version: '1.0.0',
}),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
it('dataset versions are monotonic and carry the contract hash', async (ctx) => {
if (!reachable) ctx.skip();
const r = repo();
const c = contract('ds_alpha_1');
const v1 = await r.createDatasetVersion(ALPHA, {
dataset_id: 'ds_alpha_1',
contract_hash: contractHash(c),
schema_contract_version: '1.0.0',
});
const v2 = await r.createDatasetVersion(ALPHA, {
dataset_id: 'ds_alpha_1',
contract_hash: contractHash({ ...c, version: '2.0.0' }),
schema_contract_version: '2.0.0',
});
expect(v1.version).toBe(1);
expect(v2.version).toBe(2);
expect(v2.contract_hash).not.toBe(v1.contract_hash);
expect((await r.listDatasetVersions(ALPHA, 'ds_alpha_1')).map((v) => v.version)).toEqual([1, 2]);
});
it('IMMUTABILITY is enforced by the DATABASE: UPDATE and DELETE on a version row are refused', async (ctx) => {
if (!reachable) ctx.skip();
// Direct SQL, bypassing every TypeScript `readonly` — the only test that
// proves the guarantee survives a psql session.
await expect(
sql!.unsafe(
`UPDATE ${SCHEMA}.opt_analytics_dataset_version SET contract_hash = 'tampered' WHERE dataset_id = 'ds_alpha_1'`,
),
).rejects.toThrow(/immutable/i);
await expect(
sql!.unsafe(`DELETE FROM ${SCHEMA}.opt_analytics_dataset_version WHERE dataset_id = 'ds_alpha_1'`),
).rejects.toThrow(/immutable/i);
// The rows are untouched.
const rows = await sql!<{ contract_hash: string }[]>`
SELECT contract_hash FROM opt_analytics_dataset_version WHERE dataset_id = 'ds_alpha_1'`;
expect(rows).toHaveLength(2);
for (const r of rows) expect(r.contract_hash).not.toBe('tampered');
});
it('all four immutable entities refuse an UPDATE, not just the one that was tested first', async (ctx) => {
if (!reachable) ctx.skip();
const r = repo();
await r.createDataset(ALPHA, {
dataset_id: 'ds_imm',
name: 'Immutability fixture',
tier: 'SERVING',
schema_contract_id: 'dc_i',
schema_contract_version: '1.0.0',
owner_id: 'team_data',
source_ref: 'src',
freshness_slo_seconds: 60,
quality_rule_ids: [],
retention_days: 30,
classification: 'none',
status: 'active',
});
const metric = await r.createMetric(ALPHA, {
metric_id: 'm_imm',
name: 'immutable metric',
dataset_id: 'ds_imm',
aggregation: 'sum',
measure_field: 'value',
allowed_dimension_ids: [],
owner_id: 'team_data',
});
await r.createMetricVersion(ALPHA, { metric_id: metric.metric_id, definition_json: '{"v":1}' });
await r.createDatasetVersion(ALPHA, {
dataset_id: 'ds_imm',
contract_hash: 'h1',
schema_contract_version: '1.0.0',
});
await sql!.unsafe(`INSERT INTO ${SCHEMA}.opt_analytics_semantic_model
(semantic_model_id, tenant_id, project_id, name, version, model_json, model_hash, owner_id)
VALUES ('sm_1','t_alpha','p_main','model_a',1,'{}','h','team_data')`);
await sql!.unsafe(`INSERT INTO ${SCHEMA}.opt_analytics_dashboard_definition
(dashboard_id, tenant_id, project_id, name, owner_id) VALUES ('db_1','t_alpha','p_main','dash','team_data')`);
await sql!.unsafe(`INSERT INTO ${SCHEMA}.opt_analytics_dashboard_version
(dashboard_version_id, dashboard_id, tenant_id, project_id, version, layout_json, layout_hash)
VALUES ('dv_1','db_1','t_alpha','p_main',1,'{}','h')`);
const updates: Record<string, string> = {
DatasetVersion: `UPDATE ${SCHEMA}.opt_analytics_dataset_version SET contract_hash='x' WHERE dataset_id='ds_imm'`,
MetricVersion: `UPDATE ${SCHEMA}.opt_analytics_metric_version SET definition_json='{}' WHERE metric_id='m_imm'`,
SemanticModel: `UPDATE ${SCHEMA}.opt_analytics_semantic_model SET model_json='{}' WHERE semantic_model_id='sm_1'`,
DashboardVersion: `UPDATE ${SCHEMA}.opt_analytics_dashboard_version SET layout_json='{}' WHERE dashboard_version_id='dv_1'`,
};
for (const entity of IMMUTABLE_VERSION_ENTITIES) {
await expect(sql!.unsafe(updates[entity]), `${entity} is NOT immutable`).rejects.toThrow(/immutable/i);
}
});
it('a metric version after the first must state WHY the number changed meaning', async (ctx) => {
if (!reachable) ctx.skip();
const r = repo();
await expect(
r.createMetricVersion(ALPHA, { metric_id: 'm_imm', definition_json: '{"v":2}' }),
).rejects.toThrow();
const v2 = await r.createMetricVersion(ALPHA, {
metric_id: 'm_imm',
definition_json: '{"v":2}',
change_reason: 'excluded internal test accounts from the numerator',
});
expect(v2.version).toBe(2);
});
it('a DatasetGrant without a purpose is refused by the DATABASE (purpose limitation)', async (ctx) => {
if (!reachable) ctx.skip();
// Regression pin: the first version of this constraint was written
// `array_length(allowed_purposes, 1) >= 1`, which is NULL for '{}' — and a
// CHECK evaluating to NULL PASSES in Postgres. It could never fail. This
// test found that; keep it.
await expect(
sql!.unsafe(`INSERT INTO ${SCHEMA}.opt_analytics_dataset_grant
(grant_id, dataset_id, tenant_id, project_id, subject_id, subject_type, level, allowed_purposes)
VALUES ('g_1','ds_imm','t_alpha','p_main','usr_1','user','read', '{}')`),
).rejects.toThrow(/purposes_nonempty/);
// A grant WITH a purpose is accepted, so the constraint is not simply
// rejecting everything.
await expect(
sql!.unsafe(`INSERT INTO ${SCHEMA}.opt_analytics_dataset_grant
(grant_id, dataset_id, tenant_id, project_id, subject_id, subject_type, level, allowed_purposes)
VALUES ('g_ok','ds_imm','t_alpha','p_main','usr_1','user','read', ARRAY['market_analytics'])`),
).resolves.toBeDefined();
});
it('a BIApplicationBinding without a purpose is refused too, and carries no credential column', async (ctx) => {
if (!reachable) ctx.skip();
await expect(
sql!.unsafe(`INSERT INTO ${SCHEMA}.opt_analytics_bi_application_binding
(binding_id, tenant_id, project_id, kind, name, principal_id, allowed_purposes)
VALUES ('b_1','t_alpha','p_main','superset','sup','svc_1','{}')`),
).rejects.toThrow(/purposes_nonempty/);
const cols = await sql!<{ column_name: string }[]>`
SELECT column_name FROM information_schema.columns
WHERE table_schema = ${SCHEMA} AND table_name = 'opt_analytics_bi_application_binding'`;
const names = cols.map((c) => c.column_name.toLowerCase());
for (const forbidden of ['password', 'secret', 'dsn', 'token', 'connection_string', 'clickhouse_url']) {
expect(names, `BI binding must never store ${forbidden}`).not.toContain(forbidden);
}
});
it('the dimension catalog is tenant-scoped and FAILS CLOSED for a tenant with none', async (ctx) => {
if (!reachable) ctx.skip();
const r = repo();
await r.createDimension(ALPHA, {
dimension_id: 'dim_1',
name: 'make',
dataset_id: 'ds_imm',
field_name: 'vehicle_make',
field_type: 'string',
classification: 'none',
});
expect(await r.dimensionCatalog(ALPHA)).toEqual({ make: 'vehicle_make' });
// t_beta declared nothing, so it may reference nothing.
expect(await r.dimensionCatalog(BETA)).toEqual({});
});
it('a dimension whose physical field is not identifier-safe is refused by the DATABASE', async (ctx) => {
if (!reachable) ctx.skip();
await expect(
sql!.unsafe(`INSERT INTO ${SCHEMA}.opt_analytics_dimension_definition
(dimension_id, tenant_id, project_id, name, dataset_id, field_name, field_type)
VALUES ('dim_bad','t_alpha','p_main','evil','ds_imm', 'x''; DROP TABLE opt_analytics_dataset; --','string')`),
).rejects.toThrow();
});
it('the repository refuses to act without a verified tenant scope', async (ctx) => {
if (!reachable) ctx.skip();
const r = repo();
await expect(r.getDataset({ tenant_id: '', project_id: 'p' }, 'ds_imm')).rejects.toMatchObject({
code: 'UNAUTHENTICATED',
});
await expect(r.listDatasets({ tenant_id: 't_alpha', project_id: ' ' })).rejects.toMatchObject({
code: 'UNAUTHENTICATED',
});
});
});
@@ -0,0 +1,124 @@
/**
* BI-P009 DoD: "Provider contract tests added."
*
* This is the contract every `SiaxAnalyticsEngine` provider must satisfy
* regardless of engine — ClickHouse today, DuckDB (BI-P014) and Trino
* (BI-P015) later. It is written against the INTERFACE, so a future provider
* imports `analyticsEngineContract` and gets the same bar.
*
* The identity rules here are the ones that matter most: this estate has
* already shipped a live cross-tenant hole by reading the tenant out of a
* REQUEST BODY (INF0 Wave 2). So the contract asserts that a request field
* named `tenant_id` cannot influence the engine at all.
*/
import { describe, it, expect } from 'vitest';
import { ClickHouseAnalyticsEngine } from '@/src/analytics/engine/clickhouse-engine';
import {
SIAX_ANALYTICS_ENGINE_CAPABILITIES,
type AnalyticsIdentity,
type SiaxAnalyticsEngine,
} from '@/src/analytics/engine/siax-analytics-engine';
const IDENTITY: AnalyticsIdentity = {
tenant_id: 't_alpha',
project_id: 'p_default',
principal_id: 'usr_1',
};
/** Reusable contract suite — future providers call this with their factory. */
export function analyticsEngineContract(name: string, make: () => SiaxAnalyticsEngine): void {
describe(`SiaxAnalyticsEngine contract: ${name}`, () => {
it('implements all eight BI-P009 capabilities as callable methods', () => {
const engine = make() as unknown as Record<string, unknown>;
for (const cap of SIAX_ANALYTICS_ENGINE_CAPABILITIES) {
expect(typeof engine[cap], `${cap} is not a method`).toBe('function');
}
expect(SIAX_ANALYTICS_ENGINE_CAPABILITIES).toEqual([
'health',
'executeMetric',
'executeQuery',
'estimateQuery',
'cancelQuery',
'explain',
'ingestProjection',
'refreshProjection',
]);
});
it('names its provider', () => {
expect(make().provider.length).toBeGreaterThan(0);
});
it('refuses every tenant-scoped capability without a verified identity', async () => {
const engine = make();
const blank = { tenant_id: '', project_id: 'p', principal_id: 'usr_1' };
const noPrincipal = { tenant_id: 't_alpha', project_id: 'p', principal_id: '' };
for (const bad of [blank, noPrincipal]) {
await expect(engine.executeMetric(bad, { metric: 'm', aggregate: 'sum' })).rejects.toMatchObject({
code: 'UNAUTHENTICATED',
});
await expect(engine.estimateQuery(bad, { metric: 'm', aggregate: 'sum' })).rejects.toMatchObject({
code: 'UNAUTHENTICATED',
});
await expect(engine.ingestProjection(bad, { dataset_id: 'ds', rows: [] })).rejects.toMatchObject({
code: 'UNAUTHENTICATED',
});
await expect(engine.refreshProjection(bad, 'ds')).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
await expect(engine.cancelQuery(bad, 'q')).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
}
});
it('a tenant_id smuggled into the REQUEST cannot influence the engine (INF0 Wave-2 bug class)', async () => {
const engine = make();
const smuggled = { metric: 'm', aggregate: 'sum', tenant_id: 't_victim' } as never;
// The request type has no tenant field; if a provider ever started
// reading one, this call would target t_victim. The engine must still
// fail on the IDENTITY, proving the request field is inert.
await expect(
engine.executeMetric({ tenant_id: '', project_id: 'p', principal_id: 'u' }, smuggled),
).rejects.toMatchObject({ code: 'UNAUTHENTICATED' });
});
it('cancelQuery refuses a query id belonging to another tenant', async () => {
const engine = make();
await expect(engine.cancelQuery(IDENTITY, 'opt_deadbeefdead_someoneelses')).rejects.toMatchObject({
code: 'AUTHORIZATION_DENIED',
});
});
it('health() reports unhealthy rather than throwing when the engine is unreachable', async () => {
const report = await make().health();
expect(report.healthy).toBe(false);
expect(report.provider.length).toBeGreaterThan(0);
// Never leak an engine body or a DSN into the operator-facing detail.
expect(report.detail ?? '').not.toMatch(/http|password|@/i);
});
});
}
analyticsEngineContract(
'clickhouse (unreachable host — contract-level assertions only)',
() =>
new ClickHouseAnalyticsEngine({
baseUrl: 'http://clickhouse.invalid:8123',
database: 'opt_contract_test',
timeoutMs: 500,
}),
);
describe('BI-P009 refusals that are deliberate, not missing', () => {
it('executeQuery (analyst SQL) is declared and REFUSED until BI-P017/BI-P033', async () => {
const engine = new ClickHouseAnalyticsEngine({ baseUrl: 'http://clickhouse.invalid:8123' });
await expect(engine.executeQuery(IDENTITY, { sql: 'SELECT 1', dataset_ids: [] })).rejects.toMatchObject({
code: 'CAPABILITY_UNAVAILABLE',
});
});
it('the PRESERVED ClickHouseAnalytics is reachable through the engine, not replaced by it', () => {
const engine = new ClickHouseAnalyticsEngine({ baseUrl: 'http://clickhouse.invalid:8123' });
expect(engine.legacyAnalytics.constructor.name).toBe('ClickHouseAnalytics');
expect(typeof engine.legacyAnalytics.queryMetric).toBe('function');
expect(typeof engine.legacyAnalytics.ensureSchema).toBe('function');
expect(typeof engine.legacyAnalytics.ingest).toBe('function');
});
});
@@ -0,0 +1,349 @@
/**
* tests/analytics/analytics-governance-postgres.realinfra.test.ts
* ================================================================
* sql/009 against a REAL Postgres.
*
* A migration nobody ran is a migration that does not work, and a trigger
* nobody fired is a comment. So this applies sql/008 and sql/009 into a
* throwaway schema and then attempts, against the database, every write the
* constraints exist to refuse:
*
* BI-P031 UPDATE a CERTIFIED metric's meaning in place -> must RAISE.
* This is the layer that holds when something writes without going
* through the application: a migration script, a psql session, an
* admin tool. A TypeScript guard does not survive `psql`.
* BI-P030 UPDATE a published semantic model version's content -> must RAISE.
* Two ACTIVE versions of one model -> must violate a unique index.
* BI-P028 A currency-formatted metric with no currency -> must be refused.
* Certification without an actor or the two definitions -> refused.
* BI-P018 A `compiled_query_hash` that is not a 64-hex digest -> refused.
* BI-P021 UPDATE or DELETE a usage-ledger row -> must RAISE (append-only).
*
* Gated on ANALYTICS_TEST_DATABASE_URL, matching the convention in
* analytics-domain-postgres.realinfra.test.ts. With it set and Postgres down,
* this FAILS rather than skipping.
*
* docker run -d --name pg -p 25433:5432 -e POSTGRES_PASSWORD=test \
* -e POSTGRES_DB=opt postgres:16-alpine
* ANALYTICS_TEST_DATABASE_URL=postgres://postgres:test@127.0.0.1:25433/opt \
* pnpm vitest run tests/analytics/analytics-governance-postgres.realinfra.test.ts
*/
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import postgres from 'postgres';
const TEST_DATABASE_URL = process.env.ANALYTICS_TEST_DATABASE_URL;
const run = TEST_DATABASE_URL ? describe : describe.skip;
const SCHEMA = `bi_p009_${Date.now().toString(36)}`;
let sql: ReturnType<typeof postgres>;
/** Did the statement RAISE? Returns the message, or undefined if it succeeded. */
async function refusalOf(fn: () => Promise<unknown>): Promise<string | undefined> {
try {
await fn();
return undefined;
} catch (e) {
return String((e as Error).message);
}
}
beforeAll(async () => {
if (!TEST_DATABASE_URL) return;
// The search_path is pinned on the CONNECTION rather than prefixed to every
// statement. Prefixing makes each call a multi-statement simple query, and
// postgres.js then returns the LAST statement's result — which silently
// turned `SELECT state FROM ...` into the connection object in the first
// version of this file, and made two assertions compare against nonsense.
const admin = postgres(TEST_DATABASE_URL, { max: 1, onnotice: () => undefined });
await admin.unsafe(`CREATE SCHEMA IF NOT EXISTS ${SCHEMA}`);
await admin.end({ timeout: 5 });
sql = postgres(TEST_DATABASE_URL, {
max: 2,
onnotice: () => undefined,
connection: { search_path: SCHEMA },
});
for (const file of [
'sql/008_analytics_domain_model.sql',
'sql/009_analytics_execution_metrics_governance.sql',
]) {
await sql.unsafe(fs.readFileSync(path.join(process.cwd(), file), 'utf8'));
}
// A dataset and a metric to govern.
await sql.unsafe(`
INSERT INTO opt_analytics_dataset
(dataset_id, tenant_id, project_id, name, tier, schema_contract_id, schema_contract_version,
owner_id, source_ref, freshness_slo_seconds, retention_days, classification, status)
VALUES ('ds_sales','t_alpha','p_main','sales','SERVING','c_sales','1.0.0',
'u_1','0pt://sourcing/sales', 3600, 90, 'none', 'active')
ON CONFLICT DO NOTHING;`);
}, 120_000);
afterAll(async () => {
if (!TEST_DATABASE_URL || !sql) return;
await sql.unsafe(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`);
await sql.end({ timeout: 5 });
});
run('sql/009 applies, and replays', () => {
it('is idempotent — a replay onto an already-migrated schema succeeds', async () => {
const text = fs.readFileSync(
path.join(process.cwd(), 'sql/009_analytics_execution_metrics_governance.sql'),
'utf8',
);
// The restore drill replays every file in order onto a live database.
await expect(sql.unsafe(text)).resolves.toBeDefined();
});
it('added every BI-P018 column the execution record needs', async () => {
const rows = await sql.unsafe(
`SELECT column_name FROM information_schema.columns
WHERE table_schema = '${SCHEMA}' AND table_name = 'opt_analytics_query_execution'`,
);
const names = new Set((rows as unknown as Array<{ column_name: string }>).map((r) => r.column_name));
for (const col of [
'principal_id',
'workload',
'compiled_query_hash',
'datasets',
'metrics',
'cache_status',
'cost_units',
]) {
expect(names.has(col), `missing ${col}`).toBe(true);
}
// And the one it must NOT have.
expect(names.has('query_text')).toBe(false);
expect(names.has('sql')).toBe(false);
});
});
run('BI-P031 — a CERTIFIED metric cannot be modified in place, enforced by the DATABASE', () => {
const base = '';
beforeAll(async () => {
await sql.unsafe(`${base}
INSERT INTO opt_analytics_metric_definition
(metric_id, tenant_id, project_id, name, dataset_id, aggregation, measure_field,
allowed_dimension_ids, current_version, owner_id, description,
metric_type, time_dimension, unit, currency, display_format, status, filters_json,
certification, business_definition, technical_definition, meaning_hash,
certified_at, certified_by)
VALUES ('m_revenue','t_alpha','p_main','net_revenue','ds_sales','sum','amount_sek',
ARRAY['country'], 3, 'finance@siax.io', 'Invoiced revenue net of credits',
'simple','invoiced_at','SEK','SEK','currency','ACTIVE','[]',
'certified','What we invoiced','sum(amount_sek)', repeat('a',64),
now(), 'u_1')
ON CONFLICT (metric_id) DO NOTHING;`);
});
it('REFUSES an in-place change to the meaning hash', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} UPDATE opt_analytics_metric_definition
SET meaning_hash = repeat('b',64) WHERE metric_id = 'm_revenue'`),
);
expect(message, "a certified metric's meaning was changed in place, in the database").toBeDefined();
expect(message).toContain('BI-P031');
expect(message).toContain('mint version 4');
});
it('ALLOWS an editorial change that leaves the meaning hash alone', async () => {
await expect(
sql.unsafe(`${base} UPDATE opt_analytics_metric_definition
SET description = 'Clearer wording' WHERE metric_id = 'm_revenue'`),
).resolves.toBeDefined();
});
it('ALLOWS a meaning change that comes with a version bump', async () => {
await expect(
sql.unsafe(`${base} UPDATE opt_analytics_metric_definition
SET meaning_hash = repeat('c',64), current_version = 4
WHERE metric_id = 'm_revenue'`),
).resolves.toBeDefined();
// Put it back for the remaining assertions.
await sql.unsafe(`${base} UPDATE opt_analytics_metric_definition
SET current_version = 3 WHERE metric_id = 'm_revenue'`);
});
it('refuses a currency-formatted metric with no currency', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} INSERT INTO opt_analytics_metric_definition
(metric_id, tenant_id, project_id, name, dataset_id, aggregation, measure_field,
owner_id, display_format, currency, time_dimension)
VALUES ('m_bad','t_alpha','p_main','bad_metric','ds_sales','sum','x','u','currency',NULL,'t')`),
);
expect(message).toContain('currency_pairing');
});
it('refuses a currency on a non-currency format', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} INSERT INTO opt_analytics_metric_definition
(metric_id, tenant_id, project_id, name, dataset_id, aggregation, measure_field,
owner_id, display_format, currency, time_dimension)
VALUES ('m_bad2','t_alpha','p_main','bad_metric2','ds_sales','sum','x','u','integer','SEK','t')`),
);
expect(message).toContain('currency_pairing');
});
it('refuses certification without an actor, a time, and both definitions', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} INSERT INTO opt_analytics_metric_definition
(metric_id, tenant_id, project_id, name, dataset_id, aggregation, measure_field,
owner_id, display_format, time_dimension, certification)
VALUES ('m_bad3','t_alpha','p_main','bad_metric3','ds_sales','sum','x','u','decimal','t','certified')`),
);
expect(message).toContain('certification_act');
});
it('refuses an unknown lifecycle status', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} UPDATE opt_analytics_metric_definition
SET status = 'PROBABLY_FINE' WHERE metric_id = 'm_revenue'`),
);
expect(message).toContain('metric_status');
});
});
run('BI-P030 — a published semantic model version is immutable, and only one is active', () => {
const base = '';
beforeAll(async () => {
for (const [id, version, status] of [
['smv_1', 1, 'active'],
['smv_2', 2, 'draft'],
] as const) {
await sql.unsafe(`${base}
INSERT INTO opt_analytics_semantic_model_version
(semantic_model_version_id, model_id, tenant_id, project_id, version,
datasets, relationships_json, metrics_json, dimensions_json, status, hash)
VALUES ('${id}','sm_sales','t_alpha','p_main',${version},
ARRAY['ds_sales'],'[]','[]','[]','${status}', repeat('${version}',64))
ON CONFLICT DO NOTHING;`);
}
});
it("REFUSES an update to a published version's content", async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} UPDATE opt_analytics_semantic_model_version
SET metrics_json = '[{"id":"m_new"}]' WHERE semantic_model_version_id = 'smv_1'`),
);
expect(message, 'a pinned semantic model version was rewritten under a dashboard').toBeDefined();
expect(message).toContain('BI-P030');
});
it('ALLOWS a status transition, which is not a content change', async () => {
await expect(
sql.unsafe(`${base} UPDATE opt_analytics_semantic_model_version
SET status = 'superseded' WHERE semantic_model_version_id = 'smv_1'`),
).resolves.toBeDefined();
await sql.unsafe(`${base} UPDATE opt_analytics_semantic_model_version
SET status = 'active' WHERE semantic_model_version_id = 'smv_1'`);
});
it('refuses TWO active versions of the same model — half the dashboards would read the other one', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} UPDATE opt_analytics_semantic_model_version
SET status = 'active' WHERE semantic_model_version_id = 'smv_2'`),
);
expect(message).toContain('opt_analytics_semantic_model_one_active');
});
it('refuses a hash that is not a sha256 digest', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base}
INSERT INTO opt_analytics_semantic_model_version
(semantic_model_version_id, model_id, tenant_id, project_id, version,
datasets, relationships_json, metrics_json, dimensions_json, status, hash)
VALUES ('smv_bad','sm_sales','t_alpha','p_main',9,ARRAY['ds_sales'],'[]','[]','[]','draft','not-a-hash')`),
);
expect(message).toBeDefined();
});
});
run('BI-P018 / BI-P021 — the execution record and the usage ledger', () => {
const base = '';
it('refuses a compiled_query_hash that is not a 64-hex digest', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} INSERT INTO opt_analytics_query_execution
(execution_id, tenant_id, project_id, engine_query_id, state, provider, compiled_query_hash)
VALUES ('e_bad','t_alpha','p_main','q1','queued','clickhouse','SELECT * FROM sales')`),
);
expect(message).toContain('hash_shape');
});
it('accepts a proper execution record', async () => {
await expect(
sql.unsafe(`${base} INSERT INTO opt_analytics_query_execution
(execution_id, tenant_id, project_id, engine_query_id, state, provider,
compiled_query_hash, principal_id, workload, cache_status, cost_units)
VALUES ('e_ok','t_alpha','p_main','q1','succeeded','clickhouse',
repeat('a',64),'u_1','dashboard','hit',0.5)`),
).resolves.toBeDefined();
});
it('refuses an unknown cache status and an unknown workload', async () => {
expect(
await refusalOf(() =>
sql.unsafe(`${base} UPDATE opt_analytics_query_execution
SET cache_status = 'probably' WHERE execution_id = 'e_ok'`),
),
).toContain('cache_status');
expect(
await refusalOf(() =>
sql.unsafe(`${base} UPDATE opt_analytics_query_execution
SET workload = 'vibes' WHERE execution_id = 'e_ok'`),
),
).toContain('workload');
});
it('the usage ledger is APPEND-ONLY — update and delete both raise', async () => {
await sql.unsafe(`${base} INSERT INTO opt_analytics_usage_ledger
(usage_id, tenant_id, principal_id, query_id, engine, rows_scanned, bytes_scanned,
execution_ms, cost_units, terminated_by_budget)
VALUES ('u_1','t_alpha','p_1','q1','clickhouse',1000,2000,50,0.25,true)`);
expect(
await refusalOf(() =>
sql.unsafe(`${base} UPDATE opt_analytics_usage_ledger SET cost_units = 0 WHERE usage_id = 'u_1'`),
),
'a billing row was editable',
).toBeDefined();
expect(
await refusalOf(() =>
sql.unsafe(`${base} DELETE FROM opt_analytics_usage_ledger WHERE usage_id = 'u_1'`),
),
'a billing row was deletable',
).toBeDefined();
});
it('an analyst statement refusal must carry a reason', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} INSERT INTO opt_analytics_sql_statement
(statement_id, tenant_id, principal_id, statement_normalized, statement_hash, outcome)
VALUES ('s_bad','t_alpha','u_1','SELECT ?', repeat('a',64), 'refused')`),
);
expect(message, 'a refusal with no reason was accepted — an unreviewable audit trail').toBeDefined();
});
it('a freshness row must carry a disclosure a UI can render', async () => {
const message = await refusalOf(() =>
sql.unsafe(`${base} INSERT INTO opt_analytics_dataset_freshness
(tenant_id, dataset_id, state, expected_interval_ms, disclosure)
VALUES ('t_alpha','ds_sales','STALE',3600000,' ')`),
);
expect(message).toBeDefined();
});
it('freshness defaults to UNKNOWN, never to FRESH', async () => {
await sql.unsafe(`${base} INSERT INTO opt_analytics_dataset_freshness
(tenant_id, dataset_id, expected_interval_ms, disclosure)
VALUES ('t_beta','ds_sales',3600000,'not yet computed')`);
const rows = await sql.unsafe(`${base} SELECT state FROM opt_analytics_dataset_freshness
WHERE tenant_id = 't_beta'`);
expect((rows as unknown as Array<{ state: string }>)[0].state).toBe('UNKNOWN');
});
});
@@ -0,0 +1,521 @@
/**
* BI-P129 — ANALYTICS DATA INGESTION.
*
* DoD: "Two real source types ingest into canonical analytics tiers."
*
* The two source types here are the REAL P061 connectors, sharing no code but
* the contract: a JSONL file on actual disk, and an HTTP JSON API served by a
* real `fetch` implementation over a real request/response cycle. Both go
* through the REAL P062 ingestion runner and the REAL landing sink into a
* declared tier. Nothing about the tier or the contract is stubbed.
*
* Every gate is attacked TWICE: once with the guard in place (it must
* refuse), and once in a counterfactual that removes only the guard (it must
* succeed). A guard whose counterfactual also fails is not a guard — the
* behaviour was coming from somewhere else, and the estate has shipped three
* of those this month.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { InMemoryIngestionRepository } from '@/src/repositories/in-memory-ingestion-repository';
import { SchemaRegistry } from '@/src/schema/schema-registry';
import { LineageStore } from '@/src/lineage/lineage-store';
import { SiaxError } from '@/src/platform/errors';
import type { RecordSchemaFields } from '@/src/schema/record-schema';
import {
ConnectorProviderRegistry,
assertContractCoversDiscovery,
assertLandingTierIngestible,
assertPhysicalHomeMatchesTier,
assertProviderRunnable,
contractCoverageProblems,
planAnalyticsIngestion,
type AnalyticsConnectorProvider,
type AnalyticsIngestionSpec,
type AnalyticsLandingTarget,
} from '@/src/analytics/ingestion/connector-provider';
import { NativeConnectorProvider } from '@/src/analytics/ingestion/native-provider';
import { InMemoryLandingWriter, assertDiscoveryLandable } from '@/src/analytics/ingestion/landing';
import { AnalyticsIngestionService } from '@/src/analytics/ingestion/analytics-ingestion-service';
import type { DatasetContract } from '@/src/analytics/domain/contract';
// ── fixtures ───────────────────────────────────────────────────────────────
const SOURCE_SCHEMA: RecordSchemaFields = {
org_number: { type: 'string', required: true },
name: { type: 'string', required: true },
employees: { type: 'number', required: false },
};
const CONTRACT: DatasetContract = {
dataset_id: 'ds_companies_raw',
version: '1.0.0',
tier: 'RAW',
fields: [
{ name: 'org_number', type: 'string', nullable: false, role: 'identifier', primary_identifier: true },
{ name: 'name', type: 'string', nullable: false, role: 'dimension' },
{ name: 'employees', type: 'int64', nullable: true, role: 'measure' },
],
primary_identifiers: ['org_number'],
dimensions: ['name'],
measures: ['employees'],
freshness_slo_seconds: 86_400,
retention_days: 3650,
pii_classification: 'none',
source_lineage: ['bolagsverket'],
quality_rules: [],
allowed_purposes: ['analytics'],
};
function target(overrides: Partial<AnalyticsLandingTarget> = {}): AnalyticsLandingTarget {
return {
dataset_id: 'ds_companies_raw',
tier: 'RAW',
contract: CONTRACT,
physical: { format: 'parquet', namespace: 'analytics_raw', table_name: 'companies' },
...overrides,
};
}
const ROWS = Array.from({ length: 9 }, (_, i) => ({
org_number: `55600${i}-000${i}`,
name: `Bolag ${i} AB`,
employees: (i + 1) * 10,
}));
const tmpDir = path.join(os.tmpdir(), `opt-bi129-${process.pid}`);
const filePath = path.join(tmpDir, 'companies.jsonl');
beforeAll(async () => {
await fs.mkdir(tmpDir, { recursive: true });
await fs.writeFile(filePath, ROWS.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
});
afterAll(async () => {
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
});
/**
* A real HTTP JSON source: an actual fetch implementation returning real
* `Response` objects, paging by an opaque server token. The connector under
* test does a genuine request/response cycle against it — the seam is the
* transport, not the connector.
*/
function httpSourceFetch(): (url: string, init: RequestInit) => Promise<Response> {
return async (url: string) => {
const parsed = new URL(url);
if (parsed.pathname.endsWith('/health')) {
return new Response(JSON.stringify({ ok: true }), { status: 200 });
}
const cursor = parsed.searchParams.get('cursor');
const limit = Number(parsed.searchParams.get('limit') ?? '100');
const offset = cursor ? Number(cursor) : 0;
const page = ROWS.slice(offset, offset + limit);
const nextOffset = offset + page.length;
return new Response(
JSON.stringify({
records: page,
next_cursor: nextOffset < ROWS.length ? String(nextOffset) : undefined,
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
);
};
}
function jsonlSpec(overrides: Partial<AnalyticsIngestionSpec> = {}): AnalyticsIngestionSpec {
return {
source_id: 'src_jsonl',
tenant_id: 't_test',
project_id: 'p_test',
mode: 'batch',
provider: 'native',
connector_ref: 'jsonl_file',
config: {
file_path: filePath,
partition_key: 'companies',
schema: SOURCE_SCHEMA,
record_key_field: 'org_number',
},
target: target(),
...overrides,
};
}
function httpSpec(overrides: Partial<AnalyticsIngestionSpec> = {}): AnalyticsIngestionSpec {
return {
source_id: 'src_http',
tenant_id: 't_test',
project_id: 'p_test',
mode: 'batch',
provider: 'native',
connector_ref: 'http_json',
config: {
base_url: 'http://source.invalid',
records_path: '/v1/companies',
partition_key: 'companies',
schema: SOURCE_SCHEMA,
record_key_field: 'org_number',
record_cursor_field: 'org_number',
health_path: '/health',
},
target: target({ dataset_id: 'ds_companies_raw' }),
...overrides,
};
}
let repo: InMemoryIngestionRepository;
let writer: InMemoryLandingWriter;
let service: AnalyticsIngestionService;
function buildService(runtimeEnv = 'test'): AnalyticsIngestionService {
repo = new InMemoryIngestionRepository();
writer = new InMemoryLandingWriter();
return new AnalyticsIngestionService({
repo,
schemas: new SchemaRegistry(repo),
lineage: new LineageStore(repo),
writer,
runtimeEnv,
});
}
beforeEach(() => {
service = buildService();
});
// ── DoD: two real source types land in a canonical tier ────────────────────
describe('BI-P129 DoD — two real source types ingest into canonical analytics tiers', () => {
it('source type 1 (JSONL file on disk) lands every row in the declared RAW tier', async () => {
const result = await service.ingest(new NativeConnectorProvider(), jsonlSpec(), { page_size: 4 });
expect(result.run.status).toBe('succeeded');
expect(writer.rowsLanded).toBe(ROWS.length);
expect(writer.batches.every((b) => b.tier === 'RAW')).toBe(true);
expect(writer.batches.every((b) => b.dataset_id === 'ds_companies_raw')).toBe(true);
expect(writer.batches.every((b) => b.format === 'parquet')).toBe(true);
expect(writer.batches.every((b) => b.namespace === 'analytics_raw')).toBe(true);
// Paged: 4 + 4 + 1, so the tier landing is exercised across batches.
expect(writer.batches.length).toBeGreaterThan(1);
});
it('source type 2 (HTTP JSON API, opaque page token) lands every row in the same tier', async () => {
const provider = new NativeConnectorProvider(httpSourceFetch());
const result = await service.ingest(provider, httpSpec(), { page_size: 4 });
expect(result.run.status).toBe('succeeded');
expect(writer.rowsLanded).toBe(ROWS.length);
expect(writer.batches.every((b) => b.tier === 'RAW')).toBe(true);
expect(new Set(writer.batches.flatMap((b) => b.envelope_ids)).size).toBe(ROWS.length);
});
it('the two source types share no connector code — different ids, versions and cursor vocabulary', async () => {
const nativeProvider = new NativeConnectorProvider(httpSourceFetch());
const jsonl = nativeProvider.connectorFor(jsonlSpec());
const http = nativeProvider.connectorFor(httpSpec());
expect(jsonl.connector_id).toBe('jsonl_file');
expect(http.connector_id).toBe('http_json');
expect(jsonl.connector_version).not.toBe(http.connector_version);
expect(Object.getPrototypeOf(jsonl)).not.toBe(Object.getPrototypeOf(http));
});
});
// ── gate 1: landing tier ───────────────────────────────────────────────────
describe('BI-P129 gate 1 — ingestion may not land directly in a derived tier', () => {
it('WITH the guard: landing in SERVING is refused', () => {
expect(() => assertLandingTierIngestible(target({ tier: 'SERVING' }))).toThrow(
/may not land directly in SERVING/,
);
expect(() => assertLandingTierIngestible(target({ tier: 'CURATED' }))).toThrow(
/may not land directly in CURATED/,
);
});
it('WITHOUT the guard: the same spec lands source rows into a dashboard-readable tier', async () => {
// Counterfactual — the service is bypassed and the sink is called directly,
// which is exactly what a provider that skipped the gate would do.
const { landingSink } = await import('@/src/analytics/ingestion/landing');
const bypassWriter = new InMemoryLandingWriter();
const sink = landingSink({
target: target({ tier: 'SERVING' }),
tenant_id: 't_test',
project_id: 'p_test',
run_id: 'run_bypass',
writer: bypassWriter,
});
await sink([
{
envelope_id: 'e1',
source_id: 'src_jsonl',
tenant_id: 't_test',
project_id: 'p_test',
mode: 'batch',
operation: 'upsert',
partition_key: 'companies',
record_key: '1',
schema_version: 1,
sequence: 1,
ingested_at: new Date().toISOString(),
payload: { org_number: '1', name: 'x' },
provenance: { connector_id: 'jsonl_file', connector_version: 'v1', run_id: 'run_bypass' },
},
]);
// Raw source rows now sit in SERVING, which BI-P003 makes readable by
// every dashboard with no exception recorded anywhere. That is the harm.
expect(bypassWriter.batches[0].tier).toBe('SERVING');
expect(bypassWriter.rowsLanded).toBe(1);
});
it('NORMALIZED without a declared normalization is a RAW dataset wearing a label', () => {
expect(() => assertLandingTierIngestible(target({ tier: 'NORMALIZED' }))).toThrow(
/declares no normalization/,
);
expect(() =>
assertLandingTierIngestible(
target({ tier: 'NORMALIZED', normalization: 'typed + deduped on org_number' }),
),
).not.toThrow();
// An all-whitespace declaration is not a declaration.
expect(() => assertLandingTierIngestible(target({ tier: 'NORMALIZED', normalization: ' ' }))).toThrow(
/declares no normalization/,
);
});
it('the service refuses a SERVING spec before it opens a session to the source', async () => {
await expect(
service.ingest(new NativeConnectorProvider(), jsonlSpec({ target: target({ tier: 'SERVING' }) })),
).rejects.toThrow(/may not land directly in SERVING/);
expect(writer.batches).toHaveLength(0);
});
});
// ── gate 2: contract covers what was discovered ────────────────────────────
describe('BI-P129 gate 2 — an undeclared source field is refused, not landed', () => {
it('WITH the guard: a new undeclared column stops the run', () => {
const drifted: RecordSchemaFields = {
...SOURCE_SCHEMA,
contact_email: { type: 'string', required: false },
};
expect(() => assertContractCoversDiscovery(CONTRACT, drifted)).toThrow(/undeclared_field/);
expect(() => assertContractCoversDiscovery(CONTRACT, drifted)).toThrow(/contact_email/);
});
it('the harm being prevented is named: an undeclared column is an unclassified column', () => {
const problems = contractCoverageProblems(CONTRACT, {
...SOURCE_SCHEMA,
personnummer: { type: 'string', required: false },
});
expect(problems).toHaveLength(1);
expect(problems[0].code).toBe('undeclared_field');
expect(problems[0].detail).toMatch(/unclassified/);
});
it('WITHOUT the guard: the drifted source lands and the PII column is invisible to the contract', async () => {
const driftedFile = path.join(tmpDir, 'drifted.jsonl');
await fs.writeFile(
driftedFile,
ROWS.map((r) => JSON.stringify({ ...r, personnummer: '19800101-1234' })).join('\n') + '\n',
'utf8',
);
const driftedSchema: RecordSchemaFields = {
...SOURCE_SCHEMA,
personnummer: { type: 'string', required: false },
};
// Counterfactual: the runner alone (no analytics gate) happily lands it.
const bypass = buildService();
const bypassWriter = writer;
const { IngestionRunner } = await import('@/src/ingestion/ingestion-runner');
const { JsonlFileConnector } = await import('@/src/connectors/jsonl-file-connector');
const { landingSink } = await import('@/src/analytics/ingestion/landing');
const runner = new IngestionRunner(repo, new SchemaRegistry(repo));
const landed: Array<Record<string, unknown> | null> = [];
const report = await runner.run({
source_id: 'src_drift',
tenant_id: 't_test',
project_id: 'p_test',
mode: 'batch',
connector: new JsonlFileConnector(),
config: {
file_path: driftedFile,
partition_key: 'companies',
schema: driftedSchema,
record_key_field: 'org_number',
},
sink: async (envelopes) => {
for (const e of envelopes) landed.push(e.payload);
await landingSink({
target: target(),
tenant_id: 't_test',
project_id: 'p_test',
run_id: 'run_drift',
writer: bypassWriter,
})(envelopes);
},
});
expect(report.status).toBe('succeeded');
expect(landed).toHaveLength(ROWS.length);
// The personal number is now sitting in a RAW table whose contract says
// pii_classification: "none". Nothing else in the pipeline notices.
expect(landed[0]).toHaveProperty('personnummer');
expect(CONTRACT.pii_classification).toBe('none');
void bypass;
});
it('a type mismatch and a missing required field are both refused', () => {
expect(() =>
assertContractCoversDiscovery(CONTRACT, {
...SOURCE_SCHEMA,
employees: { type: 'string', required: false },
}),
).toThrow(/type_mismatch/);
const { org_number: _dropped, ...withoutKey } = SOURCE_SCHEMA;
expect(() => assertContractCoversDiscovery(CONTRACT, withoutKey)).toThrow(/missing_required_field/);
});
it('a source field that is optional where the contract says NOT NULL is refused', () => {
const problems = contractCoverageProblems(CONTRACT, {
...SOURCE_SCHEMA,
name: { type: 'string', required: false },
});
expect(problems.map((p) => p.code)).toContain('nullability_mismatch');
});
it('discovery with no partitions is refused rather than reported as a clean empty run', () => {
expect(() => assertDiscoveryLandable(target(), {})).toThrow(/discovered no partitions/);
});
it('the live path runs gate 2 against what the connector actually discovered', async () => {
// The contract is fine for the file; narrow the CONTRACT instead so the
// real discovery result is what fails the gate.
const narrow: DatasetContract = { ...CONTRACT, fields: CONTRACT.fields.slice(0, 2) };
await expect(
service.ingest(new NativeConnectorProvider(), jsonlSpec({ target: target({ contract: narrow }) })),
).rejects.toThrow(/undeclared_field/);
expect(writer.batches).toHaveLength(0);
});
});
// ── gate 3: physical home ──────────────────────────────────────────────────
describe('BI-P129 gate 3 — RAW/NORMALIZED land as Parquet/Iceberg in ST0RE', () => {
it('a ClickHouse landing is refused', () => {
expect(() =>
assertPhysicalHomeMatchesTier(
target({ physical: { format: 'clickhouse' as never, namespace: 'n', table_name: 't' } }),
),
).toThrow(/not a lakehouse format/);
});
it('iceberg and parquet are both accepted; a nameless table is not', () => {
expect(() =>
assertPhysicalHomeMatchesTier(
target({ physical: { format: 'iceberg', namespace: 'n', table_name: 't' } }),
),
).not.toThrow();
expect(() =>
assertPhysicalHomeMatchesTier(
target({ physical: { format: 'parquet', namespace: ' ', table_name: 't' } }),
),
).toThrow(/missing a ST0RE namespace/);
});
});
// ── gate 4: unverified providers ───────────────────────────────────────────
class UnverifiedProvider implements AnalyticsConnectorProvider {
readonly provider = 'dlt' as const;
providerReadiness() {
return {
provider: 'dlt',
pinned_version: '0.0.0',
verified: false,
proven: [],
open: ['nothing has been executed'],
};
}
validateSpec() {
return { valid: true, errors: [] };
}
connectorFor(): never {
throw new Error('not used in this test');
}
executionPlan() {
return { runtime: 'n0d' as const, reason: 'test' };
}
}
describe('BI-P129 gate 4 — an unverified provider cannot quietly become production capability', () => {
const provider = new UnverifiedProvider();
const spec = jsonlSpec({ provider: 'dlt', connector_ref: 'whatever' });
it('WITH the guard: production refuses an unverified provider', () => {
expect(() => assertProviderRunnable(provider, spec, 'production')).toThrow(SiaxError);
expect(() => assertProviderRunnable(provider, spec, 'production')).toThrow(/verified: false/);
});
it('WITHOUT the guard (non-production runtime): the same provider is allowed to plan', () => {
expect(() => assertProviderRunnable(provider, spec, 'staging')).not.toThrow();
});
it('a recorded, named exception unblocks production — and is required to be non-empty', () => {
expect(() =>
assertProviderRunnable(provider, { ...spec, unverified_provider_exception: ' ' }, 'production'),
).toThrow(/unverified_provider_exception/);
expect(() =>
assertProviderRunnable(
provider,
{
...spec,
unverified_provider_exception: 'accepted by simon@siax.io 2026-09-07 for a bounded backfill',
},
'production',
),
).not.toThrow();
});
it('the native provider is verified, so it needs no exception in production', () => {
expect(() =>
assertProviderRunnable(new NativeConnectorProvider(), jsonlSpec(), 'production'),
).not.toThrow();
expect(new NativeConnectorProvider().providerReadiness().verified).toBe(true);
});
});
// ── licence boundary + registry ────────────────────────────────────────────
describe('BI-P129 — Airbyte is a declared kind with no acceptance in this estate', () => {
it('registering an airbyte provider is refused at the registry', () => {
const registry = new ConnectorProviderRegistry();
const fake = { ...new UnverifiedProvider(), provider: 'airbyte' as const };
expect(() => registry.register(fake as unknown as AnalyticsConnectorProvider)).toThrow(
/no licence\/architecture acceptance/,
);
});
it('planning an airbyte ingestion is refused even if a provider object is supplied directly', () => {
const fake = {
...new UnverifiedProvider(),
provider: 'airbyte' as const,
} as unknown as AnalyticsConnectorProvider;
expect(() => planAnalyticsIngestion(fake, jsonlSpec({ provider: 'airbyte' }), 'test')).toThrow(
/licence\/architecture acceptance/,
);
});
it('the registry refuses duplicates and unknown kinds, and reports readiness for what it has', () => {
const registry = new ConnectorProviderRegistry();
registry.register(new NativeConnectorProvider());
expect(() => registry.register(new NativeConnectorProvider())).toThrow(/already registered/);
expect(() => registry.get('singer')).toThrow(/no connector provider registered/);
expect(registry.readinessReport().map((r) => r.provider)).toEqual(['native']);
});
it('a provider handed a spec for a different kind is refused', () => {
expect(() =>
planAnalyticsIngestion(new NativeConnectorProvider(), jsonlSpec({ provider: 'dlt' }), 'test'),
).toThrow(/asks for provider "dlt"/);
});
});
+54
View File
@@ -0,0 +1,54 @@
/**
* The canonical BI-P005 fixture, in one place.
*
* Two jobs:
* 1. assert the encoder is DETERMINISTIC — the same columns must produce
* byte-identical output, or the "roundtrip" evidence would be comparing
* two different payloads run to run;
* 2. when ARROW_FIXTURE_DIR is set, write those exact bytes to disk so
* scripts/bi-p005-arrow-roundtrip.mjs hands pyarrow and DuckDB the bytes
* the SHIPPED module produces, not a copy of the encoder living in a
* script.
*/
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { type ArrowColumn, encodeArrowStream } from '@/src/analytics/arrow/ipc';
/** The same three rows the ClickHouse side of the DoD produces. */
export const BI_P005_FIXTURE: ArrowColumn[] = [
{ 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'),
],
},
];
describe('BI-P005 canonical Arrow fixture', () => {
it('encodes deterministically', () => {
const a = encodeArrowStream(BI_P005_FIXTURE);
const b = encodeArrowStream(BI_P005_FIXTURE);
expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true);
expect(a.length).toBeGreaterThan(0);
});
it('writes the fixture for the external roundtrip when asked', () => {
const dir = process.env.ARROW_FIXTURE_DIR;
if (!dir) return; // not an error: the normal test run has nowhere to put it
const bytes = encodeArrowStream(BI_P005_FIXTURE);
const out = path.join(dir, '02_0pt_encoded.arrow');
fs.writeFileSync(out, bytes);
expect(fs.statSync(out).size).toBe(bytes.length);
// Print the digest so the evidence file can be tied to these exact bytes.
console.log(`ARROW_FIXTURE_SHA256=${crypto.createHash('sha256').update(bytes).digest('hex')}`);
});
});
+107
View File
@@ -0,0 +1,107 @@
/**
* BI-P005 — APACHE ARROW INTERCHANGE, the part provable without a live engine.
*
* Honest scope note: the tests here run 0pt's encoder against 0pt's decoder,
* which proves internal consistency and NOT specification conformance. The
* conformance evidence comes from two places where an INDEPENDENT
* implementation reads the bytes:
*
* * tests/integration/analytics-arrow-clickhouse.integration.test.ts —
* ClickHouse (Arrow C++) both produces Arrow this decoder reads and
* consumes Arrow this encoder writes. Runs on every push in CI.
* * evidence/bi-p002-p012/bi-p005-arrow-roundtrip.json — pyarrow and DuckDB
* decoding the same bytes, executed against real containers.
*
* That distinction is the point: a self-roundtrip that agrees with its own
* mistakes is exactly the kind of green this estate has been burned by.
*/
import { describe, it, expect } from 'vitest';
import {
ARROW_TYPE_SUPPORT,
arrowStreamSettings,
assertArrowWithinResultBudget,
clickhouseArrowStreamFormat,
decodeArrowStream,
encodeArrowStream,
} from '@/src/analytics/arrow/ipc';
describe('BI-P005 Arrow IPC', () => {
it('emits a well-formed IPC stream: continuation markers, schema, batch, EOS', () => {
const bytes = encodeArrowStream([{ name: 'n', type: 'int64', values: [1, 2, 3] }]);
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
expect(dv.getUint32(0, true)).toBe(0xffffffff);
// Last 8 bytes are the end-of-stream marker: 0xFFFFFFFF then length 0.
expect(dv.getUint32(bytes.length - 8, true)).toBe(0xffffffff);
expect(dv.getInt32(bytes.length - 4, true)).toBe(0);
});
it('round-trips every supported column type with nulls', () => {
const bytes = encodeArrowStream([
{ name: 'tenant_id', type: 'utf8', values: ['t_alpha', 't_beta', null] },
{ name: 'n', type: 'int64', values: [1, 2, 3] },
{ name: 'v', type: 'float64', values: [1.5, 2.5, null] },
{ name: 'flag', type: 'bool', values: [true, false, true] },
{
name: 'ts',
type: 'timestamp_ms',
values: [new Date('2026-01-01T00:00:00Z'), null, new Date('2026-09-06T12:34:56.789Z')],
},
]);
const info = decodeArrowStream(bytes);
expect(info.rowCount).toBe(3);
expect(info.batchCount).toBe(1);
expect(info.fields.map((f) => f.name)).toEqual(['tenant_id', 'n', 'v', 'flag', 'ts']);
// Arrow Type union tags: Int=2, FloatingPoint=3, Utf8=5, Bool=6, Timestamp=10.
expect(info.fields.map((f) => f.typeType)).toEqual([5, 2, 3, 6, 10]);
});
it('handles an empty result set without producing a malformed stream', () => {
const bytes = encodeArrowStream([{ name: 'n', type: 'int64', values: [] }]);
const info = decodeArrowStream(bytes);
expect(info.rowCount).toBe(0);
expect(info.fields).toEqual([{ name: 'n', typeType: 2 }]);
});
it('rejects ragged columns rather than emitting a stream that decodes to garbage', () => {
expect(() =>
encodeArrowStream([
{ name: 'a', type: 'int64', values: [1, 2] },
{ name: 'b', type: 'int64', values: [1] },
]),
).toThrowError(/expected 2/);
expect(() => encodeArrowStream([])).toThrowError(/at least one column/);
});
it('refuses an int64 value outside the representable range instead of wrapping it', () => {
expect(() =>
encodeArrowStream([{ name: 'n', type: 'int64', values: [BigInt('9223372036854775808')] }]),
).toThrowError(/out of int64 range/);
});
it('rejects bytes that are not an Arrow IPC stream', () => {
expect(() => decodeArrowStream(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))).toThrowError(
/not an Arrow IPC stream/,
);
});
it('BI-P012: Arrow is not a way around max_result_rows', () => {
const bytes = encodeArrowStream([{ name: 'n', type: 'int64', values: [1, 2, 3, 4, 5] }]);
expect(() => assertArrowWithinResultBudget(bytes, 3)).toThrowError(/over the 3-row budget/);
expect(assertArrowWithinResultBudget(bytes, 5).rowCount).toBe(5);
});
it('the ClickHouse pass-through asks for text Strings, not Binary', () => {
expect(clickhouseArrowStreamFormat()).toBe('ArrowStream');
// Without this setting ClickHouse emits String as Arrow Binary, which
// pyarrow and DuckDB read as bytes — silent semantic loss.
expect(arrowStreamSettings().output_format_arrow_string_as_string).toBe('1');
});
it('documents the supported type mapping including where loss WOULD occur', () => {
expect(ARROW_TYPE_SUPPORT.length).toBeGreaterThanOrEqual(5);
const arrowTypes = ARROW_TYPE_SUPPORT.map((r) => r.arrow);
expect(new Set(arrowTypes)).toEqual(new Set(['int64', 'float64', 'utf8', 'bool', 'timestamp_ms']));
// Every row states its caveat; an empty note would be a silent promise.
for (const row of ARROW_TYPE_SUPPORT) expect(row.note.length).toBeGreaterThan(10);
});
});
+194
View File
@@ -0,0 +1,194 @@
/**
* tests/analytics/benchmark-harness.test.ts
* ==========================================
* BI-P104 — the harness's job is to stop a benchmark from lying.
*
* The tests are therefore attacks on the reporting, not on the timing:
*
* - two overlapping distributions whose MEDIANS differ 2x must come back
* `indistinguishable`, because that is the claim a noisy host manufactures;
* - the real 150x/130x pair from yesterday's budget-enforcement lane is fed
* in as data, and the harness must describe a RANGE rather than pick one;
* - a three-sample run must refuse to be compared at all;
* - every sentence `describeComparison` produces must carry the range, the
* sample size and the stability, so it cannot be quoted as a bare figure;
* - an engine that was not run must appear in the evidence with a reason.
*/
import { describe, expect, it } from 'vitest';
import {
BENCH_ENGINES,
buildEvidence,
compareDistributions,
describeComparison,
measure,
MIN_SAMPLES,
summarizeSamples,
} from '@/src/analytics/bench/benchmark-harness';
describe('BI-P104 distribution summary', () => {
it('reports the shape, and never a single number', () => {
const d = summarizeSamples([10, 11, 12, 13, 14, 15, 16, 40]);
expect(d.n).toBe(8);
expect(d.min).toBe(10);
expect(d.max).toBe(40);
expect(d.p50).toBe(13);
expect(d.spread_ratio).toBe(4);
expect(d.cv).toBeGreaterThan(0);
// Every field a reader needs to judge the p50 is present next to it.
for (const key of [
'min',
'p50',
'p95',
'p99',
'max',
'stdev',
'cv',
'iqr',
'spread_ratio',
'stability',
]) {
expect(Object.keys(d)).toContain(key);
}
});
it('calls a tight run stable and a spread run unstable', () => {
expect(summarizeSamples([100, 101, 99, 100, 102, 98, 100]).stability).toBe('stable');
expect(summarizeSamples([10, 200, 15, 400, 12, 350, 11]).stability).toBe('unstable');
});
it('refuses to characterise fewer than MIN_SAMPLES', () => {
const d = summarizeSamples([10, 11, 12]);
expect(d.n).toBe(3);
expect(d.stability).toBe('insufficient_samples');
expect(MIN_SAMPLES).toBeGreaterThan(3);
});
});
describe('BI-P104 comparison — variance beats a flattering median', () => {
it('overlapping ranges are INDISTINGUISHABLE even when medians differ 2x', () => {
const baseline = summarizeSamples([50, 60, 200, 70, 300, 55, 65, 280]);
const candidate = summarizeSamples([25, 30, 190, 35, 260, 28, 33, 240]);
const c = compareDistributions(baseline, candidate);
expect(c.p50_ratio).toBeGreaterThan(1.5); // the tempting headline
expect(c.ranges_overlap).toBe(true);
expect(c.verdict).toBe('indistinguishable'); // the honest verdict
expect(describeComparison(c)).toMatch(/INDISTINGUISHABLE/);
});
it('clean separation is reported as faster, WITH the range', () => {
const baseline = summarizeSamples([500, 520, 510, 530, 505, 515, 525]);
const candidate = summarizeSamples([50, 55, 52, 58, 51, 53, 54]);
const c = compareDistributions(baseline, candidate);
expect(c.verdict).toBe('faster');
const sentence = describeComparison(c, 'pre-aggregate');
expect(sentence).toMatch(/FASTER/);
expect(sentence).toMatch(/x to /); // a range, not a number
expect(sentence).toMatch(/n=7\/7/); // sample sizes
expect(sentence).toMatch(/stability/);
});
it('the real 150x / 130x overshoot pair is described as a range, not a figure', () => {
// Two runs of the same measurement on the same machine, from the BI-P021
// budget-enforcement lane. A harness that picks one of these is lying.
const overshoot = summarizeSamples([153, 131, 149, 128, 144, 137, 152, 126, 141]);
// Worth being precise about: by the CV test this run is STABLE (0.07). The
// problem was never instability — it is that a stable run still spans
// 126x-153x, so any single figure quoted from it is ~20% wrong. The
// harness's answer is to keep the ends attached to the middle.
expect(overshoot.stability).toBe('stable');
expect(overshoot.min).toBe(126);
expect(overshoot.p50).toBe(141);
expect(overshoot.max).toBe(153);
expect(overshoot.spread_ratio).toBeCloseTo(1.21, 2);
const sentence = describeComparison(
compareDistributions(summarizeSamples([1, 1, 1, 1, 1, 1, 1, 1, 1]), overshoot),
'budget overshoot factor',
);
expect(sentence).toMatch(/x to /); // a range survives into the prose
expect(sentence).toMatch(/n=9\/9/);
});
it('a three-sample run cannot be compared at all', () => {
const c = compareDistributions(summarizeSamples([10, 11, 12]), summarizeSamples([1, 2, 3]));
expect(c.verdict).toBe('not_comparable');
expect(describeComparison(c)).toMatch(/anecdote/);
});
it('slower is reported as slower — the harness has no favourite', () => {
const baseline = summarizeSamples([50, 51, 52, 53, 54, 55, 56]);
const candidate = summarizeSamples([500, 510, 520, 530, 540, 550, 560]);
expect(compareDistributions(baseline, candidate).verdict).toBe('slower');
});
});
describe('BI-P104 measurement', () => {
it('records warmups but excludes them from the statistics', async () => {
let call = 0;
let clock = 0;
const run = await measure({
engine: 'duckdb',
dataset: 'small_saas',
query_label: 'group by day',
warmups: 2,
repetitions: 6,
// A cold first pair (1000ms) then a warm steady state (10ms).
now: () => {
const t = clock;
clock += call <= 2 ? 1000 : 10;
call += 1;
return t;
},
run: async () => ({ rows: 42 }),
});
expect(run.warmup_ms).toHaveLength(2);
expect(run.samples_ms).toHaveLength(6);
expect(run.distribution.n).toBe(6);
expect(run.distribution.max).toBeLessThan(1000); // the cold pair is not in it
expect(run.rows_returned).toBe(42);
});
});
describe('BI-P104 evidence', () => {
it('lists every engine BI-P104 names, and says why the unrun ones were not run', () => {
const evidence = buildEvidence({
host_note: 'one idle host, warm cache',
engines: [
{ engine: 'clickhouse', available: true, version: '26.3' },
{ engine: 'duckdb', available: true, version: '1.5.5' },
{ engine: 'trino', available: false, reason: 'the running Trino belongs to another lane' },
],
runs: [
{
engine: 'clickhouse',
dataset: 'small_saas',
query_label: 'q',
warmup_ms: [1],
samples_ms: [1, 2, 3, 4, 5],
distribution: summarizeSamples([1, 2, 3, 4, 5]),
},
],
});
expect(evidence.engines.map((e) => e.engine)).toEqual([...BENCH_ENGINES]);
const notRun = evidence.not_exercised.map((e) => e.engine);
expect(notRun).toContain('superset');
expect(notRun).toContain('perspective');
expect(notRun).toContain('duckdb'); // declared available but produced no run
for (const e of evidence.not_exercised) {
expect(e.reason, e.engine).toBeTruthy();
}
expect(evidence.datasets.map((d) => d.id)).toEqual([
'small_saas',
'medium_business',
'vehiq_market',
'large_event',
'wide_table',
'geospatial',
]);
});
});
+293
View File
@@ -0,0 +1,293 @@
/**
* tests/analytics/bi-slo.test.ts
* ===============================
* BI-P103 — BI SLO, and the AUD0 usage events it is measured from.
*
* Two failure modes are attacked directly, because both look like a healthy
* dashboard:
*
* 1. AN SLO REPORT OVER SILENCE. Zero events must not read as 100%
* availability. Every objective in an empty window must come back
* `insufficient_data`, and `fully_measured` must be false.
* 2. A PRODUCER THAT LEAKS. The emitter is handed an execution record
* carrying SQL text, a database error message quoting a personnummer,
* filter VALUES, a tenant id and a result sample — everything AUD0's
* BI-P076 ingest exists to refuse — and none of it may appear in any
* emitted payload. The test greps the serialized events, and first
* proves the grep finds those strings in the INPUT so a clean result
* cannot be a broken detector.
*/
import { describe, expect, it } from 'vitest';
import {
BI_SLO_CATALOGUE,
evaluateBiSlos,
percentile,
summariseSloReport,
type SloResult,
} from '@/src/analytics/slo/bi-slo';
import {
biUsageEventsForExecution,
EMITTABLE_PAYLOAD_KEYS,
type Aud0BiEvent,
type ExecutionTelemetry,
} from '@/src/analytics/slo/usage-events';
const FROM = new Date('2026-09-07T00:00:00.000Z');
const TO = new Date('2026-09-07T23:59:59.000Z');
function queryEvents(args: {
n: number;
surface: 'dashboard' | 'explore';
outcome: 'completed' | 'failed' | 'running';
durationMs: (i: number) => number;
cacheHit?: boolean;
idPrefix?: string;
}): Aud0BiEvent[] {
const out: Aud0BiEvent[] = [];
for (let i = 0; i < args.n; i += 1) {
const t: ExecutionTelemetry = {
query_id: `${args.idPrefix ?? args.surface}_${i}`,
surface: args.surface,
state: args.outcome === 'completed' ? 'succeeded' : args.outcome === 'failed' ? 'failed' : 'running',
started_at: new Date(FROM.getTime() + i * 1000).toISOString(),
finished_at: new Date(FROM.getTime() + i * 1000 + args.durationMs(i)).toISOString(),
duration_ms: args.durationMs(i),
...(args.cacheHit !== undefined ? { cache_hit: args.cacheHit } : {}),
...(args.outcome === 'failed' ? { error_code: 'TIMEOUT' } : {}),
};
out.push(...biUsageEventsForExecution(t));
}
return out;
}
function byId(results: SloResult[], id: string): SloResult {
const r = results.find((x) => x.objective_id === id);
if (!r) throw new Error(`no result for ${id}`);
return r;
}
describe('BI-P103 — an SLO over silence is not a met SLO', () => {
it('an empty window makes every measurable objective insufficient_data, never 100%', () => {
const report = evaluateBiSlos({ events: [], from: FROM, to: TO });
expect(report.fully_measured).toBe(false);
for (const r of report.results) {
expect(['insufficient_data', 'not_measurable_here']).toContain(r.status);
expect(r.status).not.toBe('met');
}
const summary = summariseSloReport(report);
expect(summary.met).toBe(0);
expect(summary.measured_fraction).toBe(0);
});
it('a started query that never finished is unresolved, not a success', () => {
const events = queryEvents({ n: 200, surface: 'dashboard', outcome: 'running', durationMs: () => 100 });
const report = evaluateBiSlos({ events, from: FROM, to: TO });
expect(report.unresolved_queries).toBe(200);
expect(byId(report.results, 'dash.availability').status).toBe('insufficient_data');
expect(byId(report.results, 'dash.availability').observed).toBeUndefined();
});
it('a percentile below min_samples is reported WITH its sample size and not judged', () => {
const events = queryEvents({
n: 12,
surface: 'explore',
outcome: 'completed',
durationMs: (i) => 1000 + i * 10,
});
const p99 = byId(evaluateBiSlos({ events, from: FROM, to: TO }).results, 'explore.p99');
expect(p99.status).toBe('insufficient_data');
expect(p99.low_confidence).toBe(true);
expect(p99.sample_size).toBe(12);
expect(p99.observed).toBeDefined(); // reported…
expect(p99.detail).toMatch(/not a percentile/); // …with the caveat attached
});
it('freshness and delivery are declared not_measurable_here rather than proxied', () => {
const report = evaluateBiSlos({ events: [], from: FROM, to: TO });
const freshness = byId(report.results, 'dash.freshness');
const delivery = byId(report.results, 'report.delivery_sla');
expect(freshness.status).toBe('not_measurable_here');
expect(freshness.detail).toMatch(/analytics_freshness_watermark/);
expect(delivery.status).toBe('not_measurable_here');
expect(delivery.detail).toMatch(/n0tify_delivery_receipt/);
});
});
describe('BI-P103 — real measurement from real events', () => {
it('computes availability, error rate and both dashboard latencies', () => {
const events = [
...queryEvents({
n: 180,
surface: 'dashboard',
outcome: 'completed',
cacheHit: false,
durationMs: (i) => 500 + i * 10,
idPrefix: 'cold',
}),
...queryEvents({
n: 120,
surface: 'dashboard',
outcome: 'completed',
cacheHit: true,
durationMs: () => 120,
idPrefix: 'warm',
}),
...queryEvents({
n: 3,
surface: 'dashboard',
outcome: 'failed',
durationMs: () => 900,
idPrefix: 'bad',
}),
];
const { results } = evaluateBiSlos({ events, from: FROM, to: TO });
const availability = byId(results, 'dash.availability');
expect(availability.sample_size).toBe(303);
expect(availability.observed).toBeCloseTo(300 / 303, 6);
expect(availability.status).toBe('breached'); // 0.9901 < 0.995 target
const errorRate = byId(results, 'dash.error_rate');
expect(errorRate.observed).toBeCloseTo(3 / 303, 6);
const cold = byId(results, 'dash.p95_first_query');
expect(cold.sample_size).toBe(183); // 180 cold + 3 failures, which had no cache hit
expect(cold.status).toBe('met');
const cached = byId(results, 'dash.p95_cached');
expect(cached.sample_size).toBe(120);
expect(cached.observed).toBe(120);
expect(cached.status).toBe('met');
});
it('a breach is reported as a breach', () => {
const events = queryEvents({
n: 60,
surface: 'dashboard',
outcome: 'completed',
cacheHit: false,
durationMs: () => 9000,
});
expect(
byId(evaluateBiSlos({ events, from: FROM, to: TO }).results, 'dash.p95_first_query'),
).toMatchObject({ status: 'breached', observed: 9000 });
});
it('events outside the window do not count', () => {
const events = queryEvents({ n: 200, surface: 'dashboard', outcome: 'completed', durationMs: () => 100 });
const report = evaluateBiSlos({
events,
from: new Date('2026-09-08T00:00:00.000Z'),
to: new Date('2026-09-08T23:59:59.000Z'),
});
expect(byId(report.results, 'dash.availability').status).toBe('insufficient_data');
});
it('percentile is nearest-rank — it never invents a value nobody experienced', () => {
const sample = [10, 20, 30, 40];
expect(percentile(sample, 0.95)).toBe(40);
expect(percentile(sample, 0.5)).toBe(20);
expect(percentile([], 0.95)).toBeUndefined();
});
it('the catalogue covers all three workload classes and every field BI-P103 names', () => {
const kinds = new Set(BI_SLO_CATALOGUE.map((o) => `${o.workload}:${o.kind}`));
for (const expected of [
'interactive_dashboard:availability',
'interactive_dashboard:latency_p95_first',
'interactive_dashboard:latency_p95_cached',
'interactive_dashboard:error_rate',
'interactive_dashboard:freshness',
'exploration:latency_p95',
'exploration:latency_p99',
'exploration:max_result_rows',
'exploration:timeout',
'report:completion_sla',
'report:delivery_sla',
]) {
expect(kinds.has(expected), expected).toBe(true);
}
});
});
describe('BI-P103 — the producer cannot leak a result into AUD0', () => {
const hostile: ExecutionTelemetry = {
query_id: 'q_1',
compiled_query_hash: 'f'.repeat(64),
compiled_sql: "SELECT * FROM customers WHERE personnummer = '19800101-1234'",
error_message: 'duplicate key value violates unique constraint (personnummer)=(19800101-1234)',
error_code: 'CONFLICT',
tenant_id: 't_alpha',
dataset_id: 'ds_sales',
engine: 'clickhouse',
surface: 'dashboard',
state: 'failed',
started_at: '2026-09-07T10:00:00.000Z',
finished_at: '2026-09-07T10:00:02.000Z',
duration_ms: 2000,
filter_keys: ['region'],
filter_values: { region: ['Gotland'] },
result_sample: [{ customer: 'Anna Andersson', revenue: 42 }],
metric_name: 'revenue',
dashboard_id: 'dash_sales',
widget_count: 4,
};
it('emits none of the forbidden material', () => {
const events = biUsageEventsForExecution(hostile);
const serialized = JSON.stringify(events);
// The detector must be able to find these strings — they are in the input.
const input = JSON.stringify(hostile);
for (const secret of ['19800101-1234', 'Anna Andersson', 'Gotland', 't_alpha', 'SELECT *']) {
expect(input, `detector check for ${secret}`).toContain(secret);
}
for (const secret of [
'19800101-1234',
'Anna Andersson',
'Gotland',
't_alpha',
'SELECT *',
'duplicate key',
]) {
expect(serialized, secret).not.toContain(secret);
}
});
it('every emitted key is on the allowlist AUD0 accepts', () => {
const events = biUsageEventsForExecution(hostile);
for (const e of events) {
for (const key of Object.keys(e.payload)) {
expect(EMITTABLE_PAYLOAD_KEYS, `${e.event_type}.${key}`).toContain(key);
}
}
});
it('a query_hash that is not a sha256 digest is dropped, not reshaped', () => {
const events = biUsageEventsForExecution({ ...hostile, compiled_query_hash: 'SELECT 1' });
for (const e of events) expect(e.payload.query_hash).toBeUndefined();
});
it('a running query emits only "started" — it is neither a success nor a failure', () => {
const events = biUsageEventsForExecution({
...hostile,
state: 'running',
metric_name: undefined,
dashboard_id: undefined,
});
expect(events.map((e) => e.event_type)).toEqual(['aud0.analytics_query_started']);
});
it('a cancelled query is reported as failed with a CODE', () => {
const events = biUsageEventsForExecution({
...hostile,
state: 'cancelled',
error_code: undefined,
metric_name: undefined,
dashboard_id: undefined,
});
const failed = events.find((e) => e.event_type === 'aud0.analytics_query_failed');
expect(failed?.payload.error_code).toBe('CANCELLED');
expect(failed?.payload.error_message).toBeUndefined();
});
});
+330
View File
@@ -0,0 +1,330 @@
/**
* tests/analytics/dashboard-model.test.ts
* ========================================
* BI-P060 — ANALYTICS DASHBOARD MODEL.
*
* The DoD is "a native SIAX dashboard can be reconstructed without Superset",
* so the central test takes a document that CAME from Superset (it still
* carries the slice ids in `vendor_ref`), plans it, and then greps the whole
* plan for any trace of the vendor. A plan that still needs Superset to be
* understood fails here.
*
* The counterfactual matters as much: `vendor-only-widget-is-refused` builds
* the document that CANNOT be reconstructed — a widget whose only content is a
* Superset id — and requires the model to refuse it. Without that test the
* vendor-free assertion would pass trivially for documents nobody could
* render.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
dashboardDocumentHash,
parseDashboardDocument,
planDashboard,
VISUALIZATION_TYPES,
type DashboardDocument,
} from '@/src/analytics/dashboards/dashboard-document';
/** A dashboard exported from Superset and rewritten into the canonical model. */
function supersetImportedDocument(): unknown {
return {
id: 'dash_sales_overview',
title: 'Sales overview',
description: 'Migrated from Superset dashboard 41.',
version: 1,
layout: { grid_columns: 12, row_height_px: 40 },
parameters: [
{
name: 'region',
type: 'enum',
required: false,
default_value: 'SE',
allowed_values: ['SE', 'NO', 'DK'],
},
{ name: 'since', type: 'date', required: true },
],
filters: [
{
filter_id: 'f_region',
label: 'Region',
dimension: 'region',
operator: 'eq',
default_values: ['{{region}}'],
},
{
filter_id: 'f_channel',
label: 'Channel',
dimension: 'channel',
operator: 'in',
default_values: ['web'],
},
{
filter_id: 'f_tenant_scope',
label: 'Business unit',
dimension: 'business_unit',
operator: 'eq',
default_values: ['bu_north'],
locked: true,
},
],
widgets: [
{
widget_id: 'w_revenue_total',
title: 'Revenue',
source: { kind: 'metric', dataset: 'ds_sales', metric: 'revenue' },
visualization: { type: 'big_number', encoding: { value: 'revenue' } },
layout: { x: 0, y: 0, w: 3, h: 2 },
vendor_ref: { system: 'superset', id: 'slice-8812' },
},
{
widget_id: 'w_revenue_by_day',
title: 'Revenue by day',
source: {
kind: 'metric',
dataset: 'ds_sales',
metric: 'revenue',
dimensions: ['order_date'],
grain: 'day',
},
visualization: {
type: 'line',
encoding: { x: 'order_date', y: ['revenue'] },
options: { stacked: false },
},
layout: { x: 3, y: 0, w: 9, h: 4 },
filter_bindings: ['f_region', 'f_tenant_scope'],
vendor_ref: { system: 'superset', id: 'slice-8813' },
},
{
widget_id: 'w_top_products',
title: 'Top products',
source: {
kind: 'query',
request: {
dataset: 'ds_sales',
metrics: ['revenue', 'orders'],
dimensions: ['product'],
filters: [{ dimension: 'status', operator: 'eq', values: ['completed'] }],
orderBy: [{ ref: 'revenue', direction: 'desc' }],
limit: 20,
},
},
visualization: { type: 'table', encoding: { x: 'product', y: ['revenue', 'orders'] } },
layout: { x: 0, y: 4, w: 12, h: 6 },
},
],
refresh: { mode: 'interval', interval_seconds: 300, max_staleness_seconds: 900 },
permissions: {
visibility: 'roles',
roles: ['analyst', 'sales_lead'],
required_entitlement: 'bi_dashboards',
},
vendor_ref: { system: 'superset', id: 'dashboard-41' },
};
}
describe('BI-P060 dashboard model — reconstruction without Superset', () => {
it('plans every widget into a runnable analytics request', () => {
const doc = parseDashboardDocument(supersetImportedDocument());
const plan = planDashboard(doc, { parameters: { since: '2026-01-01', region: 'NO' } });
expect(plan.widgets).toHaveLength(3);
for (const w of plan.widgets) {
expect(w.request.dataset).toBe('ds_sales');
expect(w.request.metrics.length).toBeGreaterThan(0);
expect(VISUALIZATION_TYPES).toContain(w.visualization.type);
}
// The parameter reference was BOUND, not left as a template string.
const byDay = plan.widgets.find((w) => w.widget_id === 'w_revenue_by_day');
expect(byDay?.request.filters.find((f) => f.dimension === 'region')?.values).toEqual(['NO']);
expect(plan.bound_parameters).toEqual({ region: 'NO', since: '2026-01-01' });
});
it('the plan contains no vendor identifier anywhere', () => {
const doc = parseDashboardDocument(supersetImportedDocument());
const plan = planDashboard(doc, { parameters: { since: '2026-01-01' } });
const serialized = JSON.stringify(plan).toLowerCase();
// The detector must be capable of finding one: the document DOES carry
// these ids, so a grep that finds nothing in the plan means the plan is
// clean, not that the grep is broken.
expect(JSON.stringify(doc).toLowerCase()).toContain('slice-8812');
for (const trace of ['superset', 'slice-8812', 'slice-8813', 'dashboard-41', 'viz_type', 'form_data']) {
expect(serialized).not.toContain(trace);
}
});
it('vendor-only widget is refused — it is the document that cannot be reconstructed', () => {
const raw = supersetImportedDocument() as { widgets: unknown[] };
raw.widgets = [
{
widget_id: 'w_mystery',
title: 'Whatever Superset had',
source: { kind: 'vendor', system: 'superset', id: 'slice-9001' },
visualization: { type: 'line', encoding: {} },
layout: { x: 0, y: 0, w: 4, h: 3 },
},
];
expect(() => parseDashboardDocument(raw)).toThrow(SiaxError);
expect(() => parseDashboardDocument(raw)).toThrow(/reconstruct/i);
});
it('vendor-native fields are refused at the top level and inside a widget', () => {
const top = { ...(supersetImportedDocument() as object), position_json: '{}' };
expect(() => parseDashboardDocument(top)).toThrow(/vendor-native/);
const raw = supersetImportedDocument() as { widgets: Record<string, unknown>[] };
raw.widgets[0].viz_type = 'echarts_timeseries';
expect(() => parseDashboardDocument(raw)).toThrow(/vendor-native/);
});
it('a Superset viz_type value is not a SIAX visualization type', () => {
const raw = supersetImportedDocument() as { widgets: Record<string, unknown>[] };
raw.widgets[0].visualization = { type: 'echarts_timeseries', encoding: {} };
expect(() => parseDashboardDocument(raw)).toThrow(/not a SIAX visualization type/);
});
});
describe('BI-P060 dashboard model — no SQL surface', () => {
it('a widget cannot carry SQL, however it is spelled', () => {
for (const key of ['sql', 'query_text', 'statement', 'where', 'expression']) {
const raw = supersetImportedDocument() as { widgets: Record<string, unknown>[] };
raw.widgets[0][key] = 'SELECT 1';
expect(() => parseDashboardDocument(raw), key).toThrow(SiaxError);
}
});
it('a query widget goes through the BI-P016 contract, so tenant selection is impossible', () => {
const raw = supersetImportedDocument() as { widgets: Record<string, unknown>[] };
raw.widgets[2].source = {
kind: 'query',
request: {
dataset: 'ds_sales',
metrics: ['revenue'],
dimensions: [],
filters: [],
tenant_id: 't_victim',
},
};
expect(() => parseDashboardDocument(raw)).toThrow(/does not accept SQL, catalogs, or tenant selection/);
});
it('the document itself cannot name a tenant', () => {
const raw = { ...(supersetImportedDocument() as object), tenant_id: 't_victim' };
expect(() => parseDashboardDocument(raw)).toThrow(/dashboards do not carry SQL|unknown field/);
});
});
describe('BI-P060 dashboard model — validation that would otherwise bite at render time', () => {
it('a widget binding an undeclared filter is refused', () => {
const raw = supersetImportedDocument() as { widgets: Record<string, unknown>[] };
raw.widgets[1].filter_bindings = ['f_nonexistent'];
expect(() => parseDashboardDocument(raw)).toThrow(/undeclared filter/);
});
it('a filter defaulting to an undeclared parameter is refused', () => {
const raw = supersetImportedDocument() as { filters: Record<string, unknown>[] };
raw.filters[0].default_values = ['{{not_declared}}'];
expect(() => parseDashboardDocument(raw)).toThrow(/undeclared parameter/);
});
it('a widget overflowing the grid is refused', () => {
const raw = supersetImportedDocument() as { widgets: Record<string, unknown>[] };
raw.widgets[1].layout = { x: 9, y: 0, w: 6, h: 3 };
expect(() => parseDashboardDocument(raw)).toThrow(/overflows the 12-column grid/);
});
it('an interval refresh with a cron, and a manual refresh with a schedule, are both refused', () => {
const a = supersetImportedDocument() as Record<string, unknown>;
a.refresh = { mode: 'interval', interval_seconds: 300, cron: '0 * * * *', max_staleness_seconds: 900 };
expect(() => parseDashboardDocument(a)).toThrow(/meaningless/);
const b = supersetImportedDocument() as Record<string, unknown>;
b.refresh = { mode: 'manual', interval_seconds: 300, max_staleness_seconds: 900 };
expect(() => parseDashboardDocument(b)).toThrow(/manual/);
});
it('visibility "roles" with no roles is refused rather than guessed', () => {
const raw = supersetImportedDocument() as Record<string, unknown>;
raw.permissions = { visibility: 'roles', roles: [] };
expect(() => parseDashboardDocument(raw)).toThrow(/deny all/);
});
it('a required parameter that was not supplied fails the plan, not the render', () => {
const doc = parseDashboardDocument(supersetImportedDocument());
expect(() => planDashboard(doc, { parameters: {} })).toThrow(/required parameter "since"/);
});
it('a locked filter cannot be switched off by a viewer', () => {
const doc = parseDashboardDocument(supersetImportedDocument());
expect(() =>
planDashboard(doc, { parameters: { since: '2026-01-01' }, disabled_filter_ids: ['f_tenant_scope'] }),
).toThrow(/locked/);
// An unlocked one can be, and disappears from the compiled request.
const plan = planDashboard(doc, {
parameters: { since: '2026-01-01' },
disabled_filter_ids: ['f_channel'],
});
const table = plan.widgets.find((w) => w.widget_id === 'w_top_products');
expect(table?.request.filters.map((f) => f.dimension)).not.toContain('channel');
});
it('an enum parameter without allowed_values is refused', () => {
const raw = supersetImportedDocument() as { parameters: Record<string, unknown>[] };
raw.parameters[0] = { name: 'region', type: 'enum', required: false, default_value: 'SE' };
expect(() => parseDashboardDocument(raw)).toThrow(/unbounded enum/);
});
});
/** Rebuild an object graph with every object's keys in reverse order. */
function shuffleKeys(value: unknown): unknown {
if (Array.isArray(value)) return value.map(shuffleKeys);
if (value !== null && typeof value === 'object') {
const out: Record<string, unknown> = {};
for (const k of Object.keys(value as object).reverse()) {
out[k] = shuffleKeys((value as Record<string, unknown>)[k]);
}
return out;
}
return value;
}
describe('BI-P060 dashboard model — canonical hash', () => {
function parsed(): DashboardDocument {
return parseDashboardDocument(supersetImportedDocument());
}
it('is stable across key order and vendor re-export', () => {
const a = parsed();
const b = parsed();
b.vendor_ref = { system: 'superset', id: 'dashboard-999-after-migration' };
b.widgets[0].vendor_ref = { system: 'metabase', id: 'card-3' };
expect(dashboardDocumentHash(b)).toBe(dashboardDocumentHash(a));
// Key order in the source JSON must not change identity either.
expect(dashboardDocumentHash(parseDashboardDocument(shuffleKeys(supersetImportedDocument())))).toBe(
dashboardDocumentHash(a),
);
});
it('changes when meaning changes', () => {
const base = dashboardDocumentHash(parsed());
const retitled = parsed();
retitled.widgets[0].title = 'Net revenue';
expect(dashboardDocumentHash(retitled)).not.toBe(base);
const remetric = parsed();
(remetric.widgets[0].source as { metric: string }).metric = 'revenue_net';
expect(dashboardDocumentHash(remetric)).not.toBe(base);
const moved = parsed();
moved.widgets[1].layout = { x: 3, y: 1, w: 9, h: 4 };
expect(dashboardDocumentHash(moved)).not.toBe(base);
const refiltered = parsed();
refiltered.filters[1].default_values = ['store'];
expect(dashboardDocumentHash(refiltered)).not.toBe(base);
});
});
@@ -0,0 +1,346 @@
/**
* tests/analytics/dashboard-release-postgres.realinfra.test.ts
* =============================================================
* sql/010 (BI-P061) against a REAL Postgres.
*
* The interesting claim in sql/010 is not "there is a state machine" — it is
* "TWO PEOPLE CANNOT PUBLISH AT ONCE". That claim lives in a partial unique
* index, and an index nobody raced is an index nobody has tested. So the
* concurrency test runs BOTH directions, in two separate schemas so neither
* can contaminate the other:
*
* 1. WITHOUT the index (a schema where it is dropped): two sessions publish
* a release of the same dashboard concurrently, each having first read
* "nothing is live" — the exact interleaving an application-level check
* cannot see. The database ends up with TWO published releases. This is
* the counterfactual: it proves the read-then-write check in
* DashboardReleaseService.publish() is NOT the guarantee, and that this
* test can detect the failure it claims to prevent.
* 2. WITH the index: the same race, and the loser fails with
* unique_violation (23505). Exactly one published release remains.
*
* The transition trigger is attacked the same way: every illegal transition is
* attempted against the database, not against the TypeScript.
*
* Gated on ANALYTICS_TEST_DATABASE_URL, matching the convention in
* analytics-governance-postgres.realinfra.test.ts. With it set and Postgres
* down this FAILS rather than skipping.
*
* docker run -d --name pg -p 25441:5432 -e POSTGRES_PASSWORD=test \
* -e POSTGRES_DB=opt postgres:16-alpine
* ANALYTICS_TEST_DATABASE_URL=postgres://postgres:test@127.0.0.1:25441/opt \
* pnpm vitest run tests/analytics/dashboard-release-postgres.realinfra.test.ts
*/
import fs from 'node:fs';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import postgres from 'postgres';
const TEST_DATABASE_URL = process.env.ANALYTICS_TEST_DATABASE_URL;
const run = TEST_DATABASE_URL ? describe : describe.skip;
const STAMP = Date.now().toString(36);
const SCHEMA = `bi_p061_${STAMP}`;
/** The counterfactual lives in its own schema: no cleanup, no contamination. */
const SCHEMA_NOGUARD = `bi_p061_noguard_${STAMP}`;
const HASH_A = 'a'.repeat(64);
const HASH_B = 'b'.repeat(64);
const MIGRATIONS = ['sql/008_analytics_domain_model.sql', 'sql/010_analytics_dashboard_releases.sql'];
let sql: ReturnType<typeof postgres>;
function connect(schema: string, max = 1): ReturnType<typeof postgres> {
return postgres(TEST_DATABASE_URL!, {
max,
onnotice: () => undefined,
connection: { search_path: schema },
});
}
async function refusalOf(fn: () => Promise<unknown>): Promise<string | undefined> {
try {
await fn();
return undefined;
} catch (e) {
return String((e as Error).message);
}
}
async function migrate(conn: ReturnType<typeof postgres>): Promise<void> {
for (const file of MIGRATIONS) {
await conn.unsafe(fs.readFileSync(path.join(process.cwd(), file), 'utf8'));
}
}
async function seedDashboard(conn: ReturnType<typeof postgres>, id: string): Promise<void> {
await conn.unsafe(`
INSERT INTO opt_analytics_dashboard_definition
(dashboard_id, tenant_id, project_id, name, current_version, owner_id)
VALUES ('${id}', 't_alpha', 'p_main', '${id}', 1, 'u_1')
ON CONFLICT DO NOTHING`);
}
async function seedVersion(
conn: ReturnType<typeof postgres>,
versionId: string,
dashboardId: string,
version: number,
hash = HASH_A,
): Promise<void> {
await conn.unsafe(`
INSERT INTO opt_analytics_dashboard_version
(dashboard_version_id, dashboard_id, tenant_id, project_id, version, layout_json, layout_hash)
VALUES ('${versionId}', '${dashboardId}', 't_alpha', 'p_main', ${version}, '{}', '${hash}')`);
}
async function seedDraftRelease(
conn: ReturnType<typeof postgres>,
releaseId: string,
versionId: string,
dashboardId: string,
version: number,
hash = HASH_A,
): Promise<void> {
await conn.unsafe(`
INSERT INTO opt_analytics_dashboard_release
(release_id, dashboard_id, dashboard_version_id, tenant_id, project_id, version, state, document_hash)
VALUES ('${releaseId}', '${dashboardId}', '${versionId}', 't_alpha', 'p_main', ${version}, 'draft', '${hash}')`);
}
async function publishedCount(conn: ReturnType<typeof postgres>, dashboardId: string): Promise<number> {
const rows = (await conn.unsafe(
`SELECT count(*)::int AS n FROM opt_analytics_dashboard_release
WHERE dashboard_id = '${dashboardId}' AND state = 'published'`,
)) as unknown as Array<{ n: number }>;
return rows[0].n;
}
/**
* Two sessions publish a release of the SAME dashboard at the same time, each
* having first read "nothing is live". This is the create-and-publish path:
* a new version is minted and released in one transaction, which is what a
* "save and publish" button does.
*/
async function racePublish(schema: string, dashboardId: string): Promise<{ ok: number; codes: string[] }> {
const a = connect(schema);
const b = connect(schema);
const publish = (conn: ReturnType<typeof postgres>, n: number) =>
conn.begin(async (tx) => {
await tx.unsafe(
`SELECT release_id FROM opt_analytics_dashboard_release
WHERE dashboard_id = '${dashboardId}' AND state = 'published'`,
);
// A tiny pause so both transactions have certainly done their read
// before either writes. Without it the race may not interleave and the
// counterfactual could pass for the wrong reason.
await new Promise((r) => setTimeout(r, 60));
await tx.unsafe(`
INSERT INTO opt_analytics_dashboard_release
(release_id, dashboard_id, dashboard_version_id, tenant_id, project_id, version, state,
document_hash, published_at)
VALUES ('rel_race_${n}', '${dashboardId}', 'dv_race_${n}', 't_alpha', 'p_main', ${400 + n},
'published', '${n === 1 ? HASH_A : HASH_B}', now())`);
});
const results = await Promise.allSettled([publish(a, 1), publish(b, 2)]);
await a.end({ timeout: 5 });
await b.end({ timeout: 5 });
return {
ok: results.filter((r) => r.status === 'fulfilled').length,
codes: results.flatMap((r) =>
r.status === 'rejected' ? [String((r.reason as { code?: string })?.code ?? r.reason)] : [],
),
};
}
beforeAll(async () => {
if (!TEST_DATABASE_URL) return;
const admin = postgres(TEST_DATABASE_URL, { max: 1, onnotice: () => undefined });
await admin.unsafe(`CREATE SCHEMA IF NOT EXISTS ${SCHEMA}`);
await admin.unsafe(`CREATE SCHEMA IF NOT EXISTS ${SCHEMA_NOGUARD}`);
await admin.end({ timeout: 5 });
sql = connect(SCHEMA, 3);
await migrate(sql);
for (const d of ['dash_txn', 'dash_race', 'dash_draft']) await seedDashboard(sql, d);
}, 120_000);
afterAll(async () => {
if (!TEST_DATABASE_URL || !sql) return;
await sql.unsafe(`DROP SCHEMA IF EXISTS ${SCHEMA} CASCADE`);
await sql.unsafe(`DROP SCHEMA IF EXISTS ${SCHEMA_NOGUARD} CASCADE`);
await sql.end({ timeout: 5 });
});
run('sql/010 applies and replays', () => {
it('is idempotent — a replay onto an already-migrated schema succeeds', async () => {
const text = fs.readFileSync(
path.join(process.cwd(), 'sql/010_analytics_dashboard_releases.sql'),
'utf8',
);
await expect(sql.unsafe(text)).resolves.toBeDefined();
});
it('has no column that could hold a document body — the document lives in the version row', async () => {
const rows = (await sql.unsafe(
`SELECT column_name FROM information_schema.columns
WHERE table_schema = '${SCHEMA}' AND table_name = 'opt_analytics_dashboard_release'`,
)) as unknown as Array<{ column_name: string }>;
const names = new Set(rows.map((r) => r.column_name));
for (const forbidden of ['layout_json', 'document', 'definition', 'payload', 'sql']) {
expect(names.has(forbidden), forbidden).toBe(false);
}
expect(names.has('document_hash')).toBe(true);
});
});
run('BI-P061 transitions are enforced by the database', () => {
beforeAll(async () => {
await seedVersion(sql, 'dv_t1', 'dash_txn', 101);
await seedVersion(sql, 'dv_t3', 'dash_txn', 103, HASH_B);
await seedDraftRelease(sql, 'rel_t1', 'dv_t1', 'dash_txn', 101);
});
it('draft -> published is allowed', async () => {
await sql.unsafe(
`UPDATE opt_analytics_dashboard_release SET state='published', published_at=now() WHERE release_id='rel_t1'`,
);
const rows = (await sql.unsafe(
`SELECT state FROM opt_analytics_dashboard_release WHERE release_id='rel_t1'`,
)) as unknown as Array<{ state: string }>;
expect(rows[0].state).toBe('published');
});
it('published -> draft (un-publishing) is REFUSED', async () => {
const msg = await refusalOf(() =>
sql.unsafe(
`UPDATE opt_analytics_dashboard_release SET state='draft', published_at=NULL WHERE release_id='rel_t1'`,
),
);
expect(msg).toMatch(/illegal dashboard release transition published -> draft/);
});
it('repointing a release at a different version is REFUSED', async () => {
const msg = await refusalOf(() =>
sql.unsafe(
`UPDATE opt_analytics_dashboard_release SET dashboard_version_id='dv_t3' WHERE release_id='rel_t1'`,
),
);
expect(msg).toMatch(/immutable apart from its state/);
});
it('rewriting document_hash on a release is REFUSED', async () => {
const msg = await refusalOf(() =>
sql.unsafe(
`UPDATE opt_analytics_dashboard_release SET document_hash='${HASH_B}' WHERE release_id='rel_t1'`,
),
);
expect(msg).toMatch(/immutable apart from its state/);
});
it('rewriting published_at is REFUSED — a published timestamp is history', async () => {
const msg = await refusalOf(() =>
sql.unsafe(
`UPDATE opt_analytics_dashboard_release SET published_at = now() - interval '10 days'
WHERE release_id='rel_t1'`,
),
);
expect(msg).toMatch(/published_at is history/);
});
it('published -> superseded is allowed, and superseded -> published is REFUSED', async () => {
await sql.unsafe(
`UPDATE opt_analytics_dashboard_release SET state='superseded', superseded_at=now() WHERE release_id='rel_t1'`,
);
const msg = await refusalOf(() =>
sql.unsafe(`UPDATE opt_analytics_dashboard_release SET state='published' WHERE release_id='rel_t1'`),
);
expect(msg).toMatch(/illegal dashboard release transition superseded -> published/);
});
it('deleting a release is REFUSED — the ledger has no eraser', async () => {
const msg = await refusalOf(() =>
sql.unsafe(`DELETE FROM opt_analytics_dashboard_release WHERE release_id='rel_t1'`),
);
expect(msg).toMatch(/ledger; delete is refused/);
});
it('a published release with no published_at is REFUSED by the CHECK', async () => {
const msg = await refusalOf(() =>
sql.unsafe(`
INSERT INTO opt_analytics_dashboard_release
(release_id, dashboard_id, dashboard_version_id, tenant_id, project_id, version, state, document_hash)
VALUES ('rel_bad', 'dash_txn', 'dv_t3', 't_alpha', 'p_main', 900, 'published', '${HASH_A}')`),
);
expect(msg).toMatch(/opt_analytics_dashboard_release_timestamps/);
});
it('a document_hash that is not a sha256 digest is REFUSED', async () => {
const msg = await refusalOf(() =>
sql.unsafe(`
INSERT INTO opt_analytics_dashboard_release
(release_id, dashboard_id, dashboard_version_id, tenant_id, project_id, version, state, document_hash)
VALUES ('rel_bad2', 'dash_txn', 'dv_t3', 't_alpha', 'p_main', 901, 'draft', 'not-a-hash')`),
);
expect(msg).toMatch(/document_hash/);
});
it('the sql/008 immutability trigger still forbids editing the frozen document', async () => {
// Assert the row exists FIRST: an UPDATE that matches nothing raises
// nothing, which would read as "refused" to a careless test.
const before = (await sql.unsafe(
`SELECT count(*)::int AS n FROM opt_analytics_dashboard_version WHERE dashboard_version_id='dv_t3'`,
)) as unknown as Array<{ n: number }>;
expect(before[0].n).toBe(1);
const msg = await refusalOf(() =>
sql.unsafe(
`UPDATE opt_analytics_dashboard_version SET layout_json='{"tampered":true}'
WHERE dashboard_version_id='dv_t3'`,
),
);
expect(msg).toMatch(/rows are immutable/);
});
it('a second open draft for one dashboard is REFUSED', async () => {
await seedVersion(sql, 'dv_d1', 'dash_draft', 301);
await seedVersion(sql, 'dv_d2', 'dash_draft', 302);
await seedDraftRelease(sql, 'rel_d1', 'dv_d1', 'dash_draft', 301);
const msg = await refusalOf(() => seedDraftRelease(sql, 'rel_d2', 'dv_d2', 'dash_draft', 302));
expect(msg).toMatch(/one_draft/);
});
});
run('BI-P061 concurrency: the partial unique index is the guarantee', () => {
let noguard: ReturnType<typeof postgres>;
beforeAll(async () => {
noguard = connect(SCHEMA_NOGUARD, 3);
await migrate(noguard);
await noguard.unsafe(`DROP INDEX opt_analytics_dashboard_release_one_published`);
await seedDashboard(noguard, 'dash_race');
await seedVersion(noguard, 'dv_race_1', 'dash_race', 401);
await seedVersion(noguard, 'dv_race_2', 'dash_race', 402, HASH_B);
await seedVersion(sql, 'dv_race_1', 'dash_race', 401);
await seedVersion(sql, 'dv_race_2', 'dash_race', 402, HASH_B);
}, 60_000);
afterAll(async () => {
if (noguard) await noguard.end({ timeout: 5 });
});
it('WITHOUT the index, two concurrent publishes BOTH succeed — two live dashboards', async () => {
const race = await racePublish(SCHEMA_NOGUARD, 'dash_race');
expect(race.ok).toBe(2);
expect(await publishedCount(noguard, 'dash_race')).toBe(2);
}, 30_000);
it('WITH the index, the same race leaves exactly one published release', async () => {
expect(await publishedCount(sql, 'dash_race')).toBe(0);
const race = await racePublish(SCHEMA, 'dash_race');
expect(race.ok).toBe(1);
expect(race.codes.join(' ')).toContain('23505');
expect(await publishedCount(sql, 'dash_race')).toBe(1);
}, 30_000);
});
+212
View File
@@ -0,0 +1,212 @@
/**
* tests/analytics/dashboard-release.test.ts
* ==========================================
* BI-P061 — DASHBOARD VERSIONING. DoD: "rollback to previous dashboard
* definition".
*
* A rollback test that only asserts "the service returned version 4" proves
* nothing: the interesting failure is a rollback that publishes a DIFFERENT
* document while reporting success. So every rollback assertion here compares
* BI-P060 canonical hashes and re-plans the restored dashboard, and one test
* corrupts the stored document underneath a release to show that serving it
* is refused rather than silently rendered.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
dashboardDocumentHash,
parseDashboardDocument,
planDashboard,
} from '@/src/analytics/dashboards/dashboard-document';
import {
DashboardReleaseService,
InMemoryDashboardReleaseStore,
isLegalTransition,
DASHBOARD_RELEASE_STATES,
type DashboardReleaseState,
} from '@/src/analytics/dashboards/dashboard-release';
const SCOPE = { tenant_id: 't_alpha', project_id: 'p_main' };
function doc(title: string, metric = 'revenue') {
return {
id: 'dash_sales',
title,
version: 1,
layout: { grid_columns: 12, row_height_px: 40 },
parameters: [],
filters: [],
widgets: [
{
widget_id: 'w_1',
title,
source: { kind: 'metric', dataset: 'ds_sales', metric },
visualization: { type: 'big_number', encoding: { value: metric } },
layout: { x: 0, y: 0, w: 4, h: 2 },
},
],
refresh: { mode: 'manual', max_staleness_seconds: 3600 },
permissions: { visibility: 'tenant' },
};
}
function service() {
let n = 0;
let t = Date.parse('2026-09-07T10:00:00.000Z');
return new DashboardReleaseService(
new InMemoryDashboardReleaseStore(),
() => new Date((t += 1000)),
() => `id_${++n}`,
);
}
describe('BI-P061 release lifecycle', () => {
it('the transition table is exactly DRAFT -> PUBLISHED -> SUPERSEDED', () => {
const legal: Array<[DashboardReleaseState, DashboardReleaseState]> = [
['draft', 'published'],
['published', 'superseded'],
];
for (const from of DASHBOARD_RELEASE_STATES) {
for (const to of DASHBOARD_RELEASE_STATES) {
const expected = legal.some(([f, t]) => f === from && t === to);
expect(isLegalTransition(from, to), `${from} -> ${to}`).toBe(expected);
}
}
// Named explicitly because each is a real request someone will make.
expect(isLegalTransition('published', 'draft')).toBe(false);
expect(isLegalTransition('superseded', 'published')).toBe(false);
expect(isLegalTransition('draft', 'superseded')).toBe(false);
});
it('publishing supersedes the previous release, and only one is ever live', async () => {
const svc = service();
const v1 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v1') });
await svc.publish({ scope: SCOPE, releaseId: v1.release.release_id });
const v2 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v2') });
const result = await svc.publish({ scope: SCOPE, releaseId: v2.release.release_id });
expect(result.published.version).toBe(2);
expect(result.superseded?.version).toBe(1);
expect(result.superseded?.superseded_by_release_id).toBe(v2.release.release_id);
const history = await svc.history(SCOPE, 'dash_sales');
expect(history.map((r) => `${r.version}:${r.state}`)).toEqual(['1:superseded', '2:published']);
expect((await svc.live(SCOPE, 'dash_sales'))?.version).toBe(2);
});
it('a second open draft is refused rather than racing the first', async () => {
const svc = service();
await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v1') });
await expect(
svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v1-again') }),
).rejects.toThrow(/already has an open draft/);
});
it('a superseded release cannot be re-published', async () => {
const svc = service();
const v1 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v1') });
await svc.publish({ scope: SCOPE, releaseId: v1.release.release_id });
const v2 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v2') });
await svc.publish({ scope: SCOPE, releaseId: v2.release.release_id });
await expect(svc.publish({ scope: SCOPE, releaseId: v1.release.release_id })).rejects.toThrow(
/is superseded, not draft/,
);
});
it('another tenant cannot see, publish or roll back this tenant’s releases', async () => {
const svc = service();
const v1 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v1') });
const other = { tenant_id: 't_beta', project_id: 'p_main' };
await expect(svc.publish({ scope: other, releaseId: v1.release.release_id })).rejects.toThrow(
/does not exist in this tenant/,
);
expect(await svc.live(other, 'dash_sales')).toBeUndefined();
await expect(svc.rollback({ scope: other, dashboardId: 'dash_sales', toVersion: 1 })).rejects.toThrow(
/no version 1 in this tenant/,
);
});
});
describe('BI-P061 rollback — the DoD', () => {
it('restores the earlier definition byte-for-byte, as a NEW version', async () => {
const svc = service();
const original = doc('Sales v1', 'revenue');
const originalHash = dashboardDocumentHash(parseDashboardDocument(original));
const v1 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: original });
await svc.publish({ scope: SCOPE, releaseId: v1.release.release_id });
const v2 = await svc.draft({
scope: SCOPE,
dashboardId: 'dash_sales',
document: doc('Sales v2 (broken)', 'revenue_net'),
});
await svc.publish({ scope: SCOPE, releaseId: v2.release.release_id });
expect((await svc.live(SCOPE, 'dash_sales'))?.document_hash).not.toBe(originalHash);
const rolled = await svc.rollback({ scope: SCOPE, dashboardId: 'dash_sales', toVersion: 1 });
// Faithful: same canonical document.
expect(rolled.document_hash).toBe(originalHash);
// New version, not a resurrected row — the history stays linear.
expect(rolled.release.version).toBe(3);
expect(rolled.release.rollback_of_version).toBe(1);
const history = await svc.history(SCOPE, 'dash_sales');
expect(history.map((r) => `${r.version}:${r.state}`)).toEqual([
'1:superseded',
'2:superseded',
'3:published',
]);
// And the restored dashboard actually renders as the original did.
const live = await svc.live(SCOPE, 'dash_sales');
const restored = await svc.documentOf(SCOPE, live!);
expect(planDashboard(restored)).toEqual(planDashboard(parseDashboardDocument(original)));
});
it('rolling back to the live version is refused as a no-op', async () => {
const svc = service();
const v1 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v1') });
await svc.publish({ scope: SCOPE, releaseId: v1.release.release_id });
await expect(svc.rollback({ scope: SCOPE, dashboardId: 'dash_sales', toVersion: 1 })).rejects.toThrow(
/already live/,
);
});
it('a stored document that no longer matches its released hash is refused, not rendered', async () => {
const store = new InMemoryDashboardReleaseStore();
const svc = new DashboardReleaseService(
store,
() => new Date(),
() => crypto.randomUUID(),
);
const v1 = await svc.draft({ scope: SCOPE, dashboardId: 'dash_sales', document: doc('v1') });
const { published } = await svc.publish({ scope: SCOPE, releaseId: v1.release.release_id });
// Tamper with storage the way a bad migration or a manual UPDATE would.
const stored = await store.getVersion(SCOPE, published.dashboard_version_id);
const tampered = JSON.parse(stored!.layout_json);
tampered.widgets[0].source.metric = 'revenue_including_vat';
await store.insertVersionAndRelease(
{ ...stored!, dashboard_version_id: 'tampered', version: 99, layout_json: JSON.stringify(tampered) },
{
...published,
release_id: 'r_tampered',
dashboard_version_id: 'tampered',
version: 99,
state: 'draft',
published_at: undefined,
},
);
// documentOf must compare hashes, not trust the row.
await expect(svc.documentOf(SCOPE, { ...published, dashboard_version_id: 'tampered' })).rejects.toThrow(
/refusing to serve an unapproved definition/,
);
await expect(svc.documentOf(SCOPE, { ...published, dashboard_version_id: 'tampered' })).rejects.toThrow(
SiaxError,
);
});
});
+296
View File
@@ -0,0 +1,296 @@
/**
* BI-P004 — ANALYTICS DATA CONTRACT.
*
* DoD: "Breaking dataset schema changes fail compatibility gate unless
* explicitly versioned." Each breaking change class below is tested TWICE:
* once under a minor bump (must be REFUSED) and once under a major bump (must
* be ACCEPTED). A gate that only ever says yes, or only ever says no, would
* pass a one-sided test; this one cannot.
*/
import { describe, it, expect } from 'vitest';
import {
assertContractCompatible,
checkContractCompatibility,
contractHash,
diffContracts,
parseSemVer,
validateContract,
type DatasetContract,
} from '@/src/analytics/domain/contract';
function base(): DatasetContract {
return {
dataset_id: 'ds_vehicle_listings',
version: '1.2.0',
tier: 'CURATED',
fields: [
{ name: 'listing_id', type: 'string', nullable: false, role: 'identifier', primary_identifier: true },
{ name: 'make', type: 'string', nullable: false, role: 'dimension' },
{ name: 'asking_price', type: 'int64', nullable: true, role: 'measure' },
{ name: 'listed_at', type: 'timestamp', nullable: false, role: 'attribute' },
],
primary_identifiers: ['listing_id'],
dimensions: ['make'],
measures: ['asking_price'],
freshness_slo_seconds: 3600,
retention_days: 730,
pii_classification: 'none',
source_lineage: ['src_dealer_feed'],
quality_rules: [
{ rule_id: 'qr_listing_id_unique', kind: 'unique', field_name: 'listing_id', severity: 'block' },
],
allowed_purposes: ['market_analytics'],
};
}
/** Apply a mutation and set the version. */
function next(mutate: (c: DatasetContract) => void, version: string): DatasetContract {
const c: DatasetContract = JSON.parse(JSON.stringify(base()));
mutate(c);
c.version = version;
return c;
}
const BREAKING_CASES: { name: string; mutate: (c: DatasetContract) => void; code: string }[] = [
{
name: 'field removed',
mutate: (c) => {
c.fields = c.fields.filter((f) => f.name !== 'make');
c.dimensions = [];
},
code: 'field_removed',
},
{
name: 'field type changed',
mutate: (c) => {
c.fields[2].type = 'float64';
},
code: 'field_type_changed',
},
{
name: 'field became nullable',
mutate: (c) => {
c.fields[1].nullable = true;
},
code: 'field_became_nullable',
},
{
name: 'field role changed',
mutate: (c) => {
c.fields[1].role = 'measure';
},
code: 'field_role_changed',
},
{
name: 'required field added',
mutate: (c) => {
c.fields.push({ name: 'vat_rate', type: 'float64', nullable: false, role: 'attribute' });
},
code: 'required_field_added',
},
{
name: 'primary identifier changed',
mutate: (c) => {
c.primary_identifiers = ['make'];
},
code: 'primary_identifier_changed',
},
{
name: 'dimension removed',
mutate: (c) => {
c.dimensions = [];
},
code: 'dimension_removed',
},
{
name: 'measure removed',
mutate: (c) => {
c.measures = [];
},
code: 'measure_removed',
},
{
name: 'freshness SLO loosened',
mutate: (c) => {
c.freshness_slo_seconds = 86400;
},
code: 'freshness_slo_loosened',
},
{
name: 'retention shortened',
mutate: (c) => {
c.retention_days = 30;
},
code: 'retention_shortened',
},
{
name: 'allowed purpose removed',
mutate: (c) => {
c.allowed_purposes = [];
},
code: 'purpose_removed',
},
{
name: 'PII classification raised',
mutate: (c) => {
c.pii_classification = 'personal';
},
code: 'pii_classification_raised',
},
{
name: 'blocking quality rule removed',
mutate: (c) => {
c.quality_rules = [];
},
code: 'blocking_quality_rule_removed',
},
{
name: 'blocking quality rule downgraded',
mutate: (c) => {
c.quality_rules[0].severity = 'warn';
},
code: 'blocking_quality_rule_downgraded',
},
{
name: 'tier changed',
mutate: (c) => {
c.tier = 'SERVING';
},
code: 'tier_changed',
},
];
describe('BI-P004 compatibility gate', () => {
it.each(BREAKING_CASES)('REFUSES $name under a minor bump', ({ mutate, code }) => {
const verdict = checkContractCompatibility(base(), next(mutate, '1.3.0'));
expect(verdict.compatible).toBe(false);
expect(verdict.breaking.map((b) => b.code)).toContain(code);
expect(verdict.reason).toMatch(/MAJOR version bump/);
});
it.each(BREAKING_CASES)('ACCEPTS $name once explicitly versioned (major bump)', ({ mutate, code }) => {
const verdict = checkContractCompatibility(base(), next(mutate, '2.0.0'));
expect(verdict.compatible).toBe(true);
expect(verdict.explicitly_versioned).toBe(true);
expect(verdict.breaking.map((b) => b.code)).toContain(code);
});
it('a patch bump is equally refused — the gate is about the MAJOR, not about moving at all', () => {
const verdict = checkContractCompatibility(
base(),
next((c) => c.fields.pop(), '1.2.1'),
);
expect(verdict.compatible).toBe(false);
});
it('allows genuinely additive changes without a major bump', () => {
const additive = next((c) => {
c.fields.push({ name: 'mileage_km', type: 'int64', nullable: true, role: 'measure' });
c.measures.push('mileage_km');
c.quality_rules.push({
rule_id: 'qr_mileage_range',
kind: 'range',
field_name: 'mileage_km',
severity: 'warn',
});
c.allowed_purposes.push('valuation');
c.retention_days = 1095;
c.freshness_slo_seconds = 1800;
}, '1.3.0');
const verdict = checkContractCompatibility(base(), additive);
expect(verdict.compatible).toBe(true);
expect(verdict.breaking).toEqual([]);
expect(verdict.explicitly_versioned).toBe(false);
});
it('refuses a version that does not move forward', () => {
expect(
checkContractCompatibility(
base(),
next(() => {}, '1.2.0'),
).compatible,
).toBe(false);
expect(
checkContractCompatibility(
base(),
next(() => {}, '1.1.9'),
).compatible,
).toBe(false);
expect(
checkContractCompatibility(
base(),
next(() => {}, '0.9.0'),
).compatible,
).toBe(false);
});
it('treats date -> timestamp as a safe widening, and int64 -> float64 as NOT one', () => {
const widened = next((c) => {
c.fields.push({ name: 'sold_on', type: 'date', nullable: true, role: 'attribute' });
}, '1.3.0');
const later = JSON.parse(JSON.stringify(widened)) as DatasetContract;
later.fields[later.fields.length - 1].type = 'timestamp';
later.version = '1.4.0';
expect(checkContractCompatibility(widened, later).compatible).toBe(true);
const lossy = next((c) => {
c.fields[2].type = 'float64';
}, '1.3.0');
expect(checkContractCompatibility(base(), lossy).compatible).toBe(false);
});
it('assertContractCompatible throws a CONFLICT rather than returning a verdict nobody reads', () => {
expect(() =>
assertContractCompatible(
base(),
next((c) => c.fields.pop(), '1.3.0'),
),
).toThrowError(/MAJOR/);
expect(() =>
assertContractCompatible(
base(),
next(() => {}, '1.3.0'),
),
).not.toThrow();
});
it('refuses to compare contracts for different datasets', () => {
const other = next((c) => {
c.dataset_id = 'ds_other';
}, '1.3.0');
expect(() => diffContracts(base(), other)).toThrowError(/SAME dataset/);
});
it('validateContract catches internally inconsistent contracts', () => {
expect(() => validateContract(base())).not.toThrow();
expect(() => validateContract({ ...base(), version: '1.2' })).toThrowError(/major.minor.patch/);
expect(() => validateContract({ ...base(), fields: [] })).toThrowError(/no fields/);
expect(() => validateContract({ ...base(), dimensions: ['nope'] })).toThrowError(/unknown field/);
expect(() => validateContract({ ...base(), primary_identifiers: [] })).toThrowError(
/no primary identifier/,
);
expect(() => validateContract({ ...base(), allowed_purposes: [] })).toThrowError(/allowed_purposes/);
expect(() => validateContract({ ...base(), freshness_slo_seconds: 0 })).toThrowError(/freshness/);
const dup = base();
dup.fields.push({ ...dup.fields[0] });
expect(() => validateContract(dup)).toThrowError(/duplicate field/);
});
it('contractHash is order-insensitive over fields but sensitive to meaning', () => {
const a = base();
const reordered = JSON.parse(JSON.stringify(a)) as DatasetContract;
reordered.fields.reverse();
expect(contractHash(reordered)).toBe(contractHash(a));
const changed = JSON.parse(JSON.stringify(a)) as DatasetContract;
changed.fields[1].nullable = true;
expect(contractHash(changed)).not.toBe(contractHash(a));
});
it('parseSemVer rejects anything that is not major.minor.patch', () => {
expect(parseSemVer('2.10.3')).toEqual({ major: 2, minor: 10, patch: 3 });
for (const bad of ['v1.0.0', '1.0', '1.0.0-rc1', 'latest', '']) {
expect(() => parseSemVer(bad)).toThrowError(/major.minor.patch/);
}
});
});
+321
View File
@@ -0,0 +1,321 @@
/**
* tests/analytics/dbt-contract.test.ts
* =====================================
* BI-P022 — DBT CORE CANONICAL TRANSFORMATION (the CONTRACT).
*
* This repo does not run dbt; N0D (n0d#38) does, against this contract. So
* what is testable here is exactly what the contract must refuse, and the
* interesting refusals are the ones that look like successes:
*
* * `status: "success"` with ZERO nodes executed — a dbt selector that
* matches nothing exits 0. The dbt-shaped false green.
* * a result whose observed dbt version differs from the pin — the models
* mean something different and nothing says so.
* * a branch name as the revision — "main" today and "main" tomorrow are
* different projects, and BI-P022's DoD is about reproducibility.
* * a production run against an unreviewed runtime, which is BI-P022's
* "after current license/security verification" turned into a gate.
*
* The scaffold itself is asserted against the filesystem, because a directory
* convention that nothing checks is a directory convention that drifts.
*/
import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
assertDbtRuntimeCertified,
assertLayerDependenciesLegal,
assertValidDbtJobRequest,
assertValidDbtJobResult,
DBT_LAYER_TIERS,
DBT_LAYERS,
DBT_RUNTIME_PIN,
REQUIRED_DBT_ARTIFACTS,
REQUIRED_DBT_DIRECTORIES,
tierForModelPath,
type DbtJobRequest,
type DbtJobResult,
} from '@/src/analytics/transform/dbt-contract';
const DBT_ROOT = path.join(process.cwd(), 'analytics/dbt');
const SHA = 'a'.repeat(40);
const CERTIFIED_PIN = {
...DBT_RUNTIME_PIN,
licenseReviewed: true,
securityReviewed: true,
reviewedBy: 'u_1',
reviewedAt: '2026-09-07T00:00:00Z',
};
function request(over: Partial<DbtJobRequest> = {}): DbtJobRequest {
return {
tenant_id: 't_alpha',
project_id: 'p_main',
dbt_project: 'siax_analytics',
revision: SHA,
command: 'build',
target_layer: 'marts',
environment: 'ci',
runtime: DBT_RUNTIME_PIN,
idempotency_key: 'idem-1',
expected_target_schema: 't_alpha_marts',
...over,
};
}
function result(over: Partial<DbtJobResult> = {}): DbtJobResult {
return {
tenant_id: 't_alpha',
dbt_project: 'siax_analytics',
revision: SHA,
command: 'build',
status: 'success',
started_at: '2026-09-07T00:00:00Z',
finished_at: '2026-09-07T00:05:00Z',
artifacts: {
'manifest.json': 'st0re://a/manifest.json',
'run_results.json': 'st0re://a/run_results.json',
},
nodes: [
{ unique_id: 'model.siax_analytics.mart_sales_daily', resource_type: 'model', status: 'success' },
],
observed_dbt_version: DBT_RUNTIME_PIN.version,
...over,
};
}
describe('BI-P022 — the scaffold exists and matches the declared conventions', () => {
it.each([...REQUIRED_DBT_DIRECTORIES])('analytics/dbt/%s exists', (dir) => {
expect(fs.existsSync(path.join(DBT_ROOT, dir)), `${dir} is missing`).toBe(true);
});
it('declares a reference project covering raw -> staging -> curated -> serving', () => {
expect(fs.existsSync(path.join(DBT_ROOT, 'models/sources/sources.yml'))).toBe(true);
expect(fs.existsSync(path.join(DBT_ROOT, 'models/staging/stg_sales_events.sql'))).toBe(true);
expect(fs.existsSync(path.join(DBT_ROOT, 'models/intermediate/int_sales_enriched.sql'))).toBe(true);
expect(fs.existsSync(path.join(DBT_ROOT, 'models/marts/mart_sales_daily.sql'))).toBe(true);
expect(fs.existsSync(path.join(DBT_ROOT, 'snapshots/snap_customers.sql'))).toBe(true);
});
it('the staging model applies the tenant predicate at the first modelled layer', () => {
const sql = fs.readFileSync(path.join(DBT_ROOT, 'models/staging/stg_sales_events.sql'), 'utf8');
expect(sql).toContain('where tenant_id = \'{{ var("siax_tenant_id") }}\'');
});
it('the mart reads intermediate, never a source directly', () => {
const sql = fs.readFileSync(path.join(DBT_ROOT, 'models/marts/mart_sales_daily.sql'), 'utf8');
expect(sql).toContain("ref('int_sales_enriched')");
expect(sql).not.toContain('source(');
});
it('ships a test that fails on an EMPTY mart', () => {
// Without it, every column test passes trivially over zero rows.
const sql = fs.readFileSync(path.join(DBT_ROOT, 'tests/assert_mart_is_not_empty.sql'), 'utf8');
expect(sql).toContain('= 0');
});
it('ships a cross-tenant test even though it should be impossible to fail', () => {
const sql = fs.readFileSync(path.join(DBT_ROOT, 'tests/assert_no_cross_tenant_rows.sql'), 'utf8');
expect(sql).toContain('tenant_id !=');
});
it("maps the four layers onto BI-P003's tiers", () => {
expect(DBT_LAYER_TIERS).toEqual({
sources: 'RAW',
staging: 'NORMALIZED',
intermediate: 'CURATED',
marts: 'SERVING',
});
expect([...DBT_LAYERS]).toEqual(['sources', 'staging', 'intermediate', 'marts']);
});
it('assigns a tier from a model path, and refuses one it cannot place', () => {
expect(tierForModelPath('models/marts/mart_sales_daily.sql')).toBe('SERVING');
expect(tierForModelPath('analytics/dbt/models/staging/x.sql')).toBe('NORMALIZED');
expect(() => tierForModelPath('models/scratch/x.sql')).toThrowError(SiaxError);
});
});
describe('BI-P022 — the version rule is a GATE, not a paragraph', () => {
it('the shipped pin is honestly UNREVIEWED', () => {
// If someone flips these without doing the review, that is a deliberate
// act visible in a diff — which is the point of storing the state.
expect(DBT_RUNTIME_PIN.licenseReviewed).toBe(false);
expect(DBT_RUNTIME_PIN.securityReviewed).toBe(false);
expect(DBT_RUNTIME_PIN.line).toBe('stable');
});
it('refuses a PRODUCTION run against an unreviewed runtime', () => {
expect(() => assertDbtRuntimeCertified(DBT_RUNTIME_PIN, 'production')).toThrowError(SiaxError);
});
it('allows development and CI against the same unreviewed runtime', () => {
expect(() => assertDbtRuntimeCertified(DBT_RUNTIME_PIN, 'ci')).not.toThrow();
expect(() => assertDbtRuntimeCertified(DBT_RUNTIME_PIN, 'development')).not.toThrow();
});
it('allows production once both reviews are recorded', () => {
expect(() => assertDbtRuntimeCertified(CERTIFIED_PIN, 'production')).not.toThrow();
});
it('refuses an ALPHA line in production without a separate certification reference', () => {
const alpha = { ...CERTIFIED_PIN, line: 'alpha' as const };
expect(() => assertDbtRuntimeCertified(alpha, 'production')).toThrowError(SiaxError);
expect(() =>
assertDbtRuntimeCertified({ ...alpha, separateCertificationRef: 'CERT-2026-11' }, 'production'),
).not.toThrow();
});
it('refuses a version range — a pin is exact or it is not a pin', () => {
expect(() => assertDbtRuntimeCertified({ ...CERTIFIED_PIN, version: '1.10' }, 'ci')).toThrowError(
SiaxError,
);
expect(() => assertDbtRuntimeCertified({ ...CERTIFIED_PIN, version: '^1.10.0' }, 'ci')).toThrowError(
SiaxError,
);
});
});
describe('BI-P022 — the job request', () => {
it('accepts a well-formed request', () => {
expect(() => assertValidDbtJobRequest(request())).not.toThrow();
});
it("refuses a branch name as the revision — BI-P022's DoD is reproducibility", () => {
for (const rev of ['main', 'HEAD', 'v1.0.0', 'a'.repeat(39)]) {
expect(() => assertValidDbtJobRequest(request({ revision: rev }))).toThrowError(SiaxError);
}
});
it('refuses a target schema that is not scoped to the tenant', () => {
let thrown: unknown;
try {
assertValidDbtJobRequest(request({ expected_target_schema: 't_beta_marts' }));
} catch (e) {
thrown = e;
}
expect((thrown as SiaxError).code).toBe('AUTHORIZATION_DENIED');
});
it('refuses a selector carrying shell metacharacters', () => {
for (const selector of ['stg_sales; rm -rf /', '$(whoami)', 'a`b`', 'x && y', 'a|b']) {
expect(() => assertValidDbtJobRequest(request({ select: [selector] }))).toThrowError(SiaxError);
}
// ...while accepting real dbt selector syntax.
expect(() =>
assertValidDbtJobRequest(
request({ select: ['tag:tier:SERVING+', 'state:modified', '+mart_sales_daily'] }),
),
).not.toThrow();
});
it('refuses a job targeting the sources layer — sources are declared, not built', () => {
expect(() => assertValidDbtJobRequest(request({ target_layer: 'sources' }))).toThrowError(SiaxError);
});
it('refuses a request with no idempotency key', () => {
expect(() => assertValidDbtJobRequest(request({ idempotency_key: '' }))).toThrowError(SiaxError);
});
it('refuses a production request on the unreviewed pin', () => {
expect(() =>
assertValidDbtJobRequest(
request({ environment: 'production', expected_target_schema: 't_alpha_marts' }),
),
).toThrowError(SiaxError);
});
});
describe('BI-P022 — the job RESULT is untrusted input', () => {
it('accepts a well-formed result', () => {
expect(() => assertValidDbtJobResult(result(), request())).not.toThrow();
});
it('REFUSES success with zero nodes — a selector matching nothing exits 0', () => {
let thrown: unknown;
try {
assertValidDbtJobResult(result({ nodes: [] }), request());
} catch (e) {
thrown = e;
}
expect(thrown).toBeInstanceOf(SiaxError);
expect((thrown as SiaxError).message).toContain('zero nodes');
});
it('refuses success while nodes failed', () => {
expect(() =>
assertValidDbtJobResult(
result({ nodes: [{ unique_id: 't1', resource_type: 'test', status: 'fail' }] }),
request(),
),
).toThrowError(SiaxError);
});
it('refuses a runtime that is not the pinned one', () => {
expect(() => assertValidDbtJobResult(result({ observed_dbt_version: '1.9.0' }), request())).toThrowError(
SiaxError,
);
});
it('refuses a result for a different revision', () => {
expect(() => assertValidDbtJobResult(result({ revision: 'b'.repeat(40) }), request())).toThrowError(
SiaxError,
);
});
it('refuses a result for a different tenant', () => {
expect(() => assertValidDbtJobResult(result({ tenant_id: 't_beta' }), request())).toThrowError(SiaxError);
});
it.each([...REQUIRED_DBT_ARTIFACTS])('refuses a result missing %s', (artifact) => {
const artifacts = { ...result().artifacts };
delete artifacts[artifact];
expect(() => assertValidDbtJobResult(result({ artifacts }), request())).toThrowError(SiaxError);
});
});
describe('BI-P022 — layer dependencies are checked against the graph, not the convention', () => {
it("accepts the reference project's own edges", () => {
expect(() =>
assertLayerDependenciesLegal([
{ from: 'models/staging/stg_sales_events.sql', to: 'models/sources/sources.yml' },
{ from: 'models/intermediate/int_sales_enriched.sql', to: 'models/staging/stg_sales_events.sql' },
{ from: 'models/marts/mart_sales_daily.sql', to: 'models/intermediate/int_sales_enriched.sql' },
]),
).not.toThrow();
});
it('refuses a mart reading a source directly — raw data reaching a dashboard', () => {
expect(() =>
assertLayerDependenciesLegal([
{ from: 'models/marts/mart_sales_daily.sql', to: 'models/sources/sources.yml' },
]),
).toThrowError(SiaxError);
});
it('refuses a mart reading staging — one layer skipped is still a skip', () => {
expect(() =>
assertLayerDependenciesLegal([
{ from: 'models/marts/mart_sales_daily.sql', to: 'models/staging/stg_sales_events.sql' },
]),
).toThrowError(SiaxError);
});
it('refuses a staging model reading a mart — an upward edge', () => {
expect(() =>
assertLayerDependenciesLegal([
{ from: 'models/staging/stg_sales_events.sql', to: 'models/marts/mart_sales_daily.sql' },
]),
).toThrowError(SiaxError);
});
it('allows a model reading another in the same layer', () => {
expect(() =>
assertLayerDependenciesLegal([
{ from: 'models/staging/stg_sales_events.sql', to: 'models/staging/stg_customers.sql' },
]),
).not.toThrow();
});
});
+326
View File
@@ -0,0 +1,326 @@
/**
* tests/analytics/duckdb-provider.test.ts
* ========================================
* BI-P014 — the parts provable without a DuckDB, plus the pin on the parts
* that are not.
*
* The live suite (tests/duckdb/duckdb-provider.live.test.ts) only
* runs when DUCKDB_PYTHON is set. On a runner without it, it contributes
* nothing — so the recorded evidence is committed and THIS file, which never
* skips, checks it. In particular it pins the finding that makes layer 2 real:
*
* `allowed_directories` WITHOUT `enable_external_access=false` permits
* /etc/passwd. Measured, recorded, and asserted here — because a comment
* saying so would rot the moment someone "simplified" the bootstrap.
*/
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
ArtifactMountRegistry,
assertSessionSandboxed,
duckDbSessionBootstrap,
escapeLiteral,
DuckDbAnalyticsProvider,
REQUIRED_SANDBOX_SETTINGS,
type DuckDbRunner,
} from '@/src/analytics/providers/duckdb-provider';
const EVIDENCE_PATH = path.join(process.cwd(), 'evidence/bi-p014/duckdb-sandbox.json');
const FIXTURES = path.join(process.cwd(), 'tests/fixtures/duckdb');
const IDENTITY = { tenant_id: 't_alpha', principal_id: 'u_1' };
const capturingRunner = (): DuckDbRunner & { lastSql?: string; lastBootstrap?: readonly string[] } => {
const r: DuckDbRunner & { lastSql?: string; lastBootstrap?: readonly string[] } = {
engine: 'duckdb',
async run({ bootstrap, sql }) {
r.lastSql = sql;
r.lastBootstrap = bootstrap;
return [];
},
};
return r;
};
describe('BI-P014 — the session bootstrap is one unit, not three settings', () => {
it('emits all three statements, external access LAST-but-one and the lock last', () => {
const stmts = duckDbSessionBootstrap(['/mnt/artifacts']);
expect(stmts).toHaveLength(3);
expect(stmts[0]).toContain('allowed_directories');
expect(stmts[1]).toBe('SET enable_external_access=false');
expect(stmts[2]).toBe('SET lock_configuration=true');
});
it('refuses an EMPTY allow-list — that is not a sandbox', () => {
expect(() => duckDbSessionBootstrap([])).toThrowError(SiaxError);
});
it('refuses a relative or quote-carrying directory', () => {
expect(() => duckDbSessionBootstrap(['relative/path'])).toThrowError(SiaxError);
expect(() => duckDbSessionBootstrap(["/mnt/it's"])).toThrowError(SiaxError);
});
it.each([...REQUIRED_SANDBOX_SETTINGS])(
'assertSessionSandboxed refuses a session missing %s',
(setting) => {
const stmts = duckDbSessionBootstrap(['/mnt/artifacts']).filter((s) => !s.includes(setting));
expect(() => assertSessionSandboxed(stmts)).toThrowError(SiaxError);
},
);
it('refuses a session that sets the allow-list but leaves external access ON', () => {
// The exact naive spelling. It looks configured and permits everything.
const naive = [
"SET allowed_directories=['/mnt/artifacts']",
'SET enable_external_access=true',
'SET lock_configuration=true',
];
expect(() => assertSessionSandboxed(naive)).toThrowError(SiaxError);
});
});
describe('BI-P014 — the mount registry refuses everything that is not a mounted artifact', () => {
function registry(): ArtifactMountRegistry {
// A fake realpath, so path semantics are tested without touching disk.
const fakeReal = (p: string) => (p.includes('symlinked') ? '/etc/passwd' : p);
const reg = new ArtifactMountRegistry('/mnt/artifacts', fakeReal);
reg.register({
artifact_id: 'a_ok',
tenant_id: 't_alpha',
st0re_ref: 'st0re://x',
relative_path: 'sales.parquet',
format: 'parquet',
size_bytes: 10,
});
return reg;
}
it('resolves a mounted artifact for its owner', () => {
expect(registry().resolve(IDENTITY, 'a_ok').absolutePath).toBe('/mnt/artifacts/sales.parquet');
});
it('refuses an absolute mount path', () => {
expect(() =>
registry().register({
artifact_id: 'a_abs',
tenant_id: 't_alpha',
st0re_ref: 'x',
relative_path: '/etc/passwd',
format: 'csv',
size_bytes: 1,
}),
).toThrowError(SiaxError);
});
it('refuses a path that resolves outside the root once symlinks are followed', () => {
expect(() =>
registry().register({
artifact_id: 'a_link',
tenant_id: 't_alpha',
st0re_ref: 'x',
relative_path: 'symlinked.parquet',
format: 'parquet',
size_bytes: 1,
}),
).toThrowError(SiaxError);
});
it("refuses a sibling directory that merely shares the root's prefix", () => {
// `startsWith('/mnt/artifacts')` alone would accept `/mnt/artifacts-evil`.
const reg = new ArtifactMountRegistry('/mnt/artifacts', (p) =>
p.includes('sibling') ? '/mnt/artifacts-evil/x.parquet' : p,
);
expect(() =>
reg.register({
artifact_id: 'a_sib',
tenant_id: 't_alpha',
st0re_ref: 'x',
relative_path: 'sibling.parquet',
format: 'parquet',
size_bytes: 1,
}),
).toThrowError(SiaxError);
});
it('refuses a request with no verified tenant', () => {
expect(() => registry().resolve({ tenant_id: '', principal_id: 'u' }, 'a_ok')).toThrowError(SiaxError);
});
it('distinguishes NOT_FOUND from AUTHORIZATION_DENIED', () => {
const reg = registry();
try {
reg.resolve(IDENTITY, 'a_missing');
} catch (e) {
expect((e as SiaxError).code).toBe('NOT_FOUND');
}
try {
reg.resolve({ tenant_id: 't_beta', principal_id: 'u' }, 'a_ok');
} catch (e) {
// An attempted cross-tenant read must be visible in the audit trail as
// one, not disguised as a missing object.
expect((e as SiaxError).code).toBe('AUTHORIZATION_DENIED');
}
});
it('refuses an artifact id that is not registry-safe', () => {
for (const bad of ['../x', 'a b', "a'b", 'a/b', '']) {
expect(() => registry().resolve(IDENTITY, bad)).toThrowError(SiaxError);
}
});
});
describe('BI-P014 — the query builder has no caller-SQL surface', () => {
function provider(runner: DuckDbRunner, sizeBytes = 10) {
const reg = new ArtifactMountRegistry('/mnt/artifacts', (p) => p);
reg.register({
artifact_id: 'a_ok',
tenant_id: 't_alpha',
st0re_ref: 'x',
relative_path: 'sales.parquet',
format: 'parquet',
size_bytes: sizeBytes,
});
return new DuckDbAnalyticsProvider(reg, runner);
}
it('builds a reader from the RESOLVED path, never from caller text', async () => {
const r = capturingRunner();
await provider(r).query(IDENTITY, { artifact_id: 'a_ok', select: ['country'] });
expect(r.lastSql).toContain("read_parquet('/mnt/artifacts/sales.parquet')");
});
it('always applies the sandbox bootstrap before the query', async () => {
const r = capturingRunner();
await provider(r).query(IDENTITY, { artifact_id: 'a_ok' });
expect(() => assertSessionSandboxed(r.lastBootstrap ?? [])).not.toThrow();
});
it.each(['a b', 'x; DROP TABLE t', '*', '1=1', "a'", '../x'])(
'refuses %s as a column name',
async (col) => {
await expect(
provider(capturingRunner()).query(IDENTITY, { artifact_id: 'a_ok', select: [col] }),
).rejects.toBeInstanceOf(SiaxError);
},
);
it('hands a heavy artifact to N0D instead of running it locally', async () => {
let thrown: unknown;
try {
await provider(capturingRunner(), 40 * 1024 * 1024 * 1024).query(IDENTITY, { artifact_id: 'a_ok' });
} catch (e) {
thrown = e;
}
expect((thrown as SiaxError).code).toBe('CAPABILITY_UNAVAILABLE');
expect((thrown as SiaxError).message).toContain('N0D');
});
it("escapes a literal by DOUBLING the quote, which is DuckDB's only escape", () => {
// MEASURED on DuckDB 1.5.5 rather than assumed, because the whole escaping
// strategy rests on it: `SELECT length('a\\b')` returns 4, so a backslash
// is a literal character; and `SELECT 'a\''` is a PARSER ERROR
// ("unterminated quoted string"), which is what a non-escaping backslash
// produces. A dialect where `\'` closed the literal would make doubling
// insufficient.
expect(escapeLiteral("O'Brien")).toBe("O''Brien");
// A backslash is NOT an escape inside a DuckDB single-quoted string, so it
// must survive untouched rather than being "helpfully" doubled.
expect(escapeLiteral("a\\'b")).toBe("a\\''b");
expect(escapeLiteral("x' OR '1'='1")).toBe("x'' OR ''1''=''1");
});
it('refuses a NUL byte in a filter value rather than escaping it', () => {
expect(() => escapeLiteral('a\u0000b')).toThrowError(SiaxError);
});
it('declares which formats have actually been PROVEN, and why the others have not', () => {
const readiness = provider(capturingRunner()).readiness();
expect(readiness.proven).toContain('parquet');
expect(readiness.proven).toContain('iceberg');
const arrow = readiness.unproven.find((u) => u.format === 'arrow_ipc');
expect(arrow?.reason).toContain('network install');
});
});
describe('BI-P014 — the committed evidence, checked by a test that never skips', () => {
it('the evidence file exists', () => {
expect(
fs.existsSync(EVIDENCE_PATH),
'evidence/bi-p014/duckdb-sandbox.json is missing — run the live suite with DUCKDB_PYTHON set',
).toBe(true);
});
const evidence = fs.existsSync(EVIDENCE_PATH)
? (JSON.parse(fs.readFileSync(EVIDENCE_PATH, 'utf8')) as Record<string, never>)
: ({} as Record<string, never>);
it('was recorded against a real DuckDB', () => {
expect(String(evidence.duckdb_version ?? '')).toMatch(/^\d+\.\d+/);
});
it('PINS the finding: allowed_directories alone read /etc/passwd', () => {
// The load-bearing assertion of this whole file. If someone "simplifies"
// the bootstrap down to the allow-list, the module comment would become a
// lie quietly; this keeps the measurement attached to the build.
const naive = evidence.naive_allowed_directories_is_a_noop as unknown as {
read_etc_passwd_succeeded: boolean;
statements: string[];
};
expect(naive).toBeDefined();
expect(naive.read_etc_passwd_succeeded).toBe(true);
expect(naive.statements.join(' ')).not.toContain('enable_external_access');
});
it('records that NO bypass attempt succeeded with the full bootstrap', () => {
const attempts = evidence.sandbox_bypass_attempts as unknown as Array<{ id: string; succeeded: boolean }>;
expect(Array.isArray(attempts)).toBe(true);
expect(attempts.length).toBeGreaterThanOrEqual(10);
expect(attempts.filter((a) => a.succeeded).map((a) => a.id)).toEqual([]);
});
it('records the counterfactual — the mounted file WAS readable in the same session', () => {
// Without this, "no attempt succeeded" is equally consistent with a
// sandbox that blocks everything, which is an outage, not a control.
expect(evidence.counterfactual_mounted_file_readable).toBe(true);
});
it('records the Iceberg snapshot read, whose fixture is deliberately not committed', () => {
// pyiceberg embeds ABSOLUTE paths in its manifests, so a committed Iceberg
// table would only work on the machine that built it. The recorded result
// is the artefact instead.
const iceberg = evidence.iceberg as unknown as { totals: Record<string, number> };
expect(iceberg?.totals).toEqual({ NO: 20, SE: 40 });
});
it('records that a locked session could not re-open its own sandbox', () => {
const reopened = evidence.reconfiguration_refused as unknown as Array<{ refused: boolean }>;
expect(reopened.length).toBe(3);
expect(reopened.every((r) => r.refused)).toBe(true);
});
});
describe('BI-P014 — the committed fixtures', () => {
it('ships the Parquet and CSV fixtures the live suite reads', () => {
expect(fs.existsSync(path.join(FIXTURES, 'sales.parquet'))).toBe(true);
expect(fs.existsSync(path.join(FIXTURES, 'customers.csv'))).toBe(true);
});
it('does NOT ship the Iceberg table, because its manifests carry absolute paths', () => {
// Asserted against GIT, not the filesystem. The claim is about what is
// COMMITTED; the live suite REBUILDS that table locally, so a filesystem
// check fails whenever both suites run in one pass — it was testing the
// wrong thing rather than catching a real problem.
const tracked = execFileSync('git', ['ls-files', 'tests/fixtures/duckdb/'], {
encoding: 'utf8',
cwd: process.cwd(),
})
.split('\n')
.filter(Boolean);
// The parquet/csv fixtures ARE tracked, so a version that shipped nothing
// would fail here too rather than passing vacuously.
expect(tracked.length).toBeGreaterThan(0);
expect(tracked.filter((f) => f.includes('/iceberg'))).toEqual([]);
});
});
@@ -0,0 +1,327 @@
/**
* tests/analytics/materialization-drift.test.ts
* ==============================================
* BI-P105 — MATERIALIZATION / PRE-AGGREGATION.
*
* The DoD asks for measured improvement and documented freshness semantics.
* The failure mode it does not name, and the one that actually costs money, is
* a pre-aggregate that returns a confident wrong number. So every test here is
* written as an attack on the router:
*
* - a drifted aggregate must NOT serve, and the counterfactual (a naive
* router that only checks staleness) must serve it — otherwise the guard
* is not known to be doing anything;
* - a MISSING bucket must count as drift even though every value present is
* correct;
* - a comparison over an empty window must be `insufficient_data`, never
* `match`;
* - an aggregate that has never been verified must not serve, because on
* launch day it is exactly as unproven as a drifted one.
*/
import { describe, expect, it } from 'vitest';
import {
applyDriftReport,
detectDrift,
type AggregateBucket,
} from '@/src/analytics/materialization/drift-detector';
import {
assertSpec,
describeRouting,
materializationStaleness,
selectQuerySource,
type MaterializationSpec,
type MaterializationStatus,
} from '@/src/analytics/materialization/materialization';
import type { AnalyticsQueryRequest } from '@/src/analytics/contract/query-request';
const NOW = new Date('2026-09-07T12:00:00.000Z');
const TOLERANCE = { absolute: 0.5, relative: 0.001 };
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: 'opt_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: TOLERANCE,
};
/** Fresh, recently verified, matching. The only state that may serve. */
function healthyStatus(): MaterializationStatus {
return {
materialization_id: SPEC.materialization_id,
state: 'serving',
data_watermark: '2026-09-07T11:45:00.000Z',
last_refresh_at: '2026-09-07T11:46:00.000Z',
last_drift_check_at: '2026-09-07T06:00:00.000Z',
last_drift_verdict: 'match',
};
}
const REQUEST: AnalyticsQueryRequest = {
dataset: 'ds_sales',
metrics: ['revenue'],
dimensions: ['order_date'],
filters: [{ dimension: 'region', operator: 'eq', values: ['SE'] }],
timeRange: { from: '2026-09-01T00:00:00.000Z', to: '2026-09-07T00:00:00.000Z', grain: 'day' },
};
/**
* The router someone writes when they have thought about staleness but not
* about correctness. It exists here as the counterfactual: it must SERVE the
* drifted aggregate that `selectQuerySource` refuses.
*/
function naiveRouter(status: MaterializationStatus, now: Date): 'materialization' | 'base_table' {
const staleness = materializationStaleness(status, now) ?? 0;
return staleness <= SPEC.max_staleness_seconds ? 'materialization' : 'base_table';
}
function buckets(spec: Record<string, [number, number]>): AggregateBucket[] {
return Object.entries(spec).map(([key, [revenue, orders]]) => ({ key, values: { revenue, orders } }));
}
const SOURCE = buckets({
'2026-09-01|SE': [120_000, 410],
'2026-09-02|SE': [131_500, 442],
'2026-09-03|SE': [98_250, 305],
'2026-09-04|SE': [140_000, 480],
});
describe('BI-P105 drift detection', () => {
it('an identical aggregate matches', () => {
const report = detectDrift({
fromSource: SOURCE,
fromAggregate: SOURCE,
tolerance: TOLERANCE,
metrics: ['revenue', 'orders'],
now: NOW,
});
expect(report.verdict).toBe('match');
expect(report.buckets_compared).toBe(4);
expect(report.totals.revenue.delta).toBe(0);
});
it('a value beyond tolerance is drift, and the report says what a caller would have been told', () => {
const drifted = buckets({
'2026-09-01|SE': [120_000, 410],
'2026-09-02|SE': [131_500, 442],
'2026-09-03|SE': [98_250, 305],
// A source row was deleted (GDPR erasure) but the aggregate still counts it.
'2026-09-04|SE': [152_400, 495],
});
const report = detectDrift({
fromSource: SOURCE,
fromAggregate: drifted,
tolerance: TOLERANCE,
metrics: ['revenue', 'orders'],
now: NOW,
});
expect(report.verdict).toBe('drifted');
expect(report.worst?.key).toBe('2026-09-04|SE');
expect(report.worst?.absolute_delta).toBe(12_400);
expect(report.totals.revenue.aggregate - report.totals.revenue.source).toBe(12_400);
});
it('a MISSING bucket is drift even though every value present is correct', () => {
const lateArriving = SOURCE.filter((b) => b.key !== '2026-09-04|SE');
const report = detectDrift({
fromSource: SOURCE,
fromAggregate: lateArriving,
tolerance: TOLERANCE,
metrics: ['revenue', 'orders'],
now: NOW,
});
expect(report.discrepancies).toHaveLength(0); // every compared value agrees
expect(report.verdict).toBe('drifted'); // and it is still wrong
expect(report.missing_in_aggregate).toEqual(['2026-09-04|SE']);
expect(report.totals.revenue.delta).toBe(-140_000);
});
it('an EXTRA bucket is drift — the source rows are gone, the aggregate is not', () => {
const stale = [...SOURCE, { key: '2026-08-31|SE', values: { revenue: 90_000, orders: 300 } }];
const report = detectDrift({
fromSource: SOURCE,
fromAggregate: stale,
tolerance: TOLERANCE,
metrics: ['revenue', 'orders'],
now: NOW,
});
expect(report.verdict).toBe('drifted');
expect(report.extra_in_aggregate).toEqual(['2026-08-31|SE']);
});
it('an EMPTY comparison is insufficient_data, not match', () => {
const report = detectDrift({
fromSource: [],
fromAggregate: [],
tolerance: TOLERANCE,
metrics: ['revenue'],
now: NOW,
});
expect(report.verdict).toBe('insufficient_data');
expect(report.buckets_compared).toBe(0);
// And it must not be allowed to serve on the strength of that.
const status = applyDriftReport(healthyStatus(), report);
expect(status.state).toBe('drifted');
});
it('both tolerances must hold — a large bucket cannot hide behind a relative bound', () => {
const source = buckets({ 'b|SE': [40_000_000, 1] });
const off = buckets({ 'b|SE': [40_020_000, 1] }); // 0.05%: inside relative, far outside absolute
const report = detectDrift({
fromSource: source,
fromAggregate: off,
tolerance: { absolute: 1000, relative: 0.001 },
metrics: ['revenue'],
now: NOW,
});
expect(report.verdict).toBe('drifted');
expect(report.worst?.relative_delta).toBeCloseTo(0.0005, 6);
});
it('a bucket that should be zero and is not is drift, not a division error', () => {
const report = detectDrift({
fromSource: buckets({ 'b|SE': [0, 0] }),
fromAggregate: buckets({ 'b|SE': [12, 1] }),
tolerance: TOLERANCE,
metrics: ['revenue'],
now: NOW,
});
expect(report.verdict).toBe('drifted');
expect(report.worst?.relative_delta).toBe(Number.POSITIVE_INFINITY);
});
});
describe('BI-P105 routing — a pre-aggregate serves only while it is provably current and undrifted', () => {
it('serves when everything is proved', () => {
const decision = selectQuerySource({ request: REQUEST, spec: SPEC, status: healthyStatus(), now: NOW });
expect(decision.source).toBe('materialization');
expect(describeRouting(decision)).toMatchObject({
served_from: 'materialization',
materialization_id: 'mv_sales_daily',
staleness_seconds: 900,
});
});
it('a DRIFTED aggregate is refused — and the naive router serves it', () => {
const drifted = applyDriftReport(healthyStatus(), {
verdict: 'drifted',
checked_at: '2026-09-07T11:00:00.000Z',
buckets_compared: 4,
missing_in_aggregate: [],
extra_in_aggregate: [],
discrepancies: [],
tolerance: TOLERANCE,
totals: {},
});
const guarded = selectQuerySource({ request: REQUEST, spec: SPEC, status: drifted, now: NOW });
expect(guarded.source).toBe('base_table');
expect(guarded).toMatchObject({ refusal: 'state_not_serving' });
// The counterfactual: the same state, routed by staleness alone.
expect(naiveRouter(drifted, NOW)).toBe('materialization');
});
it('a NEVER-VERIFIED aggregate is refused — and the naive router serves it', () => {
const brandNew: MaterializationStatus = {
materialization_id: SPEC.materialization_id,
state: 'serving',
data_watermark: '2026-09-07T11:59:00.000Z',
last_refresh_at: '2026-09-07T11:59:00.000Z',
};
const guarded = selectQuerySource({ request: REQUEST, spec: SPEC, status: brandNew, now: NOW });
expect(guarded).toMatchObject({ source: 'base_table', refusal: 'drift_never_verified' });
expect(naiveRouter(brandNew, NOW)).toBe('materialization');
});
it('a verification older than the required interval is refused', () => {
const status = { ...healthyStatus(), last_drift_check_at: '2026-09-05T06:00:00.000Z' };
expect(selectQuerySource({ request: REQUEST, spec: SPEC, status, now: NOW })).toMatchObject({
refusal: 'drift_verification_stale',
});
});
it('an UNKNOWN watermark is refused rather than treated as current', () => {
const status = { ...healthyStatus(), data_watermark: undefined };
expect(materializationStaleness(status, NOW)).toBeUndefined();
expect(selectQuerySource({ request: REQUEST, spec: SPEC, status, now: NOW })).toMatchObject({
refusal: 'watermark_unknown',
});
});
it('an aggregate older than its freshness contract is refused', () => {
const status = { ...healthyStatus(), data_watermark: '2026-09-07T09:00:00.000Z' };
expect(selectQuerySource({ request: REQUEST, spec: SPEC, status, now: NOW })).toMatchObject({
refusal: 'staleness_exceeded',
});
});
it('a question that reaches past the watermark is refused, not silently shortened', () => {
const request = { ...REQUEST, timeRange: { ...REQUEST.timeRange, to: '2026-09-07T12:00:00.000Z' } };
expect(selectQuerySource({ request, spec: SPEC, status: healthyStatus(), now: NOW })).toMatchObject({
refusal: 'window_beyond_watermark',
});
});
it('a filter on a dimension the aggregate summed across is refused', () => {
const request = {
...REQUEST,
filters: [{ dimension: 'sales_channel', operator: 'eq' as const, values: ['web'] }],
};
const decision = selectQuerySource({ request, spec: SPEC, status: healthyStatus(), now: NOW });
expect(decision).toMatchObject({ source: 'base_table', refusal: 'coverage_miss' });
expect((decision as { detail: string }).detail).toMatch(/already summed across it/);
});
it('a metric or dimension the aggregate does not carry is refused', () => {
expect(
selectQuerySource({
request: { ...REQUEST, metrics: ['margin'] },
spec: SPEC,
status: healthyStatus(),
now: NOW,
}),
).toMatchObject({ refusal: 'coverage_miss' });
expect(
selectQuerySource({
request: { ...REQUEST, dimensions: ['product'] },
spec: SPEC,
status: healthyStatus(),
now: NOW,
}),
).toMatchObject({ refusal: 'coverage_miss' });
});
it('a daily aggregate cannot answer an hourly question, but can answer a monthly one', () => {
const hourly = { ...REQUEST, timeRange: { ...REQUEST.timeRange, grain: 'hour' as const } };
expect(
selectQuerySource({ request: hourly, spec: SPEC, status: healthyStatus(), now: NOW }),
).toMatchObject({ refusal: 'coverage_miss' });
const monthly = { ...REQUEST, timeRange: { ...REQUEST.timeRange, grain: 'month' as const } };
expect(
selectQuerySource({ request: monthly, spec: SPEC, status: healthyStatus(), now: NOW }).source,
).toBe('materialization');
});
it('a WEEKLY aggregate cannot answer a monthly question — weeks do not compose into months', () => {
const weekly = { ...SPEC, grain: 'week' as const };
const monthly = { ...REQUEST, timeRange: { ...REQUEST.timeRange, grain: 'month' as const } };
expect(
selectQuerySource({ request: monthly, spec: weekly, status: healthyStatus(), now: NOW }),
).toMatchObject({ refusal: 'coverage_miss' });
});
it('a spec with no drift check interval is refused at declaration time', () => {
expect(() => assertSpec({ ...SPEC, drift_check_interval_seconds: 0 })).toThrow(/never re-verified/);
expect(() => assertSpec(SPEC)).not.toThrow();
});
});
+483
View File
@@ -0,0 +1,483 @@
/**
* tests/analytics/metric-governance.test.ts
* ==========================================
* BI-P028 (metric domain model), BI-P030 (semantic model registry),
* BI-P031 (metric governance), BI-P029 (semantic provider — the parts not
* needing a Python runtime).
*
* Each prompt's DoD is turned into something that can FAIL:
*
* BI-P028 "No production metric exists only inside a dashboard tool."
* A dashboard panel carrying an inline aggregation / expression /
* SQL is REFUSED, and so is one naming an unregistered metric.
*
* BI-P030 "MetricFlow can be replaced without breaking canonical SIAX
* metric IDs." Two providers with different naming rules compile
* the same registry version; the canonical id set must be
* identical and the provider BINDINGS must differ — otherwise the
* test would pass for a registry that simply has one provider.
*
* BI-P031 "Certified metric cannot be modified in-place; new version
* required." Every semantic field is mutated one at a time and
* each must be refused; every editorial field is mutated and each
* must be allowed.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
assertMetricEditAllowed,
assertPanelUsesRegisteredMetric,
assertValidMetricSpec,
certifyMetric,
metricMeaningHash,
nextMetricVersion,
METRIC_STATUSES,
type GovernedMetric,
type MetricSpec,
} from '@/src/analytics/metrics/metric-model';
import {
assertEngineNeutral,
assertOnlySemanticModelFields,
InMemorySemanticModelStore,
SemanticModelRegistry,
semanticModelHash,
type SemanticModelVersion,
} from '@/src/analytics/metrics/semantic-registry';
import { MetricFlowProvider, type SiaxSemanticProvider } from '@/src/analytics/metrics/semantic-provider';
import { compileRequestToSemantic } from '@/src/analytics/contract/compile-semantic';
import {
parseAnalyticsQueryRequest,
queryResolutionFrom,
resolveAnalyticsQuery,
} from '@/src/analytics/contract/query-request';
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',
};
const GOVERNED: GovernedMetric = {
spec: REVENUE,
governance: {
certification: 'certified',
business_definition: 'What we actually invoiced, after credits.',
technical_definition: "sum(amount_sek) on ds_sales where channel != 'internal', by invoiced_at.",
owner: 'finance@siax.io',
lineage_refs: ['ds_sales@v42'],
quality_status: 'passing',
},
};
describe('BI-P028 — a metric that cannot mean nothing', () => {
it('accepts the golden metric', () => {
expect(() => assertValidMetricSpec(REVENUE)).not.toThrow();
});
const rejections: Array<[string, Partial<MetricSpec>]> = [
['no description', { description: '' }],
['no owner', { owner: '' }],
['no time dimension', { timeDimension: '' }],
['a ratio with no denominator', { type: 'ratio' }],
['a denominator on a non-ratio', { denominator: 'orders' }],
['currency format with no currency', { currency: undefined }],
['a currency on a non-currency format', { format: 'integer' }],
['a non-ISO currency', { currency: 'kronor' as string }],
['a name that is not snake_case', { name: 'Net Revenue' }],
['a duplicate dimension', { dimensions: ['country', 'country'] }],
[
'a filter on an undeclared dimension',
{ filters: [{ dimension: 'segment', operator: 'eq', values: ['x'] }] },
],
['a value operator with no values', { filters: [{ dimension: 'channel', operator: 'eq', values: [] }] }],
[
'a presence operator with values',
{ filters: [{ dimension: 'channel', operator: 'is_null', values: ['x'] }] },
],
['version zero', { version: 0 }],
];
it.each(rejections)('refuses %s', (_label, override) => {
expect(() => assertValidMetricSpec({ ...REVENUE, ...override })).toThrowError(SiaxError);
});
it('declares the five lifecycle statuses BI-P028 names, in order', () => {
expect([...METRIC_STATUSES]).toEqual(['DRAFT', 'REVIEW', 'ACTIVE', 'DEPRECATED', 'RETIRED']);
});
});
describe('BI-P028 DoD — no production metric exists only inside a dashboard tool', () => {
const lookup = (id: string) => (id === 'm_revenue' ? GOVERNED : undefined);
it.each(['inline_expression', 'inline_aggregation', 'inline_sql'])(
'refuses a panel that defines a metric via %s',
(field) => {
expect(() =>
assertPanelUsesRegisteredMetric({ panel_id: 'p1', [field]: 'sum(amount)' }, lookup),
).toThrowError(SiaxError);
},
);
it('refuses a panel that names an unregistered metric', () => {
expect(() =>
assertPanelUsesRegisteredMetric({ panel_id: 'p1', metric_id: 'm_invented' }, lookup),
).toThrowError(SiaxError);
});
it('refuses a panel with no metric at all', () => {
expect(() => assertPanelUsesRegisteredMetric({ panel_id: 'p1' }, lookup)).toThrowError(SiaxError);
});
it('refuses a panel pointing at a RETIRED metric', () => {
const retired = { ...GOVERNED, spec: { ...REVENUE, status: 'RETIRED' as const } };
expect(() =>
assertPanelUsesRegisteredMetric({ panel_id: 'p1', metric_id: 'm_revenue' }, () => retired),
).toThrowError(SiaxError);
});
it('accepts a panel that references a registered, live metric', () => {
expect(assertPanelUsesRegisteredMetric({ panel_id: 'p1', metric_id: 'm_revenue' }, lookup).spec.id).toBe(
'm_revenue',
);
});
});
describe('BI-P031 DoD — a certified metric cannot be modified in place', () => {
/** Every field that changes what the number MEANS. */
const semanticEdits: Array<[string, Partial<MetricSpec>]> = [
['the measure', { measure: 'amount_eur' }],
['the aggregation', { aggregation: 'avg' }],
['the type', { type: 'ratio', denominator: 'orders' }],
['the dimensions', { dimensions: ['country'] }],
['the filters', { filters: [] }],
['the time dimension', { timeDimension: 'paid_at' }],
['the unit', { unit: 'EUR' }],
['the currency', { currency: 'EUR' }],
];
it.each(semanticEdits)('refuses an in-place change to %s', (_label, override) => {
const proposed = { ...REVENUE, ...override };
let thrown: unknown;
try {
assertMetricEditAllowed(GOVERNED, proposed);
} catch (e) {
thrown = e;
}
expect(thrown, "a certified metric's meaning was changed in place").toBeInstanceOf(SiaxError);
expect((thrown as SiaxError).code).toBe('CONFLICT');
expect((thrown as SiaxError).message).toContain('version 4');
});
/** Editorial fields stay editable — forcing a version bump for a typo is how teams route around governance. */
const editorialEdits: Array<[string, Partial<MetricSpec>]> = [
['the description', { description: 'Clearer wording.' }],
['the owner', { owner: 'controlling@siax.io' }],
['the lifecycle status', { status: 'DEPRECATED' }],
];
it.each(editorialEdits)('allows an in-place change to %s', (_label, override) => {
expect(() => assertMetricEditAllowed(GOVERNED, { ...REVENUE, ...override })).not.toThrow();
});
it('allows any change to an EXPERIMENTAL metric', () => {
const experimental = {
...GOVERNED,
governance: { ...GOVERNED.governance, certification: 'experimental' as const },
};
expect(() => assertMetricEditAllowed(experimental, { ...REVENUE, measure: 'anything' })).not.toThrow();
});
it('mints a new version that is DRAFT and EXPERIMENTAL, never inheriting the certification', () => {
const next = nextMetricVersion(
GOVERNED,
{ measure: 'amount_eur', unit: 'EUR', currency: 'EUR' },
'switch to EUR',
);
expect(next.spec.version).toBe(4);
expect(next.spec.status).toBe('DRAFT');
expect(next.governance.certification).toBe('experimental');
expect(next.governance.certified_at).toBeUndefined();
expect(next.change_reason).toBe('switch to EUR');
});
it('requires a change reason for a new version', () => {
expect(() => nextMetricVersion(GOVERNED, { measure: 'x' }, ' ')).toThrowError(SiaxError);
});
it('refuses to change the metric id under the guise of an edit', () => {
expect(() => assertMetricEditAllowed(GOVERNED, { ...REVENUE, id: 'm_other' })).toThrowError(SiaxError);
});
it('the meaning hash ignores editorial fields and catches semantic ones', () => {
expect(metricMeaningHash({ ...REVENUE, description: 'different', owner: 'x', status: 'DRAFT' })).toBe(
metricMeaningHash(REVENUE),
);
expect(metricMeaningHash({ ...REVENUE, measure: 'other' })).not.toBe(metricMeaningHash(REVENUE));
// Filter ORDER is not meaning; filter CONTENT is.
expect(
metricMeaningHash({
...REVENUE,
filters: [
{ dimension: 'country', operator: 'eq', values: ['SE', 'NO'] },
{ dimension: 'channel', operator: 'ne', values: ['internal'] },
],
}),
).not.toBe(metricMeaningHash(REVENUE));
});
it('certification is an act with an actor and a time, and needs both definitions', () => {
const draft: GovernedMetric = {
spec: { ...REVENUE, status: 'DRAFT' },
governance: { ...GOVERNED.governance, certification: 'experimental' },
};
expect(() => certifyMetric(draft, 'u_1', '2026-09-07T00:00:00Z')).toThrowError(SiaxError);
const active = { ...draft, spec: { ...draft.spec, status: 'ACTIVE' as const } };
const noDefs = { ...active, governance: { ...active.governance, technical_definition: '' } };
expect(() => certifyMetric(noDefs, 'u_1', '2026-09-07T00:00:00Z')).toThrowError(SiaxError);
const certified = certifyMetric(active, 'u_1', '2026-09-07T00:00:00Z');
expect(certified.governance.certification).toBe('certified');
expect(certified.governance.certified_by).toBe('u_1');
});
});
// ── BI-P030 ────────────────────────────────────────────────────────────────
function model(version = 1): Omit<SemanticModelVersion, 'hash'> {
return {
model_id: 'sm_sales',
version,
tenant_id: 't_alpha',
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',
};
}
describe('BI-P030 — the registry is engine-neutral and its versions are immutable', () => {
it('refuses a model that names an implementation engine anywhere in it', async () => {
for (const smuggled of [
{ model_id: 'sm_metricflow_sales' },
{ datasets: ['clickhouse_sales'] },
{ metrics: [{ ...REVENUE, description: 'computed by MetricFlow' }] },
]) {
expect(() =>
assertEngineNeutral({ ...model(), ...smuggled } as Omit<SemanticModelVersion, 'hash'>),
).toThrowError(SiaxError);
}
});
it('refuses a metric naming a dimension the model does not define', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
await expect(
registry.publish({ ...model(), metrics: [{ ...REVENUE, dimensions: ['country', 'segment'] }] }),
).rejects.toBeInstanceOf(SiaxError);
});
it('refuses a metric whose time dimension is not declared as a time dimension', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
await expect(
registry.publish({ ...model(), metrics: [{ ...REVENUE, timeDimension: 'country' }] }),
).rejects.toBeInstanceOf(SiaxError);
});
it('refuses to republish an existing version — a pinned dashboard must mean the same thing tomorrow', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
await registry.publish(model(1));
await expect(registry.publish(model(1))).rejects.toBeInstanceOf(SiaxError);
});
it('supersedes the previous active version on activation', async () => {
const store = new InMemorySemanticModelStore();
const registry = new SemanticModelRegistry(store);
await registry.publish(model(1));
await registry.publish(model(2));
await registry.activate('t_alpha', 'sm_sales', 1, '2026-09-01T00:00:00Z');
await registry.activate('t_alpha', 'sm_sales', 2, '2026-09-05T00:00:00Z');
expect((await store.get('t_alpha', 'sm_sales', 1))?.status).toBe('superseded');
expect((await store.active('t_alpha', 'sm_sales'))?.version).toBe(2);
});
it('the hash covers meaning and ignores activation', () => {
const a = semanticModelHash(model(1));
const b = semanticModelHash({
...model(1),
valid_from: '2030-01-01T00:00:00Z',
status: 'active',
} as never);
expect(a).toBe(b);
const c = semanticModelHash({ ...model(1), metrics: [{ ...REVENUE, version: 4 }] });
expect(c).not.toBe(a);
});
it('requires a verified tenant', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
await expect(registry.publish({ ...model(), tenant_id: '' })).rejects.toBeInstanceOf(SiaxError);
});
});
describe('BI-P030 DoD — the semantic engine can be replaced without breaking metric IDs', () => {
/**
* A SECOND provider with DIFFERENT naming rules, so the test cannot pass
* trivially for a registry that only ever had one provider. Cube-shaped:
* metric names are `cube.measure`, which is exactly the kind of difference
* that would break a consumer if canonical ids were not the contract.
*/
class CubeShapedProvider implements SiaxSemanticProvider {
readonly provider = 'cube-shaped';
buildManifest(m: SemanticModelVersion) {
return { cubes: m.datasets.map((d) => ({ name: d, measures: m.metrics.map((x) => x.measure) })) };
}
compile(spec: ReturnType<typeof compileRequestToSemantic>, m: SemanticModelVersion) {
const bindings = this.providerBindings(m);
return {
provider: this.provider,
query: { measures: spec.metrics.map((x) => bindings[x.metric_id]) },
canonical_metric_ids: spec.metrics.map((x) => x.metric_id).sort(),
};
}
providerBindings(m: SemanticModelVersion): Record<string, string> {
return Object.fromEntries(m.metrics.map((x) => [x.id, `ds_sales.${x.measure}`]));
}
}
it('both providers preserve the canonical ids while naming them differently', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
const published = await registry.publish(model(1));
const resolution = queryResolutionFrom({
dataset_id: 'ds_sales',
metrics: [
{
name: 'net_revenue',
metric_id: 'm_revenue',
event_metric_key: 'amount_sek',
aggregation: 'sum',
allowed_dimensions: ['country', 'channel'],
},
],
dimensions: [{ name: 'country', dimension_id: 'd_country', field_name: 'country_code' }],
semantic_model_version: 1,
});
const spec = compileRequestToSemantic(
resolveAnalyticsQuery(
parseAnalyticsQueryRequest({
dataset: 'ds_sales',
metrics: ['net_revenue'],
dimensions: ['country'],
}),
resolution,
),
);
const mf = new MetricFlowProvider();
const cube = new CubeShapedProvider();
expect(mf.compile(spec, published).canonical_metric_ids).toEqual(['m_revenue']);
expect(cube.compile(spec, published).canonical_metric_ids).toEqual(['m_revenue']);
expect(await registry.canonicalMetricIds('t_alpha', 'sm_sales', 1)).toEqual(['m_revenue']);
// ...and the providers genuinely differ, so the equality above is not
// trivially true.
expect(mf.providerBindings(published)).not.toEqual(cube.providerBindings(published));
expect(cube.providerBindings(published).m_revenue).toBe('ds_sales.amount_sek');
});
it('the MetricFlow manifest is DERIVED, never persisted into the registry', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
const published = await registry.publish(model(1));
const manifest = new MetricFlowProvider().buildManifest(published);
expect(manifest.metrics[0].name).toBe('m_revenue');
expect(manifest._generated_from.hash).toBe(published.hash);
// Two independent reasons a registry row cannot become a provider manifest.
// The vocabulary scan catches the generator stamp...
expect(() => assertEngineNeutral({ ...published, ...(manifest as object) } as never)).toThrowError(
SiaxError,
);
// ...and the structural check catches ANY extra field, which is what holds
// for a manifest that avoids the word. The first version of this test
// asserted only the vocabulary scan and passed for the wrong reason:
// buildManifest did not mention "metricflow" anywhere, so nothing fired.
expect(() => assertOnlySemanticModelFields({ ...published, semantic_models: [] })).toThrowError(
SiaxError,
);
});
it("publish refuses a model carrying any field outside BI-P030's list", async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
await expect(registry.publish({ ...model(1), compiled_sql: 'SELECT 1' } as never)).rejects.toBeInstanceOf(
SiaxError,
);
});
it('refuses to compile a metric that is not in the model version', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
const published = await registry.publish(model(1));
expect(() =>
new MetricFlowProvider().compile(
{
dataset_id: 'ds_sales',
metrics: [{ metric_id: 'm_ghost', name: 'ghost' }],
groupBy: [],
where: [],
orderBy: [],
limit: 10,
format: 'json',
},
published,
),
).toThrowError(SiaxError);
});
it('puts no SQL predicate text into the compiled provider query', async () => {
const registry = new SemanticModelRegistry(new InMemorySemanticModelStore());
const published = await registry.publish(model(1));
const compiled = new MetricFlowProvider().compile(
{
dataset_id: 'ds_sales',
metrics: [{ metric_id: 'm_revenue', name: 'net_revenue' }],
groupBy: [],
where: [{ dimension_id: 'd_country', name: 'country', operator: 'eq', values: ["SE' OR '1'='1"] }],
orderBy: [],
limit: 10,
format: 'json',
},
published,
);
const serialized = JSON.stringify(compiled.query);
expect(serialized).toContain("SE' OR '1'='1"); // survives as DATA
expect(serialized).not.toMatch(/\bWHERE\b|\bSELECT\b/);
});
});
describe('BI-P029 — the provider states what it has NOT proven', () => {
it('reports itself unverified, and names the open surfaces', () => {
const readiness = new MetricFlowProvider().providerReadiness();
expect(readiness.verified).toBe(false);
expect(readiness.open.join(' ')).toContain('NOT been executed');
expect(readiness.open.join(' ')).toContain('Superset');
expect(readiness.open.join(' ')).toContain('AI Analyst');
expect(readiness.proven.length).toBeGreaterThan(0);
});
});
@@ -0,0 +1,377 @@
/**
* tests/analytics/quality-and-freshness.test.ts
* ==============================================
* BI-P025 (data quality provider) and BI-P026 (data freshness).
*
* Both DoDs are about a FALSE GREEN, so both are tested by constructing the
* false green and requiring a failure:
*
* BI-P025 A quality gate that passes when nothing ran. A `not_null` check
* over an EMPTY table finds zero violations — the single most
* common false green in data quality. Both are asserted to FAIL.
*
* BI-P026 UNKNOWN age quietly rendering as current, and a result released
* with no freshness envelope at all. Both are refused.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
DbtQualityProvider,
GreatExpectationsQualityProvider,
NativeQualityProvider,
QUALITY_RULES,
type QualityQueryRunner,
type QualityRuleSpec,
type QualityVerdict,
} from '@/src/analytics/quality/quality-provider';
import { InMemoryQuarantineStore, QualityGate } from '@/src/analytics/quality/quarantine';
import {
assertFreshnessDisclosed,
computeFreshness,
FRESHNESS_STATES,
isPresentableAsCurrent,
NON_CURRENT_STATES,
} from '@/src/analytics/quality/freshness';
function runner(
violations: number,
evaluated: number,
): QualityQueryRunner & { lastExpression?: string; lastParams?: Record<string, string> } {
const r: QualityQueryRunner & { lastExpression?: string; lastParams?: Record<string, string> } = {
engine: 'clickhouse',
async count(args) {
r.lastExpression = args.violationExpression;
r.lastParams = args.params;
return { violations, evaluated };
},
};
return r;
}
const RULE: QualityRuleSpec = {
rule_id: 'q_not_null_customer',
tenant_id: 't_alpha',
dataset_id: 'ds_sales',
rule: 'not_null',
field: 'customer',
severity: 'block',
params: {},
};
describe('BI-P025 — the native provider EXECUTES, and says so', () => {
it('declares every rule BI-P025 names', () => {
expect([...QUALITY_RULES]).toEqual([
'not_null',
'unique',
'range',
'referential',
'freshness',
'schema',
'distribution',
'custom',
]);
});
it('passes a clean dataset', async () => {
const verdict = await new NativeQualityProvider(runner(0, 1000)).evaluate(RULE);
expect(verdict.passed).toBe(true);
expect(verdict.provider_kind).toBe('executing');
});
it('FAILS an empty dataset instead of reporting zero violations', async () => {
// The false green this whole file exists for: a not-null check over zero
// rows finds zero violations and looks healthy while the pipeline is dead.
const verdict = await new NativeQualityProvider(runner(0, 0)).evaluate(RULE);
expect(verdict.passed).toBe(false);
expect(verdict.detail).toContain('EMPTY');
});
it('fails a dataset with violations', async () => {
const verdict = await new NativeQualityProvider(runner(7, 1000)).evaluate(RULE);
expect(verdict.passed).toBe(false);
expect(verdict.violation_count).toBe(7);
});
it('binds rule parameters instead of splicing them into the expression', async () => {
const r = runner(0, 10);
await new NativeQualityProvider(r).evaluate({
...RULE,
rule: 'distribution',
field: 'channel',
params: { accepted_values: ['web', "retail'; DROP TABLE x; --"] },
});
expect(r.lastExpression).not.toContain('DROP');
expect(Object.values(r.lastParams ?? {})).toContain("retail'; DROP TABLE x; --");
});
it('refuses a field name that is not an identifier', async () => {
const p = new NativeQualityProvider(runner(0, 10));
await expect(p.evaluate({ ...RULE, field: 'customer; DROP TABLE x' })).rejects.toBeInstanceOf(SiaxError);
});
it('refuses an incomplete rule rather than evaluating a meaningless one', async () => {
const p = new NativeQualityProvider(runner(0, 10));
await expect(p.evaluate({ ...RULE, rule: 'range', params: {} })).rejects.toBeInstanceOf(SiaxError);
await expect(p.evaluate({ ...RULE, rule: 'freshness', params: {} })).rejects.toBeInstanceOf(SiaxError);
await expect(p.evaluate({ ...RULE, rule: 'distribution', params: {} })).rejects.toBeInstanceOf(SiaxError);
await expect(p.evaluate({ ...RULE, rule: 'custom', params: {} })).rejects.toBeInstanceOf(SiaxError);
});
it('says CAPABILITY_UNAVAILABLE for rules it cannot evaluate, rather than passing them', async () => {
const p = new NativeQualityProvider(runner(0, 10));
for (const rule of ['schema', 'referential'] as const) {
await expect(p.evaluate({ ...RULE, rule })).rejects.toBeInstanceOf(SiaxError);
expect(p.supports(rule)).toBe(false);
}
});
});
describe('BI-P025 — the ingesting providers do not pretend to execute', () => {
it('dbt and GE declare themselves as ingesting', async () => {
expect(new DbtQualityProvider(new Map()).providerKind).toBe('ingesting');
expect(new GreatExpectationsQualityProvider(new Map()).providerKind).toBe('ingesting');
});
it('a MISSING dbt result is a failure, not a pass', async () => {
// Treating "no result" as "passed" is how a gate stops gating the moment
// the test stops running.
const verdict = await new DbtQualityProvider(new Map()).evaluate(RULE);
expect(verdict.passed).toBe(false);
expect(verdict.detail).toContain('no dbt result');
});
it.each(['error', 'warn', 'skipped'] as const)('dbt status %s is NOT a pass', async (status) => {
const results = new Map([[RULE.rule_id, { unique_id: 't1', status, failures: 0 }]]);
const verdict = await new DbtQualityProvider(results).evaluate(RULE);
expect(verdict.passed).toBe(false);
});
it('dbt pass is a pass', async () => {
const results = new Map([[RULE.rule_id, { unique_id: 't1', status: 'pass' as const, failures: 0 }]]);
expect((await new DbtQualityProvider(results).evaluate(RULE)).passed).toBe(true);
});
it('a missing GE suite is a failure', async () => {
expect((await new GreatExpectationsQualityProvider(new Map()).evaluate(RULE)).passed).toBe(false);
});
it("a GE suite's unexpected counts are carried through", async () => {
const suites = new Map([
[
RULE.rule_id,
{
expectation_suite_name: 'sales_suite',
success: false,
results: [
{
expectation_config: { expectation_type: 'expect_column_values_to_not_be_null' },
success: false,
result: { unexpected_count: 12, element_count: 1000 },
},
],
},
],
]);
const verdict = await new GreatExpectationsQualityProvider(suites).evaluate(RULE);
expect(verdict.passed).toBe(false);
expect(verdict.violation_count).toBe(12);
expect(verdict.evaluated_rows).toBe(1000);
});
});
describe('BI-P025 DoD — a failed critical gate QUARANTINES the serving projection', () => {
function verdict(overrides: Partial<QualityVerdict> = {}): QualityVerdict {
return {
rule_id: 'q1',
dataset_id: 'ds_sales',
tenant_id: 't_alpha',
rule: 'not_null',
severity: 'block',
passed: true,
violation_count: 0,
evaluated_rows: 100,
produced_by: 'native:clickhouse',
provider_kind: 'executing',
evaluated_at: new Date().toISOString(),
...overrides,
};
}
it('a blocking failure quarantines, and the READ is then REFUSED', async () => {
const gate = new QualityGate(new InMemoryQuarantineStore());
// Before: readable.
await expect(gate.assertProjectionReadable('t_alpha', 'ds_sales')).resolves.toBeUndefined();
const outcome = await gate.apply('t_alpha', 'ds_sales', [verdict({ passed: false, severity: 'block' })]);
expect(outcome.quarantined).toBe(true);
expect(outcome.passed).toBe(false);
// After: refused. Not annotated — refused.
await expect(gate.assertProjectionReadable('t_alpha', 'ds_sales')).rejects.toBeInstanceOf(SiaxError);
});
it('a WARN failure does not quarantine, but is surfaced', async () => {
const gate = new QualityGate(new InMemoryQuarantineStore());
const outcome = await gate.apply('t_alpha', 'ds_sales', [verdict({ passed: false, severity: 'warn' })]);
expect(outcome.quarantined).toBe(false);
expect(outcome.warnings).toHaveLength(1);
await expect(gate.assertProjectionReadable('t_alpha', 'ds_sales')).resolves.toBeUndefined();
});
it("a gate over ZERO verdicts QUARANTINES — 'no rules ran' is not 'everything passed'", async () => {
// The same shape as l0re's silently-skipped tests and api0's
// `trivy --exit-code 0`: a check that produced nothing reporting green.
const gate = new QualityGate(new InMemoryQuarantineStore());
const outcome = await gate.apply('t_alpha', 'ds_sales', []);
expect(outcome.passed).toBe(false);
expect(outcome.quarantined).toBe(true);
await expect(gate.assertProjectionReadable('t_alpha', 'ds_sales')).rejects.toBeInstanceOf(SiaxError);
});
it('a later passing run does NOT auto-release a quarantine', async () => {
const gate = new QualityGate(new InMemoryQuarantineStore());
await gate.apply('t_alpha', 'ds_sales', [verdict({ passed: false })]);
await gate.apply('t_alpha', 'ds_sales', [verdict({ passed: true })]);
// A flapping rule would otherwise quarantine and un-quarantine the dataset
// between two reads of the same dashboard.
await expect(gate.assertProjectionReadable('t_alpha', 'ds_sales')).rejects.toBeInstanceOf(SiaxError);
});
it('release requires a principal and a reason', async () => {
const gate = new QualityGate(new InMemoryQuarantineStore());
await gate.apply('t_alpha', 'ds_sales', [verdict({ passed: false })]);
await expect(gate.release('t_alpha', 'ds_sales', '', 'x')).rejects.toBeInstanceOf(SiaxError);
await expect(gate.release('t_alpha', 'ds_sales', 'u_1', ' ')).rejects.toBeInstanceOf(SiaxError);
const released = await gate.release('t_alpha', 'ds_sales', 'u_1', 'upstream backfilled');
expect(released.released_by).toBe('u_1');
await expect(gate.assertProjectionReadable('t_alpha', 'ds_sales')).resolves.toBeUndefined();
});
it("quarantine is tenant-scoped: one tenant's failure does not block another", async () => {
const gate = new QualityGate(new InMemoryQuarantineStore());
await gate.apply('t_alpha', 'ds_sales', [verdict({ passed: false })]);
await expect(gate.assertProjectionReadable('t_beta', 'ds_sales')).resolves.toBeUndefined();
});
it('refuses a verdict belonging to another tenant or dataset', async () => {
const gate = new QualityGate(new InMemoryQuarantineStore());
await expect(
gate.apply('t_alpha', 'ds_sales', [verdict({ tenant_id: 't_beta' })]),
).rejects.toBeInstanceOf(SiaxError);
await expect(
gate.apply('t_alpha', 'ds_sales', [verdict({ dataset_id: 'ds_other' })]),
).rejects.toBeInstanceOf(SiaxError);
});
});
describe('BI-P026 — five states, and UNKNOWN is not FRESH', () => {
const HOUR = 3_600_000;
const NOW = Date.parse('2026-09-07T12:00:00Z');
const policy = { expectedIntervalMs: HOUR };
it('declares the five states BI-P026 names', () => {
expect([...FRESHNESS_STATES]).toEqual(['FRESH', 'DELAYED', 'STALE', 'FAILED', 'UNKNOWN']);
});
it('only FRESH may be presented as current', () => {
expect(isPresentableAsCurrent('FRESH')).toBe(true);
for (const s of NON_CURRENT_STATES) expect(isPresentableAsCurrent(s)).toBe(false);
expect(NON_CURRENT_STATES).toContain('UNKNOWN');
});
const cases: Array<[string, Parameters<typeof computeFreshness>[0], string]> = [
[
'recent load',
{ lastSuccessfulLoadAt: '2026-09-07T11:50:00Z', lastRunStatus: 'succeeded', policy, now: NOW },
'FRESH',
],
[
'behind schedule',
{ lastSuccessfulLoadAt: '2026-09-07T09:50:00Z', lastRunStatus: 'succeeded', policy, now: NOW },
'DELAYED',
],
[
'well past the threshold',
{ lastSuccessfulLoadAt: '2026-09-06T12:00:00Z', lastRunStatus: 'succeeded', policy, now: NOW },
'STALE',
],
[
'the last run FAILED, even though the data looks recent',
{ lastSuccessfulLoadAt: '2026-09-07T11:59:00Z', lastRunStatus: 'failed', policy, now: NOW },
'FAILED',
],
['never run', { lastRunStatus: 'never_run', policy, now: NOW }, 'UNKNOWN'],
['no load timestamp at all', { policy, now: NOW }, 'UNKNOWN'],
['an unparseable timestamp', { lastSuccessfulLoadAt: 'not a date', policy, now: NOW }, 'UNKNOWN'],
];
it.each(cases)('%s -> %s', (_label, input, expected) => {
expect(computeFreshness(input).state).toBe(expected);
});
it('FAILED outranks a recent timestamp — a broken pipeline must not look FRESH', () => {
const env = computeFreshness({
lastSuccessfulLoadAt: '2026-09-07T11:59:59Z',
lastRunStatus: 'failed',
policy,
now: NOW,
});
expect(env.state).toBe('FAILED');
expect(env.disclosure).toContain('FAILED');
});
it('every state carries a disclosure a UI can render verbatim', () => {
for (const [, input] of cases) {
const env = computeFreshness(input);
expect(env.disclosure.length).toBeGreaterThan(10);
}
});
});
describe('BI-P026 DoD — stale data is never SILENTLY presented as current', () => {
const env = computeFreshness({
lastSuccessfulLoadAt: '2026-09-01T00:00:00Z',
lastRunStatus: 'succeeded',
policy: { expectedIntervalMs: 3_600_000 },
now: Date.parse('2026-09-07T12:00:00Z'),
});
it('refuses to release a result with NO freshness envelope', () => {
// Not defaulted to FRESH, not defaulted to UNKNOWN: unreleasable. "We
// forgot to attach it" and "the data is current" are indistinguishable to
// a reader, so a default would make forgetting the silent path.
expect(() => assertFreshnessDisclosed({}, 'dashboard panel p1')).toThrowError(SiaxError);
});
it('refuses to release STALE data that the consumer has not acknowledged', () => {
expect(env.state).toBe('STALE');
let thrown: unknown;
try {
assertFreshnessDisclosed({ freshness: env }, 'dashboard panel p1');
} catch (e) {
thrown = e;
}
expect(thrown).toBeInstanceOf(SiaxError);
expect((thrown as SiaxError).message).toContain('STALE');
});
it('releases STALE data once the consumer has acknowledged it', () => {
expect(assertFreshnessDisclosed({ freshness: env, acknowledged_non_current: true }, 'p1').state).toBe(
'STALE',
);
});
it.each(NON_CURRENT_STATES)('refuses an unacknowledged %s result', (state) => {
expect(() => assertFreshnessDisclosed({ freshness: { ...env, state } }, 'p1')).toThrowError(SiaxError);
});
it('releases FRESH data without ceremony', () => {
expect(assertFreshnessDisclosed({ freshness: { ...env, state: 'FRESH' } }, 'p1').state).toBe('FRESH');
});
it('refuses an envelope carrying a state that is not one of the five', () => {
expect(() =>
assertFreshnessDisclosed({ freshness: { ...env, state: 'PROBABLY_FINE' as never } }, 'p1'),
).toThrowError(SiaxError);
});
});
+291
View File
@@ -0,0 +1,291 @@
/**
* tests/analytics/query-cache.test.ts
* ====================================
* BI-P020 — QUERY CACHE.
*
* DoD: "Invalidation tests prove changed dataset/metric does not serve stale
* unauthorized result."
*
* Two words in that sentence carry the weight — STALE and UNAUTHORIZED — and
* they are different failures, so they are tested separately:
*
* STALE a component of the key changed (metric version, semantic
* model version, data snapshot) and the cache still answered.
* Tested by changing each of the six components ONE AT A TIME
* and requiring a miss for every one; a table-driven loop, so
* adding a component to the key without adding it to the loop
* is caught by the count assertion.
*
* UNAUTHORIZED another tenant's result came back. Tested three ways: a
* different tenant misses; a poisoned entry stored under this
* tenant's key but carrying another tenant's id is REFUSED and
* evicted rather than returned; and the same components under
* two tenants produce different keys.
*
* The poisoning test is the one that matters. Key namespacing is a naming
* convention, and a naming convention is what ST0RE was relying on when it
* turned out to have four cross-tenant paths rather than the one reported.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
buildCacheKey,
InMemoryResultCache,
tenantKeyPrefix,
ValkeyResultCache,
type CacheKeyComponents,
type CachedResult,
type ValkeyLikeClient,
} from '@/src/analytics/cache/query-cache';
const BASE: CacheKeyComponents = {
tenant_id: 't_alpha',
project_id: 'p_main',
dataset_id: 'ds_sales',
semantic_model_version: 7,
metric_versions: { m_revenue: 3, m_orders: 1 },
compiled_query_hash: 'a'.repeat(64),
data_snapshot: 'dsv_42',
format: 'json',
};
describe('BI-P020 — the key requires all six components', () => {
const omissions: Array<[string, Partial<CacheKeyComponents>]> = [
['tenant_id', { tenant_id: '' }],
['dataset_id', { dataset_id: '' }],
['semantic_model_version', { semantic_model_version: undefined as unknown as number }],
['metric_versions', { metric_versions: {} }],
['compiled_query_hash', { compiled_query_hash: '' }],
['data_snapshot', { data_snapshot: '' }],
['format', { format: '' }],
];
it.each(omissions)('refuses to build a key without %s', (_name, override) => {
expect(() => buildCacheKey({ ...BASE, ...override })).toThrowError(SiaxError);
});
it('refuses a metric whose version is missing', () => {
expect(() =>
buildCacheKey({ ...BASE, metric_versions: { m_revenue: undefined as unknown as number } }),
).toThrowError(SiaxError);
});
it('is stable under key ordering — the same query does not fragment the cache', () => {
const a = buildCacheKey({ ...BASE, metric_versions: { m_orders: 1, m_revenue: 3 } });
const b = buildCacheKey({ ...BASE, metric_versions: { m_revenue: 3, m_orders: 1 } });
expect(a).toBe(b);
});
it('carries the tenant in plaintext so invalidation is a prefix scan', () => {
expect(buildCacheKey(BASE).startsWith(tenantKeyPrefix('t_alpha'))).toBe(true);
});
it('refuses a tenant id that is not key-safe', () => {
for (const bad of ['t alpha', 't:alpha', 't*', '../t_beta']) {
expect(() => buildCacheKey({ ...BASE, tenant_id: bad })).toThrowError(SiaxError);
}
});
});
describe('BI-P020 — a changed component never serves a STALE result', () => {
/**
* Each entry changes ONE component. Every one must miss. The count is
* asserted so that adding a component to `CacheKeyComponents` without adding
* it here is caught rather than silently untested.
*/
const mutations: Array<[string, Partial<CacheKeyComponents>]> = [
['semantic model version bumped', { semantic_model_version: 8 }],
['a metric definition versioned', { metric_versions: { m_revenue: 4, m_orders: 1 } }],
['a metric removed from the query', { metric_versions: { m_revenue: 3 } }],
['the data snapshot advanced', { data_snapshot: 'dsv_43' }],
['the compiled query changed (different filters)', { compiled_query_hash: 'b'.repeat(64) }],
['a different dataset', { dataset_id: 'ds_other' }],
['a different result format', { format: 'arrow_ipc' }],
['a different project', { project_id: 'p_other' }],
['a different tenant', { tenant_id: 't_beta' }],
];
it('covers every component of the key', () => {
const covered = new Set(mutations.flatMap(([, m]) => Object.keys(m)));
const componentKeys = Object.keys(BASE);
expect([...covered].sort()).toEqual([...componentKeys].sort());
});
it.each(mutations)('misses after %s', async (_label, override) => {
const cache = new InMemoryResultCache();
await cache.set(BASE, { rows: [{ value: 100 }] }, { ttlSeconds: 300, rowCount: 1 });
expect(await cache.get(BASE)).toBeDefined();
const changed = { ...BASE, ...override };
expect(await cache.get(changed), 'a changed component served the old result').toBeUndefined();
});
it('expires an entry rather than serving it past its TTL', async () => {
let clock = 1_000_000;
const cache = new InMemoryResultCache(() => clock);
await cache.set(BASE, { rows: [] }, { ttlSeconds: 10, rowCount: 0 });
expect(await cache.get(BASE)).toBeDefined();
clock += 11_000;
expect(await cache.get(BASE)).toBeUndefined();
});
it('refuses a non-positive TTL rather than caching forever', async () => {
const cache = new InMemoryResultCache();
for (const ttl of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
await expect(cache.set(BASE, {}, { ttlSeconds: ttl, rowCount: 0 })).rejects.toBeInstanceOf(SiaxError);
}
});
});
describe('BI-P020 — invalidation', () => {
async function seed() {
const cache = new InMemoryResultCache();
await cache.set(BASE, { v: 1 }, { ttlSeconds: 300, rowCount: 1 });
await cache.set(
{ ...BASE, compiled_query_hash: 'c'.repeat(64) },
{ v: 2 },
{ ttlSeconds: 300, rowCount: 1 },
);
await cache.set(
{ ...BASE, dataset_id: 'ds_other', metric_versions: { m_other: 1 } },
{ v: 3 },
{ ttlSeconds: 300, rowCount: 1 },
);
await cache.set({ ...BASE, tenant_id: 't_beta' }, { v: 4 }, { ttlSeconds: 300, rowCount: 1 });
return cache;
}
it("invalidateDataset drops that dataset's entries and nothing else", async () => {
const cache = await seed();
const dropped = await cache.invalidateDataset('t_alpha', 'ds_sales');
expect(dropped).toBe(2);
expect(await cache.get(BASE)).toBeUndefined();
expect(
await cache.get({ ...BASE, dataset_id: 'ds_other', metric_versions: { m_other: 1 } }),
).toBeDefined();
// The other tenant is untouched — invalidation is tenant-scoped too.
expect(await cache.get({ ...BASE, tenant_id: 't_beta' })).toBeDefined();
});
it('invalidateMetric drops every entry that used the metric', async () => {
const cache = await seed();
const dropped = await cache.invalidateMetric('t_alpha', 'm_revenue');
expect(dropped).toBe(2);
expect(await cache.get(BASE)).toBeUndefined();
expect(
await cache.get({ ...BASE, dataset_id: 'ds_other', metric_versions: { m_other: 1 } }),
).toBeDefined();
});
it('invalidateTenant drops only that tenant', async () => {
const cache = await seed();
const dropped = await cache.invalidateTenant('t_alpha');
expect(dropped).toBe(3);
expect(await cache.get({ ...BASE, tenant_id: 't_beta' })).toBeDefined();
});
});
describe('BI-P020 — never share a tenant result cache', () => {
it('two tenants asking the identical question get different keys', () => {
expect(buildCacheKey(BASE)).not.toBe(buildCacheKey({ ...BASE, tenant_id: 't_beta' }));
});
it("REFUSES and evicts an entry whose recorded tenant is not the caller's", async () => {
// The scenario key namespacing alone does not cover: a poisoned or
// mis-migrated entry sitting under the right key with the wrong owner.
// Returning `undefined` here would hide a security event; this refuses.
const client = new FakeValkey();
const cache = new ValkeyResultCache(client);
await cache.set(BASE, { secret: 'alpha data' }, { ttlSeconds: 300, rowCount: 1 });
const key = buildCacheKey(BASE);
const poisoned = JSON.parse(client.data.get(key) as string) as CachedResult;
poisoned.tenant_id = 't_beta';
poisoned.value = { secret: 'BETA DATA' };
client.data.set(key, JSON.stringify(poisoned));
await expect(cache.get(BASE)).rejects.toBeInstanceOf(SiaxError);
// ...and the poisoned entry is gone, so the next read is a clean miss
// rather than a repeated alarm nobody can clear.
expect(client.data.has(key)).toBe(false);
expect(await cache.get(BASE)).toBeUndefined();
});
it('a tenant-scoped scan confirms ownership against the entry, not the glob', async () => {
const client = new FakeValkey();
const cache = new ValkeyResultCache(client);
await cache.set(BASE, { v: 1 }, { ttlSeconds: 300, rowCount: 1 });
// An entry whose KEY matches t_alpha's prefix but whose owner is t_beta.
// SCAN MATCH is a glob; the glob would include it, the ownership check
// must not.
client.data.set(
`${tenantKeyPrefix('t_alpha')}forged`,
JSON.stringify({ ...JSON.parse(client.data.get(buildCacheKey(BASE)) as string), tenant_id: 't_beta' }),
);
const dropped = await cache.invalidateTenant('t_alpha');
expect(dropped).toBe(1);
});
});
describe('BI-P020 — the Valkey adapter', () => {
it('sets a store-side TTL, not only a recorded timestamp', async () => {
const client = new FakeValkey();
const cache = new ValkeyResultCache(client);
await cache.set(BASE, { v: 1 }, { ttlSeconds: 42, rowCount: 1 });
expect(client.ttls.get(buildCacheKey(BASE))).toBe(42);
});
it('treats a corrupt entry as a miss AND removes it', async () => {
const client = new FakeValkey();
const cache = new ValkeyResultCache(client);
client.data.set(buildCacheKey(BASE), '{not json');
expect(await cache.get(BASE)).toBeUndefined();
expect(client.data.has(buildCacheKey(BASE))).toBe(false);
});
it('pages through SCAN rather than blocking on KEYS', async () => {
const client = new FakeValkey();
const cache = new ValkeyResultCache(client);
for (let i = 0; i < 1200; i += 1) {
await cache.set(
{ ...BASE, compiled_query_hash: String(i).padStart(64, '0') },
{ i },
{ ttlSeconds: 300, rowCount: 1 },
);
}
expect(await cache.invalidateTenant('t_alpha')).toBe(1200);
expect(client.scanCalls).toBeGreaterThan(1);
});
});
class FakeValkey implements ValkeyLikeClient {
readonly data = new Map<string, string>();
readonly ttls = new Map<string, number>();
scanCalls = 0;
async get(key: string): Promise<string | null> {
return this.data.get(key) ?? null;
}
async set(key: string, value: string, opts: { EX: number }): Promise<unknown> {
this.data.set(key, value);
this.ttls.set(key, opts.EX);
return 'OK';
}
async del(keys: string[]): Promise<unknown> {
for (const k of keys) {
this.data.delete(k);
this.ttls.delete(k);
}
return keys.length;
}
async scan(
cursor: string,
opts: { MATCH: string; COUNT: number },
): Promise<{ cursor: string; keys: string[] }> {
this.scanCalls += 1;
const prefix = opts.MATCH.replace(/\*$/, '');
const all = [...this.data.keys()].filter((k) => k.startsWith(prefix));
const start = Number(cursor);
const page = all.slice(start, start + opts.COUNT);
const next = start + opts.COUNT >= all.length ? '0' : String(start + opts.COUNT);
return { cursor: next, keys: page };
}
}
@@ -0,0 +1,226 @@
/**
* BI-P011's adversarial list, at the compiler layer:
*
* tenant A query B dataset · tenant A forged dataset ID · raw SQL attempt
* SQL injection · dimension identifier injection · filter injection
*
* These are the cases that never reach the network. The cases that DO reach a
* real server — and the with-fix/without-fix proof BI-P011 actually demands —
* are tests/integration/analytics-tenant-isolation.integration.test.ts.
*/
import { describe, it, expect } from 'vitest';
import {
assertSafeIdentifier,
compileMetricQuery,
compileProjectionQuery,
dimensionCatalogFrom,
restrictedTenantUserDdl,
} from '@/src/analytics/engine/query-compiler';
const catalog = dimensionCatalogFrom({ severity: 'severity', make: 'vehicle_make' });
const HOSTILE = [
"x'; DROP TABLE opt_analytics_event; --",
'1 OR 1=1',
'tenant_id',
'*/ OR 1=1 /*',
'severity UNION ALL SELECT tenant_id FROM opt_analytics_event',
'dim_values[1]',
'__proto__',
'constructor',
'sever ity',
'sévérité',
'a'.repeat(200),
'',
];
describe('BI-P011 injection surfaces at the compiler', () => {
it('dimension identifier injection: hostile group_by names are refused, not escaped', () => {
for (const bad of HOSTILE) {
expect(
() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', group_by: [bad] },
'opt_analytics',
catalog,
1000,
),
`group_by "${bad}" was not refused`,
).toThrowError(/unknown group_by dimension/);
}
});
it('filter injection: hostile filter KEYS are refused by catalog resolution', () => {
for (const bad of HOSTILE) {
expect(
() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', filters: { [bad]: 'v' } },
'opt_analytics',
catalog,
1000,
),
`filter key "${bad}" was not refused`,
).toThrowError(/unknown filter dimension/);
}
});
it('prototype-chain keys resolve to undefined rather than to Object.prototype members', () => {
// A naive `catalog[name]` lookup would resolve "constructor" to a
// function and "toString" to a method; the Map-based catalog must not.
for (const key of ['constructor', 'toString', 'hasOwnProperty', '__proto__', 'valueOf']) {
expect(catalog.resolve(key)).toBeUndefined();
}
});
it('filter VALUES are never spliced, however hostile', () => {
const compiled = compileMetricQuery(
{
tenant_id: 't_alpha',
metric: 'm',
aggregate: 'sum',
filters: { make: "volvo'; DROP TABLE opt_analytics_event; --" },
},
'opt_analytics',
catalog,
1000,
);
expect(compiled.sql).not.toContain('DROP TABLE');
expect(compiled.sql).not.toContain('volvo');
expect(compiled.params.param_f0v).toBe("volvo'; DROP TABLE opt_analytics_event; --");
// The physical column name came from the catalog, not the caller.
expect(compiled.params.param_f0n).toBe('vehicle_make');
});
it('metric and dataset VALUES are never spliced either', () => {
const compiled = compileMetricQuery(
{
tenant_id: 't_alpha',
metric: "m'; SELECT 1; --",
dataset_id: "ds'; SELECT 1; --",
aggregate: 'sum',
},
'opt_analytics',
catalog,
1000,
);
expect(compiled.sql).not.toContain('SELECT 1');
expect(compiled.sql.match(/SELECT/g)).toHaveLength(1);
});
it('raw SQL attempt: there is no request shape that reaches a second table', () => {
const compiled = compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum' },
'opt_analytics',
catalog,
1000,
);
expect(compiled.sql).not.toMatch(/\bUNION\b/i);
expect(compiled.sql).not.toMatch(/\bJOIN\b/i);
expect((compiled.sql.match(/\bFROM\b/gi) ?? []).length).toBe(1);
expect(compiled.table).toBe('opt_analytics_event');
});
it('a forged table name is refused rather than reaching the FROM clause', () => {
expect(() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', table: 'system.tables' as never },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/invalid table identifier/);
});
it('an unsupported aggregate is refused rather than being interpolated', () => {
expect(() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum(1),tenant_id' as never },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/unsupported aggregate/);
});
it('group-by cardinality is capped so a caller cannot explode the GROUP BY', () => {
const many = Array.from({ length: 9 }, () => 'severity');
expect(() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', group_by: many },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/at most 8 group-by/);
});
it('LIMIT is clamped to the governance ceiling, and never below 1', () => {
const big = compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', limit: 10_000_000 },
'opt_analytics',
catalog,
500,
);
expect(big.sql).toContain('LIMIT 500');
const zero = compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', limit: 0 },
'opt_analytics',
catalog,
500,
);
expect(zero.sql).toContain('LIMIT 1');
});
it('the projection compiler forces the tenant and parameterizes entity keys', () => {
const compiled = compileProjectionQuery(
{ tenant_id: 't_alpha', dataset_id: 'ds_x', entity_keys: ["a'; DROP", 'b'] },
'opt_analytics',
100,
);
expect(compiled.sql).toMatch(/WHERE tenant_id = \{tenant:String\}/);
expect(compiled.sql).not.toContain('DROP');
expect(compiled.params.param_entityKeys).toBe(JSON.stringify(["a'; DROP", 'b']));
});
it('assertSafeIdentifier accepts real identifiers and rejects everything else', () => {
for (const good of ['severity', 'vehicle_make', '_x', 'a1_b2']) {
expect(assertSafeIdentifier(good, 'test')).toBe(good);
}
for (const bad of ['1abc', 'a-b', 'a b', 'a;b', '', 'a'.repeat(64)]) {
expect(() => assertSafeIdentifier(bad, 'test')).toThrowError(/invalid test identifier/);
}
});
it('restrictedTenantUserDdl refuses a tenant id or password it cannot safely embed', () => {
expect(() =>
restrictedTenantUserDdl({
db: 'opt_analytics',
tenantId: "t_alpha' OR '1'='1",
userName: 'opt_t_alpha',
password: 'pw',
tables: ['opt_analytics_event'],
}),
).toThrowError(/not policy-safe/);
expect(() =>
restrictedTenantUserDdl({
db: 'opt_analytics',
tenantId: 't_alpha',
userName: 'opt_t_alpha',
password: "pw' OR '1'='1",
tables: ['opt_analytics_event'],
}),
).toThrowError(/cannot be embedded/);
const stmts = restrictedTenantUserDdl({
db: 'opt_analytics',
tenantId: 't_alpha',
userName: 'opt_t_alpha',
password: 'safe_pw_123',
tables: ['opt_analytics_event'],
});
expect(stmts.join(' ')).toContain('CREATE ROW POLICY IF NOT EXISTS');
expect(stmts.join(' ')).toContain("USING tenant_id = 't_alpha'");
});
});
@@ -0,0 +1,404 @@
/**
* tests/analytics/query-execution-model.test.ts
* ==============================================
* BI-P018 (execution model), BI-P019 (cancellation logic) and BI-P021
* (cost/budget) — the parts provable without an engine.
*
* The engine-dependent claims — "cancellation actually stops a running query",
* "the budget actually stops a running query" — are NOT asserted here. They
* live in tests/integration/query-cancellation-budget.integration.test.ts
* against a live ClickHouse, because a fake process-control that returns
* `isRunning: false` on the second call would make this file pass while
* proving nothing about the server.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
assertLegalTransition,
assertNoRawSql,
compiledQueryHash,
QueryExecutionRecorder,
TERMINAL_STATES,
type QueryExecutionRecord,
} from '@/src/analytics/execution/query-execution-record';
import { cancelAndVerify, type EngineProcessControl } from '@/src/analytics/execution/cancellation';
import {
costUnits,
DEFAULT_QUERY_BUDGET,
InMemoryWindowStore,
QueryBudgetEnforcer,
} from '@/src/analytics/cost/query-budget';
// ── BI-P018 ────────────────────────────────────────────────────────────────
function recorder(sink: { write: (r: QueryExecutionRecord) => void }, now = () => 1_000_000) {
return new QueryExecutionRecorder(
{
tenant_id: 't_alpha',
project_id: 'p_main',
principal_id: 'u_1',
workload: 'dashboard',
engine: 'clickhouse',
correlation_id: 'c_1',
sink,
now,
},
'opt_q1',
{
hash: compiledQueryHash('SELECT 1', { param_tenant: 't_alpha' }),
datasets: ['ds_sales'],
metrics: ['revenue'],
},
);
}
describe('BI-P018 — every field the prompt names, and none it forbids', () => {
it('carries all eighteen required fields once settled', async () => {
const written: QueryExecutionRecord[] = [];
let clock = 1_000_000;
const r = recorder({ write: (x) => void written.push(x) }, () => clock);
await r.submitted();
clock += 50;
await r.started();
clock += 700;
const final = await r.finish('succeeded', {
rows: 12,
rows_scanned: 40_960,
bytes_scanned: 1_234_567,
cost_units: 0.5,
});
for (const field of [
'query_id',
'tenant_id',
'project_id',
'principal_id',
'workload',
'submitted_at',
'started_at',
'completed_at',
'engine',
'compiled_query_hash',
'datasets',
'metrics',
'status',
'rows',
'rows_scanned',
'bytes_scanned',
'duration_ms',
'cache_status',
'cost_units',
]) {
expect(final[field as keyof QueryExecutionRecord], `missing ${field}`).toBeDefined();
}
expect(final.duration_ms).toBe(700);
expect(final.status).toBe('succeeded');
});
it('writes at EVERY transition, so an execution that never finishes is still visible', async () => {
const written: QueryExecutionRecord[] = [];
const r = recorder({ write: (x) => void written.push(x) });
await r.submitted();
await r.started();
expect(written.map((w) => w.status)).toEqual(['queued', 'running']);
// A recorder that only wrote at the end would have zero rows here — and
// would lose precisely the executions worth investigating.
});
it('stores a hash, never the statement', async () => {
const written: QueryExecutionRecord[] = [];
const r = recorder({ write: (x) => void written.push(x) });
await r.submitted();
await r.started();
const final = await r.finish('succeeded', { rows: 1 });
const serialized = JSON.stringify(final);
expect(serialized).not.toMatch(/SELECT/i);
expect(final.compiled_query_hash).toMatch(/^[0-9a-f]{64}$/);
});
it('REFUSES to emit a record whose error field carries statement text', () => {
const record: QueryExecutionRecord = {
query_id: 'q',
execution_id: 'e',
tenant_id: 't_alpha',
principal_id: 'u',
workload: 'api',
submitted_at: new Date().toISOString(),
engine: 'clickhouse',
compiled_query_hash: 'a'.repeat(64),
datasets: [],
metrics: [],
status: 'failed',
cache_status: 'miss',
// The realistic leak: ClickHouse's error text echoes the query.
error: 'Code: 47. Unknown identifier in scope SELECT tenant_id FROM opt_analytics.sales',
};
expect(() => assertNoRawSql(record)).toThrowError(SiaxError);
});
it('hashes the same statement with different parameters differently', () => {
const a = compiledQueryHash('SELECT 1 WHERE t = {t:String}', { param_t: 't_alpha' });
const b = compiledQueryHash('SELECT 1 WHERE t = {t:String}', { param_t: 't_beta' });
expect(a).not.toBe(b);
// ...and identically regardless of key order.
expect(compiledQueryHash('q', { b: '2', a: '1' })).toBe(compiledQueryHash('q', { a: '1', b: '2' }));
});
it('refuses an illegal state transition rather than overwriting a terminal row', () => {
for (const terminal of TERMINAL_STATES) {
expect(() => assertLegalTransition(terminal, 'running')).toThrowError(SiaxError);
}
expect(() => assertLegalTransition('queued', 'succeeded')).toThrowError(SiaxError);
expect(() => assertLegalTransition('running', 'succeeded')).not.toThrow();
});
it('records a cache hit as a cache hit, not as a very fast query', async () => {
const written: QueryExecutionRecord[] = [];
const r = recorder({ write: (x) => void written.push(x) });
await r.submitted();
await r.servedFromCache(42);
const final = written.at(-1) as QueryExecutionRecord;
expect(final.cache_status).toBe('hit');
expect(final.rows_scanned).toBe(0);
expect(final.bytes_scanned).toBe(0);
});
it('requires a verified tenant and principal', () => {
for (const bad of [{ tenant_id: '' }, { principal_id: '' }]) {
expect(
() =>
new QueryExecutionRecorder(
{
tenant_id: 't_alpha',
principal_id: 'u_1',
workload: 'api',
engine: 'clickhouse',
sink: { write: () => undefined },
...bad,
},
'q',
{ hash: 'h', datasets: [], metrics: [] },
),
).toThrowError(SiaxError);
}
});
});
// ── BI-P019 (logic only; the engine claim is in the integration suite) ─────
describe('BI-P019 — cancellation reports what it VERIFIED, not what it requested', () => {
function control(script: boolean[]): EngineProcessControl & { kills: number } {
let i = 0;
return {
engine: 'test',
kills: 0,
async isRunning() {
const v = script[Math.min(i, script.length - 1)];
i += 1;
return v;
},
async requestKill() {
(this as { kills: number }).kills += 1;
return true;
},
};
}
it('reports verified_stopped only after OBSERVING the query gone', async () => {
// running, running, running, gone
const c = control([true, true, true, false]);
const out = await cancelAndVerify(c, 'q1', { timeoutMs: 5_000, pollIntervalMs: 1 });
expect(out.verified_stopped).toBe(true);
expect(out.kill_accepted).toBe(true);
expect(c.kills).toBe(1);
});
it('reports verified_stopped=false when the query outlives the deadline — it does not claim success', async () => {
const c = control([true]); // never stops
let clock = 0;
const out = await cancelAndVerify(c, 'q1', {
timeoutMs: 100,
pollIntervalMs: 10,
now: () => (clock += 30),
sleep: async () => undefined,
});
expect(out.verified_stopped).toBe(false);
expect(out.already_finished).toBe(false);
});
it('does not claim to have stopped a query that had already finished', async () => {
const c = control([false]);
const out = await cancelAndVerify(c, 'q1', { timeoutMs: 100 });
expect(out.already_finished).toBe(true);
expect(out.verified_stopped).toBe(true);
});
it('keeps polling when the engine is unreachable, then reports unverified', async () => {
let clock = 0;
const flaky: EngineProcessControl = {
engine: 'test',
isRunning: async () => {
throw new Error('engine unreachable');
},
requestKill: async () => true,
};
// isRunning throws on the FIRST call too, which cancelAndVerify treats as
// "assume it was running" — the fail-closed reading.
const out = await cancelAndVerify(flaky, 'q1', {
timeoutMs: 50,
pollIntervalMs: 10,
now: () => (clock += 20),
sleep: async () => undefined,
});
expect(out.verified_stopped).toBe(false);
});
it('aborts the client side as well as the server side', async () => {
let aborted = false;
await cancelAndVerify(control([true, false]), 'q1', {
timeoutMs: 1_000,
pollIntervalMs: 1,
abort: () => {
aborted = true;
},
});
expect(aborted).toBe(true);
});
});
// ── BI-P021 ────────────────────────────────────────────────────────────────
describe('BI-P021 — the budget says plainly what it does and does not bound', () => {
const ledger = {
entries: [] as unknown[],
record(e: unknown) {
this.entries.push(e);
},
};
it('refuses to be constructed as an in-flight enforcer without a process control', () => {
expect(
() =>
new QueryBudgetEnforcer({
budget: DEFAULT_QUERY_BUDGET,
store: new InMemoryWindowStore(),
ledger,
enforceInFlight: true,
}),
).toThrowError(SiaxError);
});
it('declares admission-only mode as advisory, in words', () => {
const e = new QueryBudgetEnforcer({
budget: DEFAULT_QUERY_BUDGET,
store: new InMemoryWindowStore(),
ledger,
enforceInFlight: false,
});
expect(e.describeEnforcement().binding).toBe(false);
expect(e.describeEnforcement().in_flight).toContain('NOT ENFORCED');
});
it('declares the per-process window as non-binding across replicas', () => {
const e = new QueryBudgetEnforcer({
budget: DEFAULT_QUERY_BUDGET,
store: new InMemoryWindowStore(),
ledger,
control: {
engine: 't',
isRunning: async () => false,
requestKill: async () => true,
progress: async () => undefined,
},
enforceInFlight: true,
storeIsShared: false,
});
expect(e.describeEnforcement().across_replicas).toContain('N times this budget');
expect(e.describeEnforcement().binding).toBe(false);
});
it('rejects an estimate that does not fit the remaining window', async () => {
const store = new InMemoryWindowStore();
const e = new QueryBudgetEnforcer({
budget: { ...DEFAULT_QUERY_BUDGET, maxRowsScanned: 1_000 },
store,
ledger,
enforceInFlight: false,
});
expect((await e.admit('t_alpha', { rows_to_read: 100, bytes_to_read: 1 })).admitted).toBe(true);
await store.add('t_alpha', { rows: 999, bytes: 0, units: 0, windowMs: DEFAULT_QUERY_BUDGET.windowMs });
const decision = await e.admit('t_alpha', { rows_to_read: 100, bytes_to_read: 1 });
expect(decision.admitted).toBe(false);
expect(decision.reason).toContain('rows');
});
it('throttles instead of rejecting when the budget says so', async () => {
const store = new InMemoryWindowStore();
const e = new QueryBudgetEnforcer({
budget: { ...DEFAULT_QUERY_BUDGET, maxRowsScanned: 10, onExhausted: 'throttle', throttleDelayMs: 250 },
store,
ledger,
enforceInFlight: false,
});
await store.add('t_alpha', { rows: 100, bytes: 0, units: 0, windowMs: DEFAULT_QUERY_BUDGET.windowMs });
const decision = await e.admit('t_alpha', { rows_to_read: 1, bytes_to_read: 1 });
expect(decision.admitted).toBe(true);
expect(decision.delay_ms).toBe(250);
});
it('charges for the work a cancelled query already did', async () => {
const store = new InMemoryWindowStore();
const entries: Array<{ terminated_by_budget: boolean; cost_units: number }> = [];
const e = new QueryBudgetEnforcer({
budget: DEFAULT_QUERY_BUDGET,
store,
ledger: { record: (x) => void entries.push(x as never) },
enforceInFlight: false,
});
const settled = await e.settle({
tenant_id: 't_alpha',
principal_id: 'u',
query_id: 'q',
cost: { rows_scanned: 1e9, bytes_scanned: 2 ** 30, execution_ms: 1000, engine: 'clickhouse' },
terminated_by_budget: true,
});
expect(settled.cost_units).toBeGreaterThan(0);
expect(entries[0].terminated_by_budget).toBe(true);
// Not charging for it is how a tenant learns the cheapest query is one
// that gets cancelled.
expect(entries[0].cost_units).toBe(settled.cost_units);
});
it('weights bytes above rows, so a wide scan is not billed like a narrow one', () => {
const narrow = costUnits({ rows_scanned: 1e9, bytes_scanned: 1e8, execution_ms: 0, engine: 'e' });
const wide = costUnits({ rows_scanned: 1e8, bytes_scanned: 1e10, execution_ms: 0, engine: 'e' });
expect(wide).toBeGreaterThan(narrow);
});
it('expires spend out of the rolling window', async () => {
let clock = 0;
const store = new InMemoryWindowStore(() => clock);
await store.add('t_alpha', { rows: 100, bytes: 0, units: 1, windowMs: 1000 });
expect((await store.get('t_alpha', 1000)).rows_scanned).toBe(100);
clock += 1500;
expect((await store.get('t_alpha', 1000)).rows_scanned).toBe(0);
});
it('in-flight enforcement returns immediately when the query is already gone', async () => {
const e = new QueryBudgetEnforcer({
budget: { ...DEFAULT_QUERY_BUDGET, maxRowsScanned: 1 },
store: new InMemoryWindowStore(),
ledger,
control: {
engine: 't',
isRunning: async () => false,
requestKill: async () => true,
progress: async () => undefined,
},
enforceInFlight: true,
});
const out = await e.enforceInFlight('t_alpha', 'q');
expect(out.terminated).toBe(false);
expect(out.polls).toBe(1);
});
});
@@ -0,0 +1,554 @@
/**
* tests/analytics/query-request-contract.test.ts
* ==============================================
* BI-P016 — QUERY REQUEST CONTRACT.
*
* Two claims are under test, and both are stated so they can FAIL:
*
* 1. "The default product/application API must NOT accept arbitrary SQL."
* Tested by feeding the parser every field name a caller would reach for
* to smuggle SQL and asserting a rejection — not by asserting the type
* lacks the field, which a compiler already guarantees and a JSON body
* ignores.
*
* 2. "Same request can compile to ClickHouse/semantic engine without
* consumer rewrite." Tested by projecting BOTH compiled artefacts onto a
* comparable shape and demanding equality. The ClickHouse side of that
* projection is obtained by PARSING the emitted SQL and its bound
* parameters here in the test — not by trusting a field the compiler
* helpfully returned. A compiler that silently drops a filter therefore
* fails this test instead of passing it.
*/
import { describe, expect, it } from 'vitest';
import { SiaxError } from '@/src/platform/errors';
import {
ANALYTICS_QUERY_REQUEST_KEYS,
FILTER_OPERATORS,
parseAnalyticsQueryRequest,
queryResolutionFrom,
resolveAnalyticsQuery,
type AnalyticsQueryRequest,
type FilterOperator,
type ResolvedDimension,
type ResolvedMetric,
} from '@/src/analytics/contract/query-request';
import {
compileRequestToClickHouse,
type CompiledAnalyticsQuery,
} from '@/src/analytics/contract/compile-clickhouse';
import {
compileRequestToSemantic,
shapeOfSemanticSpec,
type QueryShape,
} from '@/src/analytics/contract/compile-semantic';
import { FORCED_TENANT_PREDICATE } from '@/src/analytics/engine/query-compiler';
// ── the declared catalog under test ────────────────────────────────────────
const METRICS: ResolvedMetric[] = [
{
name: 'orders',
metric_id: 'm_orders',
event_metric_key: 'order_count',
aggregation: 'count',
allowed_dimensions: ['country', 'channel', 'segment'],
},
{
name: 'revenue',
metric_id: 'm_revenue',
event_metric_key: 'revenue_sek',
aggregation: 'sum',
allowed_dimensions: ['country', 'channel', 'segment'],
unit: 'SEK',
},
{
name: 'restricted',
metric_id: 'm_restricted',
event_metric_key: 'restricted_measure',
aggregation: 'sum',
// Deliberately NOT sliceable by `segment`.
allowed_dimensions: ['country'],
},
];
const DIMENSIONS: ResolvedDimension[] = [
{ name: 'country', dimension_id: 'd_country', field_name: 'country_code' },
{ name: 'channel', dimension_id: 'd_channel', field_name: 'sales_channel' },
{ name: 'segment', dimension_id: 'd_segment', field_name: 'customer_segment' },
];
const resolution = queryResolutionFrom({
dataset_id: 'ds_sales',
metrics: METRICS,
dimensions: DIMENSIONS,
semantic_model_version: 7,
defaultTimeDimension: 'event_time',
});
const FIELD_TO_NAME = new Map(DIMENSIONS.map((d) => [d.field_name, d.name]));
const KEY_TO_METRIC = new Map(METRICS.map((m) => [m.event_metric_key, m.name]));
function compile(req: AnalyticsQueryRequest): CompiledAnalyticsQuery {
return compileRequestToClickHouse(resolveAnalyticsQuery(req, resolution), {
tenant_id: 't_alpha',
project_id: 'p_main',
database: 'opt_analytics',
maxResultRows: 10_000,
});
}
// ── independent parser: SQL text + bound params -> comparable shape ────────
/** Split a WHERE clause on top-level " AND " (parenthesised lists survive). */
function splitConditions(where: string): string[] {
const out: string[] = [];
let depth = 0;
let current = '';
for (let i = 0; i < where.length; i += 1) {
const c = where[i];
if (c === '(') depth += 1;
if (c === ')') depth -= 1;
if (depth === 0 && where.startsWith(' AND ', i)) {
out.push(current);
current = '';
i += 4;
continue;
}
current += c;
}
if (current) out.push(current);
return out;
}
const OP_SYMBOL: Record<string, FilterOperator> = {
'=': 'eq',
'!=': 'ne',
'<': 'lt',
'<=': 'lte',
'>': 'gt',
'>=': 'gte',
};
/**
* Reconstruct the query's meaning from the artefact the engine would actually
* send. Anything the compiler failed to emit is invisible here, which is the
* point.
*/
function shapeOfCompiledSql(c: CompiledAnalyticsQuery): QueryShape {
const p = (key: string): string => {
const v = c.params[`param_${key}`];
if (v === undefined) throw new Error(`compiled SQL references unbound parameter ${key}`);
return v;
};
const whereMatch = /\sWHERE\s(.*?)(?:\sGROUP BY\s|\sORDER BY\s|\sLIMIT\s)/.exec(c.sql);
if (!whereMatch) throw new Error('compiled SQL has no WHERE clause');
const conditions = splitConditions(whereMatch[1]);
const filters: QueryShape['filters'] = [];
let timeFrom: string | undefined;
let timeTo: string | undefined;
for (const cond of conditions) {
if (cond === FORCED_TENANT_PREDICATE) continue;
if (/^project_id = \{project:String\}$/.test(cond)) continue;
if (/^dataset_id = \{dataset:String\}$/.test(cond)) continue;
if (/^metric IN \(/.test(cond)) continue;
let m = /^\w+ >= parseDateTime64BestEffort\(\{fromTime:String\}\)$/.exec(cond);
if (m) {
timeFrom = p('fromTime');
continue;
}
m = /^\w+ < parseDateTime64BestEffort\(\{toTime:String\}\)$/.exec(cond);
if (m) {
timeTo = p('toTime');
continue;
}
m = /^position\(dim_values\[indexOf\(dim_names, \{(fn\d+):String\}\)\], \{(fv\d+):String\}\) > 0$/.exec(
cond,
);
if (m) {
filters.push({ dimension: dimNameFor(p(m[1])), operator: 'contains', values: [p(m[2])] });
continue;
}
m = /^(NOT )?has\(dim_names, \{(fn\d+):String\}\)$/.exec(cond);
if (m) {
filters.push({
dimension: dimNameFor(p(m[2])),
operator: m[1] ? 'is_null' : 'is_not_null',
values: [],
});
continue;
}
m = /^dim_values\[indexOf\(dim_names, \{(fn\d+):String\}\)\] (NOT IN|IN) \((.+)\)$/.exec(cond);
if (m) {
const keys = m[3].split(', ').map((t) => /^\{(fv\d+_\d+):String\}$/.exec(t)?.[1]);
if (keys.some((k) => !k)) throw new Error(`IN list contains a non-parameter token: ${m[3]}`);
filters.push({
dimension: dimNameFor(p(m[1])),
operator: m[2] === 'NOT IN' ? 'not_in' : 'in',
values: keys.map((k) => p(k as string)),
});
continue;
}
m = /^dim_values\[indexOf\(dim_names, \{(fn\d+):String\}\)\] (=|!=|<=|>=|<|>) \{(fv\d+):String\}$/.exec(
cond,
);
if (m) {
filters.push({ dimension: dimNameFor(p(m[1])), operator: OP_SYMBOL[m[2]], values: [p(m[3])] });
continue;
}
throw new Error(`unrecognised compiled condition (possible unbound SQL text): ${cond}`);
}
const selectMatch = /^SELECT (.*?) FROM /.exec(c.sql);
if (!selectMatch) throw new Error('compiled SQL has no SELECT list');
const metricKeys = [...selectMatch[1].matchAll(/\{(m\d+):String\}/g)].map((mm) => p(mm[1]));
const dimKeys = [...selectMatch[1].matchAll(/\{(d\d+):String\}/g)].map((mm) => p(mm[1]));
const grainMatch = /toStartOf(\w+)\(/.exec(selectMatch[1]);
const orderMatch = /\sORDER BY\s(.*?)\sLIMIT\s/.exec(c.sql);
const order = orderMatch
? orderMatch[1].split(', ').map((tok) => {
const [alias, dir] = tok.split(' ');
const name = c.metricAliases[alias] ?? c.dimensionAliases[alias];
if (!name) throw new Error(`ORDER BY references unknown alias ${alias}`);
return `${name}:${dir.toLowerCase()}`;
})
: [];
const limitMatch = /\sLIMIT (\d+) FORMAT JSON$/.exec(c.sql);
if (!limitMatch) throw new Error('compiled SQL has no LIMIT');
return {
dataset_id: p('dataset'),
metrics: metricKeys.map((k) => KEY_TO_METRIC.get(k) ?? k).sort(),
dimensions: dimKeys.map((k) => FIELD_TO_NAME.get(k) ?? k).sort(),
filters: filters.sort((a, b) => (a.dimension + a.operator).localeCompare(b.dimension + b.operator)),
order,
limit: Number(limitMatch[1]),
timeFrom,
timeTo,
grain: grainMatch ? (grainMatch[1].toLowerCase() as QueryShape['grain']) : undefined,
};
}
function dimNameFor(field: string): string {
const name = FIELD_TO_NAME.get(field);
if (!name) throw new Error(`compiled SQL bound an unknown physical dimension "${field}"`);
return name;
}
// ── 1. the API does not accept SQL ─────────────────────────────────────────
describe('BI-P016 — the product API accepts no SQL', () => {
const base = { dataset: 'ds_sales', metrics: ['orders'] };
const smuggling = [
'sql',
'query',
'rawSql',
'raw_sql',
'raw',
'where',
'having',
'expression',
'expr',
'select',
'from',
'groupBy',
'group_by',
'unsafe',
];
it.each(smuggling)('rejects a request carrying a %s field', (key) => {
expect(() => parseAnalyticsQueryRequest({ ...base, [key]: 'SELECT 1' })).toThrowError(SiaxError);
try {
parseAnalyticsQueryRequest({ ...base, [key]: 'SELECT 1' });
} catch (e) {
expect((e as SiaxError).code).toBe('INVALID_REQUEST');
}
});
// The INF0 Wave-2 lesson: a tenant read out of a request body. The contract
// must not merely IGNORE such a field; ignoring it is what lets a later
// refactor start honouring it.
it.each(['tenant', 'tenant_id', 'tenantId', 'project_id', 'database', 'catalog', 'table'])(
'rejects caller-supplied %s (tenant/catalog selection is never a request field)',
(key) => {
expect(() => parseAnalyticsQueryRequest({ ...base, [key]: 't_beta' })).toThrowError(SiaxError);
},
);
it('rejects ANY unknown key, not just the ones on the smell list', () => {
expect(() => parseAnalyticsQueryRequest({ ...base, somethingNewNextQuarter: 1 })).toThrowError(SiaxError);
});
it('accepts exactly the eight BI-P016 fields and no more', () => {
expect([...ANALYTICS_QUERY_REQUEST_KEYS]).toEqual([
'dataset',
'metrics',
'dimensions',
'filters',
'timeRange',
'orderBy',
'limit',
'format',
]);
});
it('rejects SQL smuggled into a nested filter object', () => {
expect(() =>
parseAnalyticsQueryRequest({
...base,
filters: [{ dimension: 'country', operator: 'eq', values: ['SE'], sql: 'OR 1=1' }],
}),
).toThrowError(SiaxError);
});
it('keeps the filter operator set closed', () => {
expect([...FILTER_OPERATORS]).toEqual([
'eq',
'ne',
'in',
'not_in',
'lt',
'lte',
'gt',
'gte',
'contains',
'is_null',
'is_not_null',
]);
expect(() =>
parseAnalyticsQueryRequest({
...base,
filters: [{ dimension: 'country', operator: 'raw', values: ['x'] }],
}),
).toThrowError(SiaxError);
});
it('refuses an orderBy that is not selected (the obvious expression smuggling slot)', () => {
expect(() =>
parseAnalyticsQueryRequest({ ...base, orderBy: [{ ref: '(SELECT 1)', direction: 'asc' }] }),
).toThrowError(SiaxError);
});
it('refuses a metric the catalog does not declare', () => {
const req = parseAnalyticsQueryRequest({ dataset: 'ds_sales', metrics: ['orders OR 1=1'] });
expect(() => resolveAnalyticsQuery(req, resolution)).toThrowError(SiaxError);
});
it('refuses slicing a metric by a dimension its definition disallows', () => {
const req = parseAnalyticsQueryRequest({
dataset: 'ds_sales',
metrics: ['restricted'],
dimensions: ['segment'],
});
try {
resolveAnalyticsQuery(req, resolution);
throw new Error('expected a rejection');
} catch (e) {
expect((e as SiaxError).code).toBe('AUTHORIZATION_DENIED');
}
});
it('refuses a dataset that is not the authorised one', () => {
const req = parseAnalyticsQueryRequest({ dataset: 'ds_other', metrics: ['orders'] });
try {
resolveAnalyticsQuery(req, resolution);
throw new Error('expected a rejection');
} catch (e) {
expect((e as SiaxError).code).toBe('AUTHORIZATION_DENIED');
}
});
it('rejects a reversed time range instead of silently returning zero rows', () => {
expect(() =>
parseAnalyticsQueryRequest({ ...base, timeRange: { from: '2026-02-01', to: '2026-01-01' } }),
).toThrowError(SiaxError);
});
});
// ── 2. one request, two targets, same meaning ──────────────────────────────
describe('BI-P016 DoD — one request compiles to ClickHouse and to the semantic engine', () => {
const requests: Array<[string, unknown]> = [
['metric only', { dataset: 'ds_sales', metrics: ['orders'] }],
[
'two metrics, two dimensions',
{ dataset: 'ds_sales', metrics: ['orders', 'revenue'], dimensions: ['country', 'channel'] },
],
[
'filters of every value operator',
{
dataset: 'ds_sales',
metrics: ['revenue'],
dimensions: ['country'],
filters: [
{ dimension: 'country', operator: 'eq', values: ['SE'] },
{ dimension: 'channel', operator: 'in', values: ['web', 'retail'] },
{ dimension: 'segment', operator: 'not_in', values: ['test'] },
{ dimension: 'channel', operator: 'contains', values: ['we'] },
],
},
],
[
'time range with grain and ordering',
{
dataset: 'ds_sales',
metrics: ['revenue'],
dimensions: ['country'],
timeRange: { from: '2026-01-01T00:00:00Z', to: '2026-02-01T00:00:00Z', grain: 'day' },
orderBy: [{ ref: 'revenue', direction: 'desc' }],
limit: 50,
},
],
[
'presence filters',
{
dataset: 'ds_sales',
metrics: ['orders'],
filters: [
{ dimension: 'segment', operator: 'is_null' },
{ dimension: 'channel', operator: 'is_not_null' },
],
},
],
];
it.each(requests)('%s — both targets agree', (_label, raw) => {
const req = parseAnalyticsQueryRequest(raw);
const resolved = resolveAnalyticsQuery(req, resolution);
const ch = compileRequestToClickHouse(resolved, {
tenant_id: 't_alpha',
project_id: 'p_main',
database: 'opt_analytics',
maxResultRows: 10_000,
});
const sem = compileRequestToSemantic(resolved);
const fromSql = shapeOfCompiledSql(ch);
const fromSemantic = shapeOfSemanticSpec(sem);
expect(fromSql.dataset_id).toBe(fromSemantic.dataset_id);
expect(fromSql.metrics).toEqual(fromSemantic.metrics);
expect(fromSql.dimensions).toEqual(fromSemantic.dimensions);
expect(fromSql.filters).toEqual(fromSemantic.filters);
expect(fromSql.order).toEqual(fromSemantic.order);
expect(fromSql.limit).toBe(fromSemantic.limit);
expect(fromSql.timeFrom).toBe(fromSemantic.timeFrom);
expect(fromSql.timeTo).toBe(fromSemantic.timeTo);
expect(fromSql.grain).toBe(fromSemantic.grain);
});
it('carries the canonical metric_id into the semantic spec so the engine is replaceable', () => {
const req = parseAnalyticsQueryRequest({ dataset: 'ds_sales', metrics: ['revenue'] });
const spec = compileRequestToSemantic(resolveAnalyticsQuery(req, resolution));
expect(spec.metrics[0].metric_id).toBe('m_revenue');
expect(spec.semantic_model_version).toBe(7);
});
it('never puts a SQL predicate string in the semantic spec', () => {
const req = parseAnalyticsQueryRequest({
dataset: 'ds_sales',
metrics: ['orders'],
filters: [{ dimension: 'country', operator: 'eq', values: ["SE' OR '1'='1"] }],
});
const spec = compileRequestToSemantic(resolveAnalyticsQuery(req, resolution));
// The hostile value survives as DATA — structured, not concatenated.
expect(spec.where[0].values).toEqual(["SE' OR '1'='1"]);
expect(JSON.stringify(spec)).not.toMatch(/SELECT|WHERE\s/i);
});
});
// ── 3. tenant forcing survives every request shape ─────────────────────────
describe('BI-P011 forced tenant predicate survives the BI-P016 contract', () => {
it.each(requests())('compiled SQL forces the tenant predicate first: %s', (_label, raw) => {
const c = compile(parseAnalyticsQueryRequest(raw));
const where = /\sWHERE\s(.*?)(?:\sGROUP BY\s|\sORDER BY\s|\sLIMIT\s)/.exec(c.sql);
expect(where).not.toBeNull();
expect(splitConditions((where as RegExpExecArray)[1])[0]).toBe(FORCED_TENANT_PREDICATE);
expect(c.params.param_tenant).toBe('t_alpha');
});
it('refuses to compile with a blank tenant rather than emitting no predicate', () => {
const resolved = resolveAnalyticsQuery(
parseAnalyticsQueryRequest({ dataset: 'ds_sales', metrics: ['orders'] }),
resolution,
);
for (const blank of ['', ' ']) {
expect(() =>
compileRequestToClickHouse(resolved, {
tenant_id: blank,
database: 'opt_analytics',
maxResultRows: 100,
}),
).toThrowError(SiaxError);
}
});
it('puts no caller-supplied value anywhere in the SQL text', () => {
const hostile = "'; DROP TABLE opt_analytics_event; --";
const c = compile(
parseAnalyticsQueryRequest({
dataset: 'ds_sales',
metrics: ['orders'],
filters: [{ dimension: 'country', operator: 'eq', values: [hostile] }],
}),
);
expect(c.sql).not.toContain(hostile);
expect(c.sql).not.toContain('DROP');
expect(Object.values(c.params)).toContain(hostile);
});
it('clamps the limit down to the governance ceiling and never up', () => {
const resolved = resolveAnalyticsQuery(
parseAnalyticsQueryRequest({ dataset: 'ds_sales', metrics: ['orders'], limit: 1_000_000 }),
resolution,
);
const c = compileRequestToClickHouse(resolved, {
tenant_id: 't_alpha',
database: 'opt_analytics',
maxResultRows: 500,
});
expect(c.effectiveLimit).toBe(500);
expect(c.sql).toContain('LIMIT 500');
});
});
function requests(): Array<[string, unknown]> {
return [
['bare', { dataset: 'ds_sales', metrics: ['orders'] }],
['grouped', { dataset: 'ds_sales', metrics: ['orders'], dimensions: ['country'] }],
[
'filtered',
{
dataset: 'ds_sales',
metrics: ['orders'],
filters: [{ dimension: 'country', operator: 'in', values: ['SE', 'NO'] }],
},
],
[
'time-bucketed',
{ dataset: 'ds_sales', metrics: ['revenue'], timeRange: { from: '2026-01-01', grain: 'month' } },
],
[
'everything at once',
{
dataset: 'ds_sales',
metrics: ['orders', 'revenue'],
dimensions: ['country', 'channel'],
filters: [
{ dimension: 'segment', operator: 'ne', values: ['internal'] },
{ dimension: 'channel', operator: 'is_not_null' },
],
timeRange: { from: '2026-01-01', to: '2026-03-01', grain: 'week' },
orderBy: [{ ref: 'revenue', direction: 'desc' }],
limit: 25,
format: 'arrow_ipc',
},
],
];
}
+122
View File
@@ -0,0 +1,122 @@
/**
* BI-P012 — CLICKHOUSE RESOURCE GOVERNANCE, the part provable without an
* engine. The "intentional query bomb is terminated" half of the DoD needs a
* real server and lives in
* tests/integration/analytics-resource-governance.integration.test.ts.
*/
import { describe, it, expect } from 'vitest';
import {
applyQuota,
BUDGET_TIERS,
clickhouseSettings,
ConcurrencyGate,
concurrencyProfileSql,
DEFAULT_BUDGETS,
REQUIRED_GOVERNANCE_SETTINGS,
} from '@/src/analytics/engine/resource-governance';
describe('BI-P012 resource governance', () => {
it('every setting the program names has a value somewhere in the enforcement path', () => {
const settings = clickhouseSettings(DEFAULT_BUDGETS.INTERACTIVE);
const profile = concurrencyProfileSql('opt_t_alpha', DEFAULT_BUDGETS.INTERACTIVE).join(' ');
for (const name of REQUIRED_GOVERNANCE_SETTINGS) {
const present = name in settings || profile.includes(name) || name === 'max_concurrent_queries';
expect(present, `${name} is not enforced anywhere`).toBe(true);
}
// The five per-statement ones must be on the STATEMENT, not only in a
// profile a future operator might forget to attach.
for (const name of [
'max_execution_time',
'max_result_rows',
'max_rows_to_read',
'max_bytes_to_read',
'max_memory_usage',
]) {
expect(settings[name], `${name} missing from per-statement settings`).toBeDefined();
}
});
it('readonly=1 rides on every SELECT so the query text cannot re-set the limits', () => {
for (const tier of BUDGET_TIERS) {
expect(clickhouseSettings(DEFAULT_BUDGETS[tier]).readonly).toBe('1');
}
});
it('overflow modes are THROW, not BREAK — a partial result must never look complete', () => {
const s = clickhouseSettings(DEFAULT_BUDGETS.INTERACTIVE);
expect(s.result_overflow_mode).toBe('throw');
expect(s.read_overflow_mode).toBe('throw');
expect(s.timeout_overflow_mode).toBe('throw');
});
it('a CL0UD quota can only TIGHTEN a tier, never loosen it', () => {
const base = DEFAULT_BUDGETS.INTERACTIVE;
const loosened = applyQuota(base, {
maxExecutionTimeSec: 100000,
maxResultRows: 10_000_000,
maxRowsToRead: Number.MAX_SAFE_INTEGER,
maxBytesToRead: Number.MAX_SAFE_INTEGER,
maxMemoryUsageBytes: Number.MAX_SAFE_INTEGER,
maxConcurrentQueries: 1000,
});
expect(loosened).toEqual(base);
const tightened = applyQuota(base, { maxResultRows: 100, maxConcurrentQueries: 1 });
expect(tightened.maxResultRows).toBe(100);
expect(tightened.maxConcurrentQueries).toBe(1);
expect(tightened.maxExecutionTimeSec).toBe(base.maxExecutionTimeSec);
});
it('a nonsense quota (zero, negative, NaN) falls back to the tier rather than to no limit', () => {
const base = DEFAULT_BUDGETS.INTERACTIVE;
expect(applyQuota(base, { maxResultRows: 0 }).maxResultRows).toBe(base.maxResultRows);
expect(applyQuota(base, { maxResultRows: -5 }).maxResultRows).toBe(base.maxResultRows);
expect(applyQuota(base, { maxResultRows: Number.NaN }).maxResultRows).toBe(base.maxResultRows);
expect(applyQuota(base, undefined)).toEqual(base);
});
it('tiers get progressively more generous, and INTERACTIVE is the mean default', () => {
expect(DEFAULT_BUDGETS.INTERACTIVE.maxExecutionTimeSec).toBeLessThan(
DEFAULT_BUDGETS.ANALYTICAL.maxExecutionTimeSec,
);
expect(DEFAULT_BUDGETS.ANALYTICAL.maxExecutionTimeSec).toBeLessThan(
DEFAULT_BUDGETS.BATCH.maxExecutionTimeSec,
);
expect(DEFAULT_BUDGETS.INTERACTIVE.maxRowsToRead).toBeLessThan(DEFAULT_BUDGETS.ANALYTICAL.maxRowsToRead);
});
it('the concurrency gate throttles ONE tenant without touching another', () => {
const gate = new ConcurrencyGate((t) => (t === 't_noisy' ? 2 : 5));
const a = gate.acquire('t_noisy');
const b = gate.acquire('t_noisy');
expect(gate.inFlightFor('t_noisy')).toBe(2);
expect(() => gate.acquire('t_noisy')).toThrowError(/queries in flight/);
// The quiet tenant is unaffected — BI-P012's "without degrading unrelated
// tenant" in the smallest testable form.
const quiet = gate.acquire('t_quiet');
expect(gate.inFlightFor('t_quiet')).toBe(1);
a();
expect(gate.inFlightFor('t_noisy')).toBe(1);
expect(() => gate.acquire('t_noisy')).not.toThrow();
b();
quiet();
});
it('releasing twice does not free a slot that was never taken', () => {
const gate = new ConcurrencyGate(() => 1);
const release = gate.acquire('t_x');
release();
release();
expect(gate.inFlightFor('t_x')).toBe(0);
expect(gate.totalInFlight()).toBe(0);
});
it("the settings profile SQL carries max_concurrent_queries' server-side half", () => {
const stmts = concurrencyProfileSql('opt_t_alpha', DEFAULT_BUDGETS.INTERACTIVE);
expect(stmts.join(' ')).toContain('CREATE SETTINGS PROFILE IF NOT EXISTS opt_t_alpha');
expect(stmts.join(' ')).toContain('readonly = 1');
expect(stmts.join(' ')).toContain('CREATE QUOTA IF NOT EXISTS opt_t_alpha_quota');
});
});
@@ -0,0 +1,151 @@
/**
* BI-P009's non-negotiable line: "Do not regress the existing forced tenant
* predicate."
*
* This suite is written to FAIL IF THE FORCING IS REMOVED, which is a
* different thing from testing that it currently works. Concretely, each test
* below would go red under a specific, plausible regression:
*
* * someone makes `tenant_id` optional in the metric DSL -> "refuses a
* blank tenant" fails;
* * someone "simplifies" the WHERE builder and drops the tenant condition
* -> "every compiled statement contains the predicate" fails on a missing
* substring;
* * someone starts splicing the tenant value into SQL text instead of
* binding it -> "the tenant VALUE never appears in the SQL text" fails;
* * someone lets a caller pass a tenant through the request body rather
* than the verified identity -> "identity wins over any request field"
* fails.
*
* It covers BOTH compilers: the PRESERVED `ClickHouseAnalytics.queryMetric`
* (src/analytics/clickhouse-analytics.ts, untouched by BI-P009) and the new
* `compileMetricQuery` — because "preserved" means the old guarantee has to
* keep holding, not merely that the file still exists.
*
* The ClickHouseAnalytics half asserts against the URL the adapter actually
* builds, captured with a stub `fetch`. That is deliberate: a mock ENGINE
* could be made to return anything, but the SQL text on the wire is the thing
* the real server would receive, so asserting on it cannot be faked by the
* test double.
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import { ClickHouseAnalytics } from '@/src/analytics/clickhouse-analytics';
import {
compileMetricQuery,
compileProjectionQuery,
dimensionCatalogFrom,
FORCED_TENANT_PREDICATE,
} from '@/src/analytics/engine/query-compiler';
const catalog = dimensionCatalogFrom({ severity: 'severity', make: 'vehicle_make' });
/** Captures every URL the adapter fetches, returning an empty JSON result. */
function captureFetch(): { urls: string[]; restore: () => void } {
const urls: string[] = [];
const original = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
urls.push(String(input));
return new Response(JSON.stringify({ data: [] }), { status: 200 });
}) as typeof fetch;
return { urls, restore: () => (globalThis.fetch = original) };
}
afterEach(() => {
vi.restoreAllMocks();
});
describe('BI-P009 regression guard: the forced tenant predicate', () => {
it('PRESERVED ClickHouseAnalytics still emits tenant_id = {tenant:String} on the wire', async () => {
const cap = captureFetch();
try {
const analytics = new ClickHouseAnalytics({ baseUrl: 'http://ch.invalid:8123', database: 'opt_test' });
await analytics.queryMetric({ tenant_id: 't_alpha', metric: 'rows', aggregate: 'sum' });
expect(cap.urls).toHaveLength(1);
// URLSearchParams decodes `+` as a space, which raw decodeURIComponent
// does not — read the statement the way the server will.
const query = new URL(cap.urls[0]).searchParams.get('query') ?? '';
expect(query).toContain('tenant_id = {tenant:String}');
expect(query).toMatch(/WHERE tenant_id = \{tenant:String\}/);
// The VALUE travels as a bound parameter, never inside the statement.
expect(query).not.toContain('t_alpha');
expect(new URL(cap.urls[0]).searchParams.get('param_tenant')).toBe('t_alpha');
} finally {
cap.restore();
}
});
it('PRESERVED ClickHouseAnalytics still refuses a blank tenant_id', async () => {
const analytics = new ClickHouseAnalytics({ baseUrl: 'http://ch.invalid:8123' });
await expect(
analytics.queryMetric({ tenant_id: ' ', metric: 'x', aggregate: 'sum' }),
).rejects.toMatchObject({
code: 'INVALID_REQUEST',
});
});
it('PRESERVED ClickHouseAnalytics still refuses a hostile group_by identifier', async () => {
const analytics = new ClickHouseAnalytics({ baseUrl: 'http://ch.invalid:8123' });
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' });
});
it('every statement the NEW compiler produces contains the forced predicate', () => {
const shapes = [
{ metric: 'm', aggregate: 'sum' as const },
{ metric: 'm', aggregate: 'count' as const, group_by: ['severity'] },
{ metric: 'm', aggregate: 'avg' as const, filters: { make: 'volvo' }, dataset_id: 'ds_1' },
{ metric: 'm', aggregate: 'max' as const, from_time: '2026-01-01', to_time: '2026-02-01' },
{ metric: 'm', aggregate: 'count_distinct' as const, group_by: ['severity', 'make'], limit: 5 },
];
for (const shape of shapes) {
const compiled = compileMetricQuery({ tenant_id: 't_alpha', ...shape }, 'opt_analytics', catalog, 1000);
expect(compiled.sql).toContain(FORCED_TENANT_PREDICATE);
// The predicate must be in the WHERE, not in a comment or an alias.
expect(compiled.sql).toMatch(/WHERE tenant_id = \{tenant:String\}/);
expect(compiled.params.param_tenant).toBe('t_alpha');
expect(compiled.sql).not.toContain('t_alpha');
}
const projection = compileProjectionQuery(
{ tenant_id: 't_alpha', dataset_id: 'ds_1', entity_keys: ['a', 'b'] },
'opt_analytics',
1000,
);
expect(projection.sql).toMatch(/WHERE tenant_id = \{tenant:String\}/);
expect(projection.sql).not.toContain('t_alpha');
});
it('the NEW compiler fails closed on a blank/absent tenant instead of emitting an unfiltered query', () => {
for (const tenant of ['', ' ']) {
expect(() =>
compileMetricQuery(
{ tenant_id: tenant, metric: 'm', aggregate: 'sum' },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/tenant_id is required/);
}
// The undefined case, which TypeScript would normally forbid, is what a
// JS caller or a loosely-typed HTTP boundary can actually produce.
expect(() =>
compileMetricQuery(
{ tenant_id: undefined as unknown as string, metric: 'm', aggregate: 'sum' },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/tenant_id is required/);
});
it('the constant itself is the predicate, so deleting the forcing cannot pass silently', () => {
// If someone redefines FORCED_TENANT_PREDICATE to something harmless
// (e.g. "1 = 1") to make the substring assertions above pass, this fails.
expect(FORCED_TENANT_PREDICATE).toBe('tenant_id = {tenant:String}');
});
});