docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 03:07:36 +01:00
parent fb072d47c7
commit a4189333af
959 changed files with 5 additions and 115771 deletions
-237
View File
@@ -1,237 +0,0 @@
/**
* src/analytics/arrow/flatbuffer-builder.ts
* ==========================================
* A minimal FlatBuffers writer, sufficient for the Arrow IPC metadata
* messages this repo emits (BI-P005).
*
* WHY HAND-ROLLED rather than `apache-arrow` from npm: adding a runtime
* dependency to 0pt's blocking-typechecked capability layer means a lockfile
* change, a new supply-chain surface, and a new CVE surface for every
* consumer of this repo — for a format whose METADATA side is a few hundred
* bytes of well-specified binary and whose DATA side is plain columnar memory
* either way.
*
* The correctness bar is NOT "this looks right". The BI-P005 evidence script
* (scripts/bi-p005-arrow-roundtrip.mjs) decodes this writer's output with
* pyarrow AND DuckDB — two independent implementations of the specification —
* so a mistake here surfaces as a failed decode by somebody else's parser,
* not as a green test of my own assumptions.
*
* Layout facts implemented (FlatBuffers binary format, little-endian):
* * the buffer is built BACK TO FRONT; `offset` counts bytes from the end;
* * a uoffset stored at a field site holds `site_offset + 4 - target_offset`
* so a reader resolves it as `position + value`;
* * a table begins with an soffset `table_start - vtable_start`;
* * a vtable is `[vtable_len:i16][table_len:i16][field_offsets:i16...]`,
* with 0 meaning "field absent, use the default".
*/
export type Offset = number;
const SIZEOF_INT = 4;
export class FlatBufferBuilder {
private buf: Uint8Array;
private view: DataView;
/** Bytes written so far, counted from the END of `buf`. */
private used = 0;
private minAlign = 1;
private vtable: number[] = [];
private objectStart = 0;
private inObject = false;
/** Offsets of previously written vtables, for deduplication. */
private vtables: number[] = [];
constructor(initial = 1024) {
this.buf = new Uint8Array(initial);
this.view = new DataView(this.buf.buffer);
}
/** Bytes written so far (FlatBuffers "offset"). */
get offset(): number {
return this.used;
}
private ensure(extra: number): void {
if (this.used + extra <= this.buf.length) return;
let size = this.buf.length;
while (size < this.used + extra) size *= 2;
const next = new Uint8Array(size);
next.set(this.buf.subarray(this.buf.length - this.used), size - this.used);
this.buf = next;
this.view = new DataView(this.buf.buffer);
}
private pad(n: number): void {
if (n <= 0) return;
this.ensure(n);
for (let i = 0; i < n; i++) {
this.used += 1;
this.buf[this.buf.length - this.used] = 0;
}
}
/** FlatBuffers `prep`: pad so that `additional` more bytes land aligned. */
private prep(size: number, additional = 0): void {
if (size > this.minAlign) this.minAlign = size;
const alignSize = (~(this.used + additional) + 1) & (size - 1);
this.pad(alignSize);
}
writeInt8(v: number): void {
this.ensure(1);
this.used += 1;
this.view.setInt8(this.buf.length - this.used, v);
}
writeInt16(v: number): void {
this.ensure(2);
this.used += 2;
this.view.setInt16(this.buf.length - this.used, v, true);
}
writeInt32(v: number): void {
this.ensure(4);
this.used += 4;
this.view.setInt32(this.buf.length - this.used, v, true);
}
writeInt64(v: bigint): void {
this.ensure(8);
this.used += 8;
this.view.setBigInt64(this.buf.length - this.used, v, true);
}
writeBytes(bytes: Uint8Array): void {
this.ensure(bytes.length);
this.used += bytes.length;
this.buf.set(bytes, this.buf.length - this.used);
}
addInt8(slot: number, value: number, def: number): void {
if (value === def) return;
this.prep(1);
this.writeInt8(value);
this.slot(slot);
}
addInt16(slot: number, value: number, def: number): void {
if (value === def) return;
this.prep(2);
this.writeInt16(value);
this.slot(slot);
}
addInt32(slot: number, value: number, def: number): void {
if (value === def) return;
this.prep(4);
this.writeInt32(value);
this.slot(slot);
}
addInt64(slot: number, value: bigint, def: bigint): void {
if (value === def) return;
this.prep(8);
this.writeInt64(value);
this.slot(slot);
}
addOffset(slot: number, value: Offset, def: number): void {
if (value === def) return;
this.prep(SIZEOF_INT);
this.writeInt32(this.used + SIZEOF_INT - value);
this.slot(slot);
}
private slot(slotNum: number): void {
this.vtable[slotNum] = this.used;
}
startObject(numFields: number): void {
if (this.inObject) throw new Error("nested startObject");
this.vtable = new Array<number>(numFields).fill(0);
this.objectStart = this.used;
this.inObject = true;
}
endObject(): Offset {
if (!this.inObject) throw new Error("endObject outside an object");
this.prep(SIZEOF_INT);
this.writeInt32(0); // soffset placeholder, patched below
const objectOffset = this.used;
let trimmed = this.vtable.length;
while (trimmed > 0 && this.vtable[trimmed - 1] === 0) trimmed -= 1;
for (let i = trimmed - 1; i >= 0; i--) {
this.writeInt16(this.vtable[i] !== 0 ? objectOffset - this.vtable[i] : 0);
}
this.writeInt16(objectOffset - this.objectStart); // table byte length
const vtLen = (trimmed + 2) * 2;
this.writeInt16(vtLen); // vtable byte length — lands at the vtable start
const vtStart = this.used;
const vtAbs = this.buf.length - vtStart;
let existing = 0;
for (const candidate of this.vtables) {
const candAbs = this.buf.length - candidate;
if (this.view.getInt16(candAbs, true) !== vtLen) continue;
let same = true;
for (let i = 2; i < vtLen; i += 2) {
if (this.view.getInt16(vtAbs + i, true) !== this.view.getInt16(candAbs + i, true)) {
same = false;
break;
}
}
if (same) {
existing = candidate;
break;
}
}
const objAbs = this.buf.length - objectOffset;
if (existing !== 0) {
this.used -= vtLen; // discard the duplicate vtable just written
this.view.setInt32(objAbs, existing - objectOffset, true);
} else {
this.vtables.push(vtStart);
this.view.setInt32(objAbs, this.used - objectOffset, true);
}
this.inObject = false;
return objectOffset;
}
createString(s: string): Offset {
const bytes = new TextEncoder().encode(s);
this.writeInt8(0); // null terminator (readers rely on it)
this.startVector(1, bytes.length, 1);
this.writeBytes(bytes);
return this.endVector(bytes.length);
}
startVector(elemSize: number, numElems: number, alignment: number): void {
this.prep(SIZEOF_INT, elemSize * numElems);
this.prep(alignment, elemSize * numElems);
}
endVector(numElems: number): Offset {
this.writeInt32(numElems);
return this.used;
}
/** Vector of table offsets. Elements are written in reverse build order. */
createOffsetVector(items: Offset[]): Offset {
this.startVector(SIZEOF_INT, items.length, SIZEOF_INT);
for (let i = items.length - 1; i >= 0; i--) {
this.writeInt32(this.used + SIZEOF_INT - items[i]);
}
return this.endVector(items.length);
}
/** Finish the buffer with `root` as the root table. Returns the bytes. */
finish(root: Offset): Uint8Array {
this.prep(this.minAlign, SIZEOF_INT);
this.prep(SIZEOF_INT);
this.writeInt32(this.used + SIZEOF_INT - root);
return this.buf.slice(this.buf.length - this.used);
}
}
File diff suppressed because it is too large Load Diff
-341
View File
@@ -1,341 +0,0 @@
/**
* src/analytics/bench/benchmark-harness.ts
* =========================================
* BI-P104 — BI PERFORMANCE BENCHMARK HARNESS. DoD: "results committed as
* machine-readable evidence."
*
* The harness exists because of a specific way benchmarks lie. Yesterday's
* lane measured the same budget-enforcement overshoot at ~150x on one run and
* ~130x on the next, on the same machine, and correctly reported the SHAPE
* rather than a number. That is the doctrine encoded here:
*
* 1. A SINGLE FIGURE IS NOT A SYSTEM PROPERTY. `summarizeSamples` returns a
* distribution — n, min, p50, p95, p99, max, mean, stdev, CV, IQR — and
* there is no function anywhere in this module that returns one number
* for a measurement. `describeComparison` renders a RANGE and the sample
* size into every sentence it produces.
*
* 2. OVERLAPPING DISTRIBUTIONS ARE INDISTINGUISHABLE, whatever the medians
* say. If the candidate's p95 is not below the baseline's minimum, the
* verdict is `indistinguishable` even when p50 differs by 2x — because a
* 2x median gap inside a 10x spread is noise with a story attached.
*
* 3. TOO FEW SAMPLES IS A REFUSAL. Under MIN_SAMPLES the summary carries
* `stability: 'insufficient_samples'` and comparisons refuse to judge.
* A three-run benchmark is an anecdote.
*
* 4. AN ENGINE THAT WAS NOT RUN IS RECORDED AS NOT RUN. `EngineAvailability`
* carries a reason. The evidence file lists every engine BI-P104 names,
* including the ones nothing measured — an omitted engine reads as "we
* chose not to report it".
*/
/** The six dataset profiles BI-P104 names, with what makes each one distinct. */
export const BENCH_DATASETS = [
{
id: 'small_saas',
label: 'small SaaS',
approx_rows: 100_000,
shape: 'narrow fact table, one tenant, high selectivity',
},
{
id: 'medium_business',
label: 'medium business',
approx_rows: 2_000_000,
shape: 'multi-tenant fact table with a date and a few dimensions',
},
{
id: 'vehiq_market',
label: 'VehIQ market',
approx_rows: 1_000_000,
shape: 'vehicle listings: make/model/year/price/mileage, skewed cardinalities',
},
{
id: 'large_event',
label: 'large event',
approx_rows: 5_000_000,
shape: 'append-only event stream, timestamp-ordered, sparse dimensions',
},
{
id: 'wide_table',
label: 'wide table',
approx_rows: 200_000,
shape: 'many columns, few read per query — the columnar-store best case',
},
{
id: 'geospatial',
label: 'geospatial',
approx_rows: 500_000,
shape: 'lat/lon points with bounding-box and distance predicates',
},
] as const;
export type BenchDatasetId = (typeof BENCH_DATASETS)[number]['id'];
/** Every engine BI-P104 lists. All of them appear in the evidence, run or not. */
export const BENCH_ENGINES = [
'clickhouse',
'duckdb',
'trino',
'semantic_query',
'superset',
'native_charts',
'perspective',
] as const;
export type BenchEngine = (typeof BENCH_ENGINES)[number];
export interface EngineAvailability {
engine: BenchEngine;
available: boolean;
/** Required when unavailable. "Unknown" is not a reason. */
reason?: string;
version?: string;
}
export const STABILITY_VERDICTS = ['stable', 'noisy', 'unstable', 'insufficient_samples'] as const;
export type StabilityVerdict = (typeof STABILITY_VERDICTS)[number];
/** Below this a run is an anecdote, not a measurement. */
export const MIN_SAMPLES = 5;
/** Coefficient of variation thresholds. Wide on purpose: real hosts are noisy. */
const CV_STABLE = 0.15;
const CV_NOISY = 0.5;
export interface Distribution {
n: number;
min: number;
p50: number;
p95: number;
p99: number;
max: number;
mean: number;
stdev: number;
/** stdev / mean. The number that decides whether a comparison is meaningful. */
cv: number;
iqr: number;
/** max / min. Reported because it is what a reader feels. */
spread_ratio: number;
stability: StabilityVerdict;
}
/** Nearest-rank; no interpolation, so every reported value really happened. */
function pct(sorted: number[], q: number): number {
const rank = Math.ceil(q * sorted.length);
return sorted[Math.min(sorted.length - 1, Math.max(0, rank - 1))];
}
export function summarizeSamples(samples: readonly number[]): Distribution {
if (samples.length === 0) {
return {
n: 0,
min: 0,
p50: 0,
p95: 0,
p99: 0,
max: 0,
mean: 0,
stdev: 0,
cv: 0,
iqr: 0,
spread_ratio: 0,
stability: 'insufficient_samples',
};
}
const s = [...samples].sort((a, b) => a - b);
const mean = s.reduce((a, b) => a + b, 0) / s.length;
const variance = s.reduce((acc, v) => acc + (v - mean) ** 2, 0) / s.length;
const stdev = Math.sqrt(variance);
const cv = mean === 0 ? 0 : stdev / mean;
const stability: StabilityVerdict =
s.length < MIN_SAMPLES
? 'insufficient_samples'
: cv <= CV_STABLE
? 'stable'
: cv <= CV_NOISY
? 'noisy'
: 'unstable';
return {
n: s.length,
min: s[0],
p50: pct(s, 0.5),
p95: pct(s, 0.95),
p99: pct(s, 0.99),
max: s[s.length - 1],
mean,
stdev,
cv,
iqr: pct(s, 0.75) - pct(s, 0.25),
spread_ratio: s[0] === 0 ? Number.POSITIVE_INFINITY : s[s.length - 1] / s[0],
stability,
};
}
export const COMPARISON_VERDICTS = ['faster', 'slower', 'indistinguishable', 'not_comparable'] as const;
export type ComparisonVerdict = (typeof COMPARISON_VERDICTS)[number];
export interface Comparison {
verdict: ComparisonVerdict;
/** Ratio of medians. Present for information; never the claim on its own. */
p50_ratio: number;
/** Worst case for the candidate: baseline.min / candidate.max. */
conservative_ratio: number;
/** Best case for the candidate: baseline.max / candidate.min. */
optimistic_ratio: number;
/** True when the observed ranges overlap at all. */
ranges_overlap: boolean;
baseline: Distribution;
candidate: Distribution;
}
/**
* Compare two measured distributions.
*
* `faster` requires clean separation — the candidate's p95 below the
* baseline's minimum. Anything less is `indistinguishable`, however flattering
* the medians look, because that is exactly the claim a noisy host will
* manufacture for you.
*/
export function compareDistributions(baseline: Distribution, candidate: Distribution): Comparison {
const ratio = (a: number, b: number) => (b === 0 ? Number.POSITIVE_INFINITY : a / b);
const base: Omit<Comparison, 'verdict'> = {
p50_ratio: ratio(baseline.p50, candidate.p50),
conservative_ratio: ratio(baseline.min, candidate.max),
optimistic_ratio: ratio(baseline.max, candidate.min),
ranges_overlap: !(candidate.max < baseline.min || baseline.max < candidate.min),
baseline,
candidate,
};
if (baseline.stability === 'insufficient_samples' || candidate.stability === 'insufficient_samples') {
return { ...base, verdict: 'not_comparable' };
}
if (candidate.p95 < baseline.min) return { ...base, verdict: 'faster' };
if (baseline.p95 < candidate.min) return { ...base, verdict: 'slower' };
return { ...base, verdict: 'indistinguishable' };
}
/**
* The sentence a human is allowed to quote. It ALWAYS carries the range, the
* sample size and the stability verdict, so it cannot be trimmed down to "3.4x
* faster" without visibly removing the caveats.
*/
export function describeComparison(c: Comparison, label = 'candidate'): string {
const r = (v: number) => (Number.isFinite(v) ? v.toFixed(1) : '∞');
if (c.verdict === 'not_comparable') {
return (
`${label}: NOT COMPARABLE — ${c.baseline.n} baseline and ${c.candidate.n} candidate samples, ` +
`fewer than the ${MIN_SAMPLES} required. A run this short is an anecdote.`
);
}
if (c.verdict === 'indistinguishable') {
return (
`${label}: INDISTINGUISHABLE at this sample size. Medians differ by ${r(c.p50_ratio)}x but the ` +
`observed ranges overlap (baseline ${c.baseline.min.toFixed(1)}-${c.baseline.max.toFixed(1)}ms, ` +
`candidate ${c.candidate.min.toFixed(1)}-${c.candidate.max.toFixed(1)}ms; n=${c.baseline.n}/${c.candidate.n}, ` +
`CV ${c.baseline.cv.toFixed(2)}/${c.candidate.cv.toFixed(2)}).`
);
}
return (
`${label}: ${c.verdict.toUpperCase()} — ${r(c.conservative_ratio)}x to ${r(c.optimistic_ratio)}x ` +
`(median ${r(c.p50_ratio)}x) over n=${c.baseline.n}/${c.candidate.n}, ` +
`stability ${c.baseline.stability}/${c.candidate.stability}. Warm cache, one host, this query shape.`
);
}
export interface BenchmarkRun {
engine: BenchEngine;
dataset: BenchDatasetId;
query_label: string;
/** Discarded from the statistics; recorded so the discard is visible. */
warmup_ms: number[];
samples_ms: number[];
distribution: Distribution;
rows_returned?: number;
}
/**
* Run one measurement. Warmups are executed and RECORDED but excluded from the
* distribution: a first run that pays for cold marks and page cache is a
* different measurement, and silently folding it in is how a p95 becomes a
* story about disk.
*/
export async function measure(args: {
engine: BenchEngine;
dataset: BenchDatasetId;
query_label: string;
run: () => Promise<{ rows?: number }>;
warmups?: number;
repetitions?: number;
now?: () => number;
}): Promise<BenchmarkRun> {
const now = args.now ?? (() => performance.now());
const warmups = args.warmups ?? 2;
const repetitions = args.repetitions ?? 9;
const warmup_ms: number[] = [];
const samples_ms: number[] = [];
let rows: number | undefined;
for (let i = 0; i < warmups; i += 1) {
const t0 = now();
await args.run();
warmup_ms.push(now() - t0);
}
for (let i = 0; i < repetitions; i += 1) {
const t0 = now();
const out = await args.run();
samples_ms.push(now() - t0);
rows = out.rows ?? rows;
}
return {
engine: args.engine,
dataset: args.dataset,
query_label: args.query_label,
warmup_ms,
samples_ms,
distribution: summarizeSamples(samples_ms),
...(rows !== undefined ? { rows_returned: rows } : {}),
};
}
export interface BenchmarkEvidence {
recorded_at: string;
host_note: string;
datasets: typeof BENCH_DATASETS;
engines: EngineAvailability[];
runs: BenchmarkRun[];
comparisons: Array<{ dataset: BenchDatasetId; query_label: string; description: string } & Comparison>;
/** Engines BI-P104 names that produced no measurement, each with a reason. */
not_exercised: EngineAvailability[];
}
/**
* Assemble the evidence document. Every engine BI-P104 names appears, and the
* ones with no runs are listed under `not_exercised` with their reason — an
* engine quietly missing from a benchmark table reads as a choice.
*/
export function buildEvidence(args: {
host_note: string;
engines: EngineAvailability[];
runs: BenchmarkRun[];
comparisons?: BenchmarkEvidence['comparisons'];
now?: Date;
}): BenchmarkEvidence {
const measured = new Set(args.runs.map((r) => r.engine));
const declared = new Map(args.engines.map((e) => [e.engine, e]));
return {
recorded_at: (args.now ?? new Date()).toISOString(),
host_note: args.host_note,
datasets: BENCH_DATASETS,
engines: BENCH_ENGINES.map(
(engine) => declared.get(engine) ?? { engine, available: false, reason: 'not declared by this run' },
),
runs: args.runs,
comparisons: args.comparisons ?? [],
not_exercised: BENCH_ENGINES.filter((e) => !measured.has(e)).map((engine) => {
const d = declared.get(engine);
if (!d) return { engine, available: false, reason: 'not present in this environment' };
// An engine declared AVAILABLE that produced no measurement is the
// dangerous case: it reads as "we could have, and chose not to say".
// It gets a reason too, generated here rather than left blank.
return d.reason ? d : { ...d, reason: 'declared available but produced no measurement in this run' };
}),
};
}
-329
View File
@@ -1,329 +0,0 @@
/**
* src/analytics/cache/query-cache.ts
* ===================================
* BI-P020 — QUERY CACHE.
*
* "Cache key includes: tenant, semantic model version, metric definitions,
* filters, query, data snapshot/version. Never share tenant result cache."
*
* All six are REQUIRED, and the key builder refuses to produce a key when one
* is missing rather than defaulting it. A defaulted component is how a cache
* serves a result computed under a metric definition that no longer exists —
* the answer is not stale, it is WRONG, and it looks current.
*
* "Never share tenant result cache" is enforced structurally, not by
* discipline:
*
* * the key is PREFIXED with the tenant id, and the prefix is derived from
* the verified identity inside this module — a caller cannot pass one;
* * every read re-derives the prefix from the identity and REFUSES a stored
* entry whose recorded tenant does not match, so a prefix collision or a
* shared backing store still cannot serve a foreign result;
* * the stored entry carries its own tenant id, so the check is against the
* DATA, not against the key that found it.
*
* The second and third points exist because the first is a naming convention,
* and naming conventions are what ST0RE was relying on when it turned out to
* have four cross-tenant paths rather than the one reported.
*
* Provider-neutral: `AnalyticsResultCache` is the port. `InMemoryResultCache`
* is the reference implementation and the test double; `ValkeyResultCache`
* adapts any Valkey/Redis client that can GET/SET/DEL with a TTL, taking it as
* an injected interface so this module adds no dependency.
*/
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
/**
* Everything that must be true for a cached result to still be the right
* answer. Missing any one of these makes the cache unsound, so the type has no
* optional fields.
*/
export interface CacheKeyComponents {
/** From the verified identity. Not a caller-supplied value. */
tenant_id: string;
project_id?: string;
dataset_id: string;
/** BI-P030's semantic model version. Bumping it invalidates everything under it. */
semantic_model_version: number;
/**
* metric_id -> version, for EVERY metric in the query. A metric whose
* definition changed must not serve a result computed under the old one.
*/
metric_versions: Record<string, number>;
/** The compiled statement hash (BI-P018). Covers filters, grain and limit. */
compiled_query_hash: string;
/**
* The data snapshot the result was computed from. Whatever identifies "the
* data as of now" for this dataset: a DatasetVersion number, an Iceberg
* snapshot id, a max ingested watermark. Advancing it invalidates.
*/
data_snapshot: string;
/** Result encoding, since a JSON and an Arrow result are different bytes. */
format: string;
}
export interface CachedResult<T = unknown> {
/** Recorded so the read check is against the DATA, not against the key. */
tenant_id: string;
key: string;
value: T;
stored_at: string;
expires_at: string;
row_count: number;
/** Kept for targeted invalidation. */
dataset_id: string;
metric_ids: string[];
semantic_model_version: number;
data_snapshot: string;
}
export interface AnalyticsResultCache {
readonly provider: string;
get<T>(components: CacheKeyComponents): Promise<CachedResult<T> | undefined>;
set<T>(
components: CacheKeyComponents,
value: T,
opts: { ttlSeconds: number; rowCount: number },
): Promise<void>;
/** Drop every entry for a dataset — the blunt, always-correct invalidation. */
invalidateDataset(tenantId: string, datasetId: string): Promise<number>;
/** Drop every entry that used a given metric. */
invalidateMetric(tenantId: string, metricId: string): Promise<number>;
/** Drop everything for a tenant (offboarding, incident response). */
invalidateTenant(tenantId: string): Promise<number>;
}
function required(value: unknown, name: string): void {
if (
value === undefined ||
value === null ||
value === '' ||
(typeof value === 'number' && !Number.isFinite(value))
) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.cache',
`cache key component "${name}" is required — a defaulted component serves results computed under a definition that no longer exists`,
);
}
}
/**
* Build the key. Deterministic, tenant-prefixed, and total over the six
* components BI-P020 lists.
*
* The tenant prefix is in PLAINTEXT at the front rather than folded into the
* hash, so `invalidateTenant` is a prefix scan and an operator reading the
* store can see which tenant an entry belongs to without a lookup table.
*/
export function buildCacheKey(c: CacheKeyComponents): string {
required(c.tenant_id, 'tenant_id');
required(c.dataset_id, 'dataset_id');
required(c.semantic_model_version, 'semantic_model_version');
required(c.compiled_query_hash, 'compiled_query_hash');
required(c.data_snapshot, 'data_snapshot');
required(c.format, 'format');
if (!c.metric_versions || Object.keys(c.metric_versions).length === 0) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.cache',
'cache key component "metric_versions" is required and must name every metric in the query',
);
}
for (const [id, version] of Object.entries(c.metric_versions)) {
required(version, `metric_versions[${id}]`);
}
if (!/^[A-Za-z0-9_-]{1,64}$/.test(c.tenant_id)) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.cache', 'tenant id is not key-safe');
}
const material = JSON.stringify([
c.tenant_id,
c.project_id ?? '',
c.dataset_id,
c.semantic_model_version,
Object.keys(c.metric_versions)
.sort()
.map((k) => [k, c.metric_versions[k]]),
c.compiled_query_hash,
c.data_snapshot,
c.format,
]);
const digest = crypto.createHash('sha256').update(material).digest('hex');
return `optq:${c.tenant_id}:${digest}`;
}
/** The prefix `invalidateTenant` scans. Derived, never supplied. */
export function tenantKeyPrefix(tenantId: string): string {
return `optq:${tenantId}:`;
}
abstract class BaseResultCache implements AnalyticsResultCache {
abstract readonly provider: string;
protected abstract read(key: string): Promise<CachedResult | undefined>;
protected abstract write(entry: CachedResult, ttlSeconds: number): Promise<void>;
protected abstract entries(tenantId: string): Promise<CachedResult[]>;
protected abstract remove(keys: string[]): Promise<void>;
protected readonly now: () => number;
constructor(now: () => number = Date.now) {
this.now = now;
}
async get<T>(components: CacheKeyComponents): Promise<CachedResult<T> | undefined> {
const key = buildCacheKey(components);
const entry = await this.read(key);
if (!entry) return undefined;
// The check that survives a prefix collision or a shared backing store:
// the ENTRY says which tenant it belongs to, and it must be this one.
if (entry.tenant_id !== components.tenant_id) {
// Not a miss — a cross-tenant hit is a security event, and returning
// `undefined` would hide it. Drop the poisoned entry and refuse loudly.
await this.remove([key]);
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics.cache',
'cache entry belongs to a different tenant; entry evicted',
);
}
if (Date.parse(entry.expires_at) <= this.now()) {
await this.remove([key]);
return undefined;
}
return entry as CachedResult<T>;
}
async set<T>(
components: CacheKeyComponents,
value: T,
opts: { ttlSeconds: number; rowCount: number },
): Promise<void> {
if (!Number.isFinite(opts.ttlSeconds) || opts.ttlSeconds <= 0) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.cache', 'ttlSeconds must be positive');
}
const key = buildCacheKey(components);
const nowMs = this.now();
await this.write(
{
tenant_id: components.tenant_id,
key,
value,
stored_at: new Date(nowMs).toISOString(),
expires_at: new Date(nowMs + opts.ttlSeconds * 1000).toISOString(),
row_count: opts.rowCount,
dataset_id: components.dataset_id,
metric_ids: Object.keys(components.metric_versions),
semantic_model_version: components.semantic_model_version,
data_snapshot: components.data_snapshot,
},
opts.ttlSeconds,
);
}
async invalidateDataset(tenantId: string, datasetId: string): Promise<number> {
const victims = (await this.entries(tenantId)).filter((e) => e.dataset_id === datasetId);
await this.remove(victims.map((v) => v.key));
return victims.length;
}
async invalidateMetric(tenantId: string, metricId: string): Promise<number> {
const victims = (await this.entries(tenantId)).filter((e) => e.metric_ids.includes(metricId));
await this.remove(victims.map((v) => v.key));
return victims.length;
}
async invalidateTenant(tenantId: string): Promise<number> {
const victims = await this.entries(tenantId);
await this.remove(victims.map((v) => v.key));
return victims.length;
}
}
export class InMemoryResultCache extends BaseResultCache {
readonly provider = 'memory';
private readonly store = new Map<string, CachedResult>();
protected async read(key: string): Promise<CachedResult | undefined> {
return this.store.get(key);
}
protected async write(entry: CachedResult): Promise<void> {
this.store.set(entry.key, entry);
}
protected async entries(tenantId: string): Promise<CachedResult[]> {
const prefix = tenantKeyPrefix(tenantId);
return [...this.store.values()].filter((e) => e.key.startsWith(prefix));
}
protected async remove(keys: string[]): Promise<void> {
for (const k of keys) this.store.delete(k);
}
/** Test/observability affordance. Never used to bypass the tenant check. */
get size(): number {
return this.store.size;
}
}
/**
* The minimum a Valkey/Redis client must offer. Taken as an interface so this
* module adds no dependency and no CVE surface — the same reason BI-P005's
* Arrow writer is hand-written.
*/
export interface ValkeyLikeClient {
get(key: string): Promise<string | null>;
set(key: string, value: string, opts: { EX: number }): Promise<unknown>;
del(keys: string[]): Promise<unknown>;
/** Cursor-based scan. A blocking KEYS on a shared Valkey is an outage. */
scan(cursor: string, opts: { MATCH: string; COUNT: number }): Promise<{ cursor: string; keys: string[] }>;
}
export class ValkeyResultCache extends BaseResultCache {
readonly provider = 'valkey';
constructor(
private readonly client: ValkeyLikeClient,
now: () => number = Date.now,
) {
super(now);
}
protected async read(key: string): Promise<CachedResult | undefined> {
const raw = await this.client.get(key);
if (raw === null) return undefined;
try {
return JSON.parse(raw) as CachedResult;
} catch {
// A corrupt entry is a miss, not a crash — but it is also removed, so a
// permanently unparseable key cannot become a permanent cache miss that
// nobody notices.
await this.client.del([key]);
return undefined;
}
}
protected async write(entry: CachedResult, ttlSeconds: number): Promise<void> {
// The TTL is set on the STORE as well as recorded in the entry. Relying on
// the recorded timestamp alone leaves expired results occupying memory
// forever on a busy tenant.
await this.client.set(entry.key, JSON.stringify(entry), { EX: Math.ceil(ttlSeconds) });
}
protected async entries(tenantId: string): Promise<CachedResult[]> {
const prefix = tenantKeyPrefix(tenantId);
const out: CachedResult[] = [];
let cursor = '0';
do {
const page = await this.client.scan(cursor, { MATCH: `${prefix}*`, COUNT: 500 });
cursor = page.cursor;
for (const key of page.keys) {
const entry = await this.read(key);
// Defence in depth: SCAN MATCH is a glob, and a glob is a naming
// convention. Confirm against the entry's own tenant id.
if (entry && entry.tenant_id === tenantId) out.push(entry);
}
} while (cursor !== '0');
return out;
}
protected async remove(keys: string[]): Promise<void> {
if (keys.length) await this.client.del(keys);
}
}
-233
View File
@@ -1,233 +0,0 @@
/**
* src/analytics/clickhouse-analytics.ts
* ======================================
* ClickHouse-backed Analytics capability (Master-DoD §10 Analytics:
* ClickHouse, tenant isolation, dataset/event ingest, query limits, metric
* query capability, retention).
*
* LEGAL BOUNDARY (absolute): this module is a GENERIC analytics adapter for
* 0pt capability events/dataset metrics. It has NO connection to, and MUST
* NEVER be pointed at, the b0ts ClickHouse pipelines (Ratsit/person-PII —
* separate legal case) or any quarantined market='sverige'/'norge' market
* data (written DPIA prohibition). Nothing here reads services/scrapers/*.
*
* Tenant isolation model:
* - every table carries a `tenant_id` column;
* - EVERY query built by this service injects `tenant_id = {tenant}` as a
* parameterized predicate — callers cannot omit it;
* - callers NEVER pass raw SQL: the query surface is a closed metric-query
* DSL (metric + optional group-by + time range) compiled here, which is
* what makes the injection guarantee enforceable.
*
* Query limits (§10): every SELECT runs with readonly=1,
* max_execution_time, max_result_rows — enforced via ClickHouse settings on
* the HTTP interface.
*
* Retention: tables are created WITH TTL (event_time + INTERVAL n DAY).
*/
import { SiaxError, siaxErrorCodeForUpstreamStatus } from "../platform/errors";
export interface ClickHouseAnalyticsOptions {
baseUrl: string;
/** "user:password" — from env/secret ref. */
basicAuth?: string;
database?: string;
timeoutMs?: number;
/** SELECT limits (§10 query limits). */
maxExecutionTimeSec?: number;
maxResultRows?: number;
}
export interface AnalyticsEvent {
tenant_id: string;
dataset_id: string;
metric: string;
value: number;
/** ISO timestamp; defaults to now. */
event_time?: string;
dimensions?: Record<string, string>;
}
export interface MetricQuery {
tenant_id: string;
dataset_id?: string;
metric: string;
aggregate: "sum" | "avg" | "min" | "max" | "count";
/** Group by one dimension key (validated identifier). */
group_by?: string;
from_time?: string;
to_time?: string;
/** Row limit; clamped to maxResultRows. */
limit?: number;
}
export interface MetricQueryRow {
group?: string;
value: number;
}
const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
export class ClickHouseAnalytics {
private readonly baseUrl: string;
private readonly authHeader?: string;
private readonly database: string;
private readonly timeoutMs: number;
private readonly maxExecutionTimeSec: number;
private readonly maxResultRows: number;
constructor(opts: ClickHouseAnalyticsOptions) {
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString("base64")}` : undefined;
this.database = opts.database ?? "opt_analytics";
this.timeoutMs = opts.timeoutMs ?? 30_000;
this.maxExecutionTimeSec = opts.maxExecutionTimeSec ?? 10;
this.maxResultRows = opts.maxResultRows ?? 10_000;
}
/** Create the events table (idempotent) with retention TTL (§10 retention). */
async ensureSchema(retentionDays = 90): Promise<void> {
await this.exec(`CREATE DATABASE IF NOT EXISTS ${this.database}`);
await this.exec(
`CREATE TABLE IF NOT EXISTS ${this.database}.opt_metric_events (
tenant_id LowCardinality(String),
dataset_id String,
metric LowCardinality(String),
value Float64,
event_time DateTime64(3, 'UTC'),
dimensions Map(String, String)
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(event_time)
ORDER BY (tenant_id, metric, dataset_id, event_time)
TTL toDateTime(event_time) + INTERVAL ${Math.floor(retentionDays)} DAY`
);
}
/** Ingest events (JSONEachRow). tenant_id is required per event. */
async ingest(events: AnalyticsEvent[]): Promise<{ ingested: number }> {
if (events.length === 0) return { ingested: 0 };
for (const e of events) {
if (!e.tenant_id?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "every analytics event needs tenant_id");
}
if (!Number.isFinite(e.value)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `metric value for "${e.metric}" must be finite`);
}
}
const rows = events
.map((e) =>
JSON.stringify({
tenant_id: e.tenant_id,
dataset_id: e.dataset_id,
metric: e.metric,
value: e.value,
event_time: (e.event_time ?? new Date().toISOString()).replace("T", " ").replace(/Z$/, ""),
dimensions: e.dimensions ?? {},
})
)
.join("\n");
await this.exec(`INSERT INTO ${this.database}.opt_metric_events FORMAT JSONEachRow`, rows);
return { ingested: events.length };
}
/** Closed metric-query DSL — compiled with a FORCED tenant predicate. */
async queryMetric(q: MetricQuery): Promise<MetricQueryRow[]> {
if (!q.tenant_id?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant_id is required on every metric query");
}
if (q.group_by !== undefined && !IDENT_RE.test(q.group_by)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `invalid group_by identifier`);
}
const agg =
q.aggregate === "count" ? "count()" : `${q.aggregate}(value)`;
const groupExpr = q.group_by ? `dimensions['${q.group_by}']` : undefined;
const limit = Math.min(q.limit ?? 1000, this.maxResultRows);
// Parameterized query — values travel as HTTP params, never spliced.
const conditions = ["tenant_id = {tenant:String}", "metric = {metric:String}"];
const params: Record<string, string> = { param_tenant: q.tenant_id, param_metric: q.metric };
if (q.dataset_id) {
conditions.push("dataset_id = {dataset:String}");
params.param_dataset = q.dataset_id;
}
if (q.from_time) {
conditions.push("event_time >= parseDateTime64BestEffort({fromTime:String})");
params.param_fromTime = q.from_time;
}
if (q.to_time) {
conditions.push("event_time < parseDateTime64BestEffort({toTime:String})");
params.param_toTime = q.to_time;
}
const sql =
`SELECT ${groupExpr ? `${groupExpr} AS grp, ` : ""}${agg} AS value ` +
`FROM ${this.database}.opt_metric_events ` +
`WHERE ${conditions.join(" AND ")} ` +
(groupExpr ? `GROUP BY grp ORDER BY value DESC ` : "") +
`LIMIT ${limit} FORMAT JSON`;
const json = (await this.exec(sql, undefined, {
readonly: "1",
max_execution_time: String(this.maxExecutionTimeSec),
max_result_rows: String(this.maxResultRows),
...params,
})) as { data?: { grp?: string; value: number | string }[] };
return (json?.data ?? []).map((r) => ({
...(r.grp !== undefined ? { group: r.grp } : {}),
value: Number(r.value),
}));
}
async health(): Promise<boolean> {
try {
await this.exec("SELECT 1 FORMAT JSON");
return true;
} catch {
return false;
}
}
// -----------------------------------------------------------------------
private async exec(
sql: string,
body?: string,
settings?: Record<string, string>
): Promise<unknown> {
const url = new URL(this.baseUrl);
url.searchParams.set("query", sql);
for (const [k, v] of Object.entries(settings ?? {})) url.searchParams.set(k, v);
const headers: Record<string, string> = {};
if (this.authHeader) headers["Authorization"] = this.authHeader;
let res: Response;
try {
res = await fetch(url.toString(), {
method: "POST",
headers,
body: body ?? "",
signal: AbortSignal.timeout(this.timeoutMs),
});
} catch (cause) {
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "clickhouse", "clickhouse unreachable", { cause });
}
const text = await res.text();
if (!res.ok) {
// ClickHouse error text can include query fragments — keep only the code.
const code = /Code: (\d+)/.exec(text)?.[1] ?? String(res.status);
throw new SiaxError(
siaxErrorCodeForUpstreamStatus(res.status),
"clickhouse",
`query failed (CH code ${code})`
);
}
if (!text) return undefined;
try {
return JSON.parse(text);
} catch {
return text;
}
}
}
@@ -1,277 +0,0 @@
/**
* src/analytics/contract/compile-clickhouse.ts
* =============================================
* BI-P016, compile target 1 of 2: the canonical `AnalyticsQueryRequest`
* becomes tenant-forced ClickHouse SQL.
*
* The BI-P011 guarantee is repeated here VERBATIM and by construction:
*
* * `FORCED_TENANT_PREDICATE` is condition[0] with no branch that can skip
* it, and the tenant value comes from the verified identity handed in by
* the engine — this function has no way to read one from a request,
* because `AnalyticsQueryRequest` has no tenant field.
* * every caller VALUE is a `param_*` binding; `sql` never contains one.
* * every caller NAME has already been resolved through the catalog
* (`resolveAnalyticsQuery`), and the resolved physical name is validated
* as an identifier a second time before it reaches the string.
*
* tests/analytics/query-request-tenant-forcing.test.ts asserts the predicate
* survives every request shape this compiler accepts, by ENUMERATING the
* shapes rather than spot-checking two of them.
*/
import { SiaxError } from '../../platform/errors';
import { assertSafeIdentifier, FORCED_TENANT_PREDICATE, type CompiledQuery } from '../engine/query-compiler';
import type { AnalyticsTable } from '../engine/schema';
import type { ResolvedQuery, TimeGrain } from './query-request';
import type { FilterOperator } from './query-request';
/** Grain -> ClickHouse truncation function. A closed map, never caller text. */
const GRAIN_FN: Record<TimeGrain, string> = {
hour: 'toStartOfHour',
day: 'toStartOfDay',
week: 'toStartOfWeek',
month: 'toStartOfMonth',
quarter: 'toStartOfQuarter',
year: 'toStartOfYear',
};
/**
* Aggregation -> conditional-aggregate template. `count_distinct` uses
* `uniqExactIf` so a multi-metric request stays one scan instead of N.
*
* The argument is the WHOLE per-metric predicate, not just the metric-key
* comparison, because a metric definition can carry its own filters (BI-P028
* `MetricSpec.filters`) and those belong INSIDE this metric's `If` — one
* request may carry two metrics that exclude different rows.
*/
const AGG_IF: Record<string, (predicate: string) => string> = {
sum: (p) => `sumIf(value, ${p})`,
avg: (p) => `avgIf(value, ${p})`,
min: (p) => `minIf(value, ${p})`,
max: (p) => `maxIf(value, ${p})`,
count: (p) => `countIf(${p})`,
count_distinct: (p) => `uniqExactIf(event_id, ${p})`,
};
export interface ClickHouseCompileOptions {
/** From the VERIFIED CL0UD identity. Never from a request body. */
tenant_id: string;
project_id?: string;
database: string;
table?: AnalyticsTable;
/** BI-P012 ceiling; `limit` is clamped to it, never raised by it. */
maxResultRows: number;
}
export interface CompiledAnalyticsQuery extends CompiledQuery {
/** Column alias -> caller-facing metric name, so the caller never sees `m0`. */
metricAliases: Record<string, string>;
/** Column alias -> caller-facing dimension name. */
dimensionAliases: Record<string, string>;
effectiveLimit: number;
}
export function compileRequestToClickHouse(
resolved: ResolvedQuery,
opts: ClickHouseCompileOptions,
): CompiledAnalyticsQuery {
if (!opts.tenant_id || !opts.tenant_id.trim()) {
// Fail closed. A blank tenant must never compile to "no predicate".
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'tenant_id is required on every analytics query');
}
assertSafeIdentifier(opts.database, 'database');
const table: AnalyticsTable = opts.table ?? 'opt_analytics_event';
assertSafeIdentifier(table, 'table');
const params: Record<string, string> = { param_tenant: opts.tenant_id };
// ── the forced predicate. First condition, always, no branch. ─────────
const conditions: string[] = [FORCED_TENANT_PREDICATE];
if (opts.project_id) {
conditions.push('project_id = {project:String}');
params.param_project = opts.project_id;
}
conditions.push('dataset_id = {dataset:String}');
params.param_dataset = resolved.dataset_id;
// ── metrics: bound keys, compiler-generated aliases ───────────────────
const selectParts: string[] = [];
const groupParts: string[] = [];
const dimensionAliases: Record<string, string> = {};
const metricAliases: Record<string, string> = {};
const metricKeyParams: string[] = [];
resolved.dimensions.forEach((d, i) => {
assertSafeIdentifier(d.field_name, 'dimension');
const key = `d${i}`;
const alias = `dim_${i}`;
selectParts.push(`dim_values[indexOf(dim_names, {${key}:String})] AS ${alias}`);
groupParts.push(alias);
params[`param_${key}`] = d.field_name;
dimensionAliases[alias] = d.name;
});
// ── time grain: a GROUP BY bucket, from the closed GRAIN_FN map ───────
const grain = resolved.request.timeRange?.grain;
if (grain) {
const timeCol = resolved.timeDimension ?? 'event_time';
assertSafeIdentifier(timeCol, 'time dimension');
const alias = 'time_bucket';
selectParts.push(`${GRAIN_FN[grain]}(${timeCol}) AS ${alias}`);
groupParts.push(alias);
dimensionAliases[alias] = resolved.request.timeRange?.dimension ?? '__time';
}
resolved.metrics.forEach((m, i) => {
const key = `m${i}`;
const alias = `metric_${i}`;
const template = AGG_IF[m.aggregation];
if (!template) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `unsupported aggregation "${m.aggregation}"`);
}
// The metric's own definition filters (BI-P028) join the metric-key
// comparison inside THIS metric's `If`. Bound, never spliced, and scoped
// to this metric — putting them in the shared WHERE would apply one
// metric's meaning to every other metric in the same request.
const metricConditions = [`metric = {${key}:String}`];
(m.definition_filters ?? []).forEach((f, j) => {
assertSafeIdentifier(f.field_name, 'metric definition filter dimension');
const nameKey = `mf${i}_${j}`;
params[`param_${nameKey}`] = f.field_name;
const lhs = `dim_values[indexOf(dim_names, {${nameKey}:String})]`;
metricConditions.push(renderFilter(lhs, nameKey, f.operator, [...f.values], `${i}_${j}m`, params));
});
selectParts.push(`${template(metricConditions.join(' AND '))} AS ${alias}`);
params[`param_${key}`] = m.event_metric_key;
metricKeyParams.push(`{${key}:String}`);
metricAliases[alias] = m.name;
});
// Restrict the SCAN to the requested metric keys — a correctness AND a cost
// measure: without it every metric row in the dataset is read to be thrown
// away by the `If` conditions.
conditions.push(`metric IN (${metricKeyParams.join(', ')})`);
// ── time range: bound instants, half-open ─────────────────────────────
const tr = resolved.request.timeRange;
if (tr?.from || tr?.to) {
const timeCol = resolved.timeDimension ?? 'event_time';
assertSafeIdentifier(timeCol, 'time dimension');
if (tr.from) {
conditions.push(`${timeCol} >= parseDateTime64BestEffort({fromTime:String})`);
params.param_fromTime = tr.from;
}
if (tr.to) {
conditions.push(`${timeCol} < parseDateTime64BestEffort({toTime:String})`);
params.param_toTime = tr.to;
}
}
// ── filters: closed operator set, values always bound ─────────────────
resolved.filters.forEach((entry, i) => {
assertSafeIdentifier(entry.dimension.field_name, 'dimension');
const nameKey = `fn${i}`;
params[`param_${nameKey}`] = entry.dimension.field_name;
const lhs = `dim_values[indexOf(dim_names, {${nameKey}:String})]`;
conditions.push(
renderFilter(lhs, nameKey, entry.filter.operator, entry.filter.values ?? [], String(i), params),
);
});
// ── order by: resolved back onto compiler-generated aliases only ──────
const aliasForName = new Map<string, string>();
for (const [alias, name] of Object.entries(dimensionAliases)) aliasForName.set(name, alias);
for (const [alias, name] of Object.entries(metricAliases)) aliasForName.set(name, alias);
const orderParts: string[] = [];
for (const o of resolved.request.orderBy ?? []) {
const alias = aliasForName.get(o.ref);
if (!alias) {
// Cannot happen after parseAnalyticsQueryRequest, which already refuses
// an orderBy that is not selected. Kept as a hard stop rather than a
// silent skip: a guard that quietly does nothing is how a bypass hides.
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `orderBy "${o.ref}" is not selected`);
}
orderParts.push(`${alias} ${o.direction === 'asc' ? 'ASC' : 'DESC'}`);
}
const requested = resolved.request.limit ?? 1000;
const effectiveLimit = Math.max(1, Math.min(Math.floor(requested), opts.maxResultRows));
const sql =
`SELECT ${selectParts.join(', ')} ` +
`FROM ${opts.database}.${table} ` +
`WHERE ${conditions.join(' AND ')}` +
(groupParts.length ? ` GROUP BY ${groupParts.join(', ')}` : '') +
(orderParts.length ? ` ORDER BY ${orderParts.join(', ')}` : '') +
` LIMIT ${effectiveLimit} FORMAT JSON`;
return {
sql,
params,
forcedTenantPredicate: FORCED_TENANT_PREDICATE,
table,
metricAliases,
dimensionAliases,
effectiveLimit,
};
}
function renderFilter(
lhs: string,
nameKey: string,
operator: FilterOperator,
values: string[],
/**
* Uniquifies this filter's bound-value parameter names. A STRING, not a
* number, because request filters and per-metric definition filters share
* one parameter map: `0` and `0_0m` must not collide, and two collided
* bindings would silently make one filter win over the other.
*/
index: string,
params: Record<string, string>,
): string {
const bind = (v: string, suffix: string): string => {
const key = `fv${index}${suffix}`;
params[`param_${key}`] = v;
return `{${key}:String}`;
};
switch (operator) {
case 'eq':
return `${lhs} = ${bind(values[0], '')}`;
case 'ne':
return `${lhs} != ${bind(values[0], '')}`;
case 'lt':
return `${lhs} < ${bind(values[0], '')}`;
case 'lte':
return `${lhs} <= ${bind(values[0], '')}`;
case 'gt':
return `${lhs} > ${bind(values[0], '')}`;
case 'gte':
return `${lhs} >= ${bind(values[0], '')}`;
case 'contains':
// `position(haystack, needle) > 0` keeps the needle a BOUND VALUE.
// A LIKE with a concatenated pattern would make it SQL text.
return `position(${lhs}, ${bind(values[0], '')}) > 0`;
case 'in':
case 'not_in': {
const bound = values.map((v, i) => bind(v, `_${i}`));
return `${lhs} ${operator === 'in' ? 'IN' : 'NOT IN'} (${bound.join(', ')})`;
}
case 'is_null':
// Dimension values live in a paired-array map; an absent key yields ''
// rather than NULL, so "is null" means "the key is not present". The
// key itself is the already-bound `param_fn<i>` — no new binding, and
// certainly no spliced identifier.
return `NOT has(dim_names, {${nameKey}:String})`;
case 'is_not_null':
return `has(dim_names, {${nameKey}:String})`;
default: {
const _never: never = operator;
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
`unsupported filter operator ${String(_never)}`,
);
}
}
}
-169
View File
@@ -1,169 +0,0 @@
/**
* src/analytics/contract/compile-semantic.ts
* ===========================================
* BI-P016, compile target 2 of 2 — and the thing that makes BI-P016's DoD
* ("same request can compile to ClickHouse/semantic engine without consumer
* rewrite") a testable claim rather than a design intention.
*
* A `SemanticQuerySpec` is the engine-neutral form a semantic layer consumes.
* It is deliberately shaped like MetricFlow's query interface (metrics /
* group-by / where / order / limit / time-constraint) so BI-P029's
* `MetricFlowProvider` can execute it without an adapter, but it names
* nothing MetricFlow-specific: swapping MetricFlow for Cube or a hand-rolled
* compiler changes this file's CONSUMER, not this file, and never the
* product API.
*
* The `where` clauses here are STRUCTURED, not SQL strings. A semantic layer
* that accepts SQL predicate text (MetricFlow's `--where` does) would put a
* raw-SQL hole behind the closed DSL — so the spec carries operator+values
* and the provider renders them itself under its own escaping rules.
*/
import type { FilterOperator, ResolvedQuery, TimeGrain } from './query-request';
export interface SemanticMetricRef {
/** Canonical SIAX metric id — stable across semantic-engine replacement. */
metric_id: string;
name: string;
/**
* The metric DEFINITION's own filters, carried through so the semantic
* target computes the same number as the ClickHouse target. Dropping them
* on one side and not the other is how one canonical metric id comes to
* mean two different things — the divergence BI-P029's DoD is written to
* catch. Structured, like every other filter here: never predicate text.
*/
definition_filters?: readonly SemanticWhere[];
}
export interface SemanticGroupBy {
dimension_id: string;
name: string;
/** Set when this group-by is a time bucket rather than a categorical one. */
grain?: TimeGrain;
}
export interface SemanticWhere {
dimension_id: string;
name: string;
operator: FilterOperator;
values: string[];
}
export interface SemanticOrderBy {
ref: string;
direction: 'asc' | 'desc';
}
export interface SemanticTimeConstraint {
/** Inclusive lower bound. */
start?: string;
/** EXCLUSIVE upper bound — matched to the ClickHouse target exactly. */
end?: string;
dimension?: string;
}
export interface SemanticQuerySpec {
dataset_id: string;
semantic_model_version?: number;
metrics: SemanticMetricRef[];
groupBy: SemanticGroupBy[];
where: SemanticWhere[];
orderBy: SemanticOrderBy[];
limit: number;
timeConstraint?: SemanticTimeConstraint;
format: 'json' | 'arrow_ipc';
}
export function compileRequestToSemantic(resolved: ResolvedQuery): SemanticQuerySpec {
const groupBy: SemanticGroupBy[] = resolved.dimensions.map((d) => ({
dimension_id: d.dimension_id,
name: d.name,
}));
const grain = resolved.request.timeRange?.grain;
if (grain) {
groupBy.push({
dimension_id: resolved.request.timeRange?.dimension ?? '__time',
name: resolved.request.timeRange?.dimension ?? '__time',
grain,
});
}
return {
dataset_id: resolved.dataset_id,
semantic_model_version: resolved.semantic_model_version,
metrics: resolved.metrics.map((m) => ({
metric_id: m.metric_id,
name: m.name,
...(m.definition_filters?.length
? {
definition_filters: m.definition_filters.map((f) => ({
// Already resolved onto the physical key; the dimension id is
// the same value here because the definition names a field, not
// a caller-supplied alias.
dimension_id: f.field_name,
name: f.field_name,
operator: f.operator,
values: [...f.values],
})),
}
: {}),
})),
groupBy,
where: resolved.filters.map((f) => ({
dimension_id: f.dimension.dimension_id,
name: f.dimension.name,
operator: f.filter.operator,
values: f.filter.values ?? [],
})),
orderBy: (resolved.request.orderBy ?? []).map((o) => ({ ref: o.ref, direction: o.direction })),
limit: resolved.request.limit ?? 1000,
timeConstraint:
resolved.request.timeRange && (resolved.request.timeRange.from || resolved.request.timeRange.to)
? {
start: resolved.request.timeRange.from,
end: resolved.request.timeRange.to,
dimension: resolved.request.timeRange.dimension,
}
: undefined,
format: resolved.request.format ?? 'json',
};
}
/**
* The comparable SHAPE of a compiled query, target-independent.
*
* BI-P016's DoD is about semantic equivalence, and the honest way to test
* that is to project both targets onto the same tuple and demand equality —
* not to eyeball two strings. `tests/analytics/query-request-contract.test.ts`
* builds this from the ClickHouse SQL by PARSING the compiled artefact, so a
* compiler that quietly drops a filter fails the comparison.
*/
export interface QueryShape {
dataset_id: string;
metrics: string[];
dimensions: string[];
filters: Array<{ dimension: string; operator: FilterOperator; values: string[] }>;
order: string[];
limit: number;
timeFrom?: string;
timeTo?: string;
grain?: TimeGrain;
}
export function shapeOfSemanticSpec(spec: SemanticQuerySpec): QueryShape {
const timeBucket = spec.groupBy.find((g) => g.grain);
return {
dataset_id: spec.dataset_id,
metrics: spec.metrics.map((m) => m.name).sort(),
dimensions: spec.groupBy
.filter((g) => !g.grain)
.map((g) => g.name)
.sort(),
filters: spec.where
.map((w) => ({ dimension: w.name, operator: w.operator, values: [...w.values] }))
.sort((a, b) => (a.dimension + a.operator).localeCompare(b.dimension + b.operator)),
order: spec.orderBy.map((o) => `${o.ref}:${o.direction}`),
limit: spec.limit,
timeFrom: spec.timeConstraint?.start,
timeTo: spec.timeConstraint?.end,
grain: timeBucket?.grain,
};
}
File diff suppressed because it is too large Load Diff
-415
View File
@@ -1,415 +0,0 @@
/**
* src/analytics/cost/query-budget.ts
* ===================================
* BI-P021 — QUERY COST / BUDGET.
*
* ── SAY THE HONEST THING FIRST ────────────────────────────────────────────
* A budget checked once before execution and never again bounds NOTHING. The
* estimate is a planner's guess; a query that scans ten times its estimate
* runs to completion regardless, and the budget discovers this after the money
* is spent. Every "cost control" that consists only of a pre-flight check is
* an accounting feature wearing a safety feature's name.
*
* ClickHouse's own `max_rows_to_read` (BI-P012) DOES stop a query mid-flight —
* but it bounds ONE query. It cannot express "this tenant may scan 10 billion
* rows per hour across all its queries", because it has no idea what the
* tenant's other queries did. That window is what a budget is for, and it is
* exactly the thing a per-query setting cannot enforce.
*
* So this module has three parts, and only the second one is a control:
*
* 1. ADMISSION — estimate vs. remaining window. Rejects the obviously
* unaffordable before it starts. Cheap, and insufficient.
* 2. IN-FLIGHT — polls the engine's live `read_rows`/`read_bytes` counters
* for the running query and CANCELS it (via BI-P019, with
* verification) the moment window spend would be exceeded.
* THIS is what makes the budget real.
* 3. ACCOUNTING — settles the actual cost into a ledger the control plane
* reads: CL0UD quotas, AUD0 usage events, B00K accounting.
*
* If part 2 is disabled (`enforceInFlight: false`), `describeEnforcement()`
* says so in plain words, and the admission-only posture is reported as
* "advisory". A control that does not control should say which one it is.
*
* ── THE CAVEAT THAT THE LIVE RUN MEASURED ────────────────────────────────
* In-flight enforcement is granular to the poll interval, so a query can
* OVERSHOOT its budget between polls — and on a columnar engine the overshoot
* is large. Measured against ClickHouse 24.8.14.39 with a 1,000,000-row window
* and a 100ms poll: the query was cancelled at 153,318,696 rows read, 55ms in.
* A 153x overshoot. See evidence/bi-p019-p021/cancellation-and-budget.json,
* which is regenerated by the live suite — the figure is machine-dependent and
* moves between runs (an earlier run on the same box recorded 131M / 130x).
* Do not quote a specific multiple; quote the SHAPE.
*
* That shape is still a bound — the same query, unwatched, read 4,227,318,261
* rows before it was stopped in the BI-P019 case — but it is a bound of the
* form "within roughly one poll interval of engine throughput", not "at
* exactly the budget". Anyone sizing a budget must size it for that, and
* anyone quoting this as a hard cap is wrong. Shortening the interval narrows
* the overshoot and costs a `system.processes` read per poll per running
* query.
*/
import { SiaxError } from '../../platform/errors';
import {
cancelAndVerify,
type CancellationOutcome,
type EngineProcessControl,
} from '../execution/cancellation';
/** The cost axes BI-P021 names. */
export interface QueryCost {
rows_scanned: number;
bytes_scanned: number;
execution_ms: number;
engine: string;
/** Bytes read from object storage, when the engine distinguishes it. */
storage_read_bytes?: number;
}
/**
* Weights turning raw counters into the single `cost_units` figure BI-P018
* records and B00K bills.
*
* The defaults are deliberately dominated by BYTES, not rows: on a columnar
* engine a billion-row scan of one narrow column is cheap and a
* hundred-million-row scan of a wide one is not, so a rows-weighted unit would
* bill the wrong query.
*/
export interface CostModel {
unitsPerBillionRows: number;
unitsPerGigabyteScanned: number;
unitsPerSecond: number;
unitsPerGigabyteStorageRead: number;
}
export const DEFAULT_COST_MODEL: CostModel = {
unitsPerBillionRows: 1,
unitsPerGigabyteScanned: 10,
unitsPerSecond: 2,
unitsPerGigabyteStorageRead: 15,
};
export function costUnits(cost: QueryCost, model: CostModel = DEFAULT_COST_MODEL): number {
const units =
(cost.rows_scanned / 1e9) * model.unitsPerBillionRows +
(cost.bytes_scanned / 2 ** 30) * model.unitsPerGigabyteScanned +
(cost.execution_ms / 1000) * model.unitsPerSecond +
((cost.storage_read_bytes ?? 0) / 2 ** 30) * model.unitsPerGigabyteStorageRead;
// Rounded to six places so the same cost always serialises identically;
// float noise in a billing figure produces support tickets.
return Math.round(units * 1e6) / 1e6;
}
/** A tenant's allowance over a rolling window. Issued by CL0UD entitlements. */
export interface QueryBudget {
windowMs: number;
maxRowsScanned: number;
maxBytesScanned: number;
maxCostUnits: number;
/** What to do when the window is exhausted. */
onExhausted: 'reject' | 'throttle';
/** For `throttle`: queries are delayed by this much instead of refused. */
throttleDelayMs?: number;
}
export const DEFAULT_QUERY_BUDGET: QueryBudget = {
windowMs: 60 * 60 * 1000,
maxRowsScanned: 50_000_000_000,
maxBytesScanned: 2 * 2 ** 40,
maxCostUnits: 10_000,
onExhausted: 'reject',
};
interface LedgerEntry {
at: number;
rows: number;
bytes: number;
units: number;
}
/** Where settled cost goes. AUD0/B00K/CL0UD sit behind this. */
export interface UsageLedgerSink {
record(entry: {
tenant_id: string;
project_id?: string;
principal_id: string;
query_id: string;
cost: QueryCost;
cost_units: number;
/** True when the query was stopped by the budget rather than by the user. */
terminated_by_budget: boolean;
at: string;
}): Promise<void> | void;
}
export interface WindowSpend {
rows_scanned: number;
bytes_scanned: number;
cost_units: number;
queries: number;
window_started_at: string;
}
/**
* In-memory rolling window per tenant.
*
* Explicitly NOT the durable ledger — this is one process's view, and a
* multi-replica deployment needs the shared counter (Valkey or the CL0UD quota
* service) behind `SharedWindowStore` for the budget to bind across replicas.
* Stated rather than implied: with N replicas and no shared store, a tenant
* can spend N times its budget. `describeEnforcement()` reports this.
*/
export interface SharedWindowStore {
/** Atomically add to the tenant's window and return the new totals. */
add(
tenantId: string,
entry: { rows: number; bytes: number; units: number; windowMs: number },
): Promise<WindowSpend>;
get(tenantId: string): Promise<WindowSpend>;
}
export class InMemoryWindowStore implements SharedWindowStore {
private readonly entries = new Map<string, LedgerEntry[]>();
constructor(private readonly now: () => number = Date.now) {}
private prune(tenantId: string, windowMs: number): LedgerEntry[] {
const cutoff = this.now() - windowMs;
const kept = (this.entries.get(tenantId) ?? []).filter((e) => e.at >= cutoff);
this.entries.set(tenantId, kept);
return kept;
}
async add(
tenantId: string,
entry: { rows: number; bytes: number; units: number; windowMs: number },
): Promise<WindowSpend> {
const kept = this.prune(tenantId, entry.windowMs);
kept.push({ at: this.now(), rows: entry.rows, bytes: entry.bytes, units: entry.units });
this.entries.set(tenantId, kept);
return this.totals(kept, entry.windowMs);
}
async get(tenantId: string, windowMs = DEFAULT_QUERY_BUDGET.windowMs): Promise<WindowSpend> {
return this.totals(this.prune(tenantId, windowMs), windowMs);
}
private totals(entries: LedgerEntry[], windowMs: number): WindowSpend {
return {
rows_scanned: entries.reduce((a, e) => a + e.rows, 0),
bytes_scanned: entries.reduce((a, e) => a + e.bytes, 0),
cost_units: entries.reduce((a, e) => a + e.units, 0),
queries: entries.length,
window_started_at: new Date(this.now() - windowMs).toISOString(),
};
}
}
export interface BudgetEnforcerOptions {
budget: QueryBudget;
store: SharedWindowStore;
ledger: UsageLedgerSink;
control?: EngineProcessControl;
costModel?: CostModel;
/** The control. Off means admission-only, and `describeEnforcement` says so. */
enforceInFlight?: boolean;
pollIntervalMs?: number;
/** True when `store` is shared across replicas. Affects the honest description. */
storeIsShared?: boolean;
now?: () => number;
sleep?: (ms: number) => Promise<void>;
}
export interface AdmissionDecision {
admitted: boolean;
reason?: string;
/** For `throttle`: how long the caller must wait first. */
delay_ms?: number;
remaining: { rows: number; bytes: number; units: number };
}
export interface InFlightOutcome {
/** True when the enforcer stopped the query. */
terminated: boolean;
reason?: 'rows' | 'bytes' | 'units';
/** Present when it terminated: the verified cancellation. */
cancellation?: CancellationOutcome;
observed: { rows_read: number; bytes_read: number; elapsed_ms: number };
polls: number;
}
export class QueryBudgetEnforcer {
private readonly opts: Required<
Pick<BudgetEnforcerOptions, 'enforceInFlight' | 'pollIntervalMs' | 'storeIsShared'>
> &
BudgetEnforcerOptions;
private readonly now: () => number;
private readonly sleep: (ms: number) => Promise<void>;
constructor(options: BudgetEnforcerOptions) {
this.opts = {
enforceInFlight: options.enforceInFlight ?? true,
pollIntervalMs: options.pollIntervalMs ?? 200,
storeIsShared: options.storeIsShared ?? false,
...options,
};
this.now = options.now ?? Date.now;
this.sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
if (this.opts.enforceInFlight && !this.opts.control) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.cost',
'in-flight budget enforcement requires an EngineProcessControl; ' +
'construct with enforceInFlight:false to run admission-only and be honest about it',
);
}
}
/**
* Exactly what this enforcer does and does not bound, in words an operator
* can paste into an incident review. Returned by the analytics health
* endpoint so the posture is visible without reading this file.
*/
describeEnforcement(): {
admission: string;
in_flight: string;
across_replicas: string;
binding: boolean;
} {
return {
admission: 'estimate is compared to the remaining window before the query starts',
in_flight: this.opts.enforceInFlight
? `live engine counters are polled every ${this.opts.pollIntervalMs}ms and the query is cancelled ` +
'(with verification) when window spend would be exceeded'
: 'NOT ENFORCED — this budget is advisory. A query that exceeds its estimate runs to completion.',
across_replicas: this.opts.storeIsShared
? 'window spend is held in a shared store, so the budget binds across replicas'
: 'window spend is per-process — with N replicas a tenant can spend up to N times this budget',
binding: this.opts.enforceInFlight && this.opts.storeIsShared,
};
}
async admit(
tenantId: string,
estimate: { rows_to_read: number; bytes_to_read: number },
): Promise<AdmissionDecision> {
const spend = await this.opts.store.get(tenantId);
const b = this.opts.budget;
const remaining = {
rows: Math.max(0, b.maxRowsScanned - spend.rows_scanned),
bytes: Math.max(0, b.maxBytesScanned - spend.bytes_scanned),
units: Math.max(0, b.maxCostUnits - spend.cost_units),
};
const over =
estimate.rows_to_read > remaining.rows
? 'rows'
: estimate.bytes_to_read > remaining.bytes
? 'bytes'
: undefined;
if (!over) return { admitted: true, remaining };
if (b.onExhausted === 'throttle') {
return {
admitted: true,
delay_ms: b.throttleDelayMs ?? 1000,
reason: `tenant window ${over} budget exhausted; throttled`,
remaining,
};
}
return { admitted: false, reason: `tenant window ${over} budget exhausted`, remaining };
}
/**
* Watch a RUNNING query and stop it if it breaches the window.
*
* Runs concurrently with the query itself; the caller awaits both. Returns
* as soon as the query leaves the engine's process list, so a well-behaved
* query costs one extra poll.
*/
async enforceInFlight(tenantId: string, queryId: string, signal?: AbortSignal): Promise<InFlightOutcome> {
const observed = { rows_read: 0, bytes_read: 0, elapsed_ms: 0 };
if (!this.opts.enforceInFlight || !this.opts.control?.progress) {
return { terminated: false, observed, polls: 0 };
}
const control = this.opts.control;
const spendBefore = await this.opts.store.get(tenantId);
const b = this.opts.budget;
const remainingRows = Math.max(0, b.maxRowsScanned - spendBefore.rows_scanned);
const remainingBytes = Math.max(0, b.maxBytesScanned - spendBefore.bytes_scanned);
const remainingUnits = Math.max(0, b.maxCostUnits - spendBefore.cost_units);
let polls = 0;
for (;;) {
if (signal?.aborted) return { terminated: false, observed, polls };
let progress;
try {
progress = await control.progress?.(queryId);
} catch {
progress = undefined;
}
polls += 1;
if (!progress) {
// Gone from the process list: finished, or never started. Either way
// there is nothing left to bound.
return { terminated: false, observed, polls };
}
observed.rows_read = progress.rows_read;
observed.bytes_read = progress.bytes_read;
observed.elapsed_ms = progress.elapsed_ms;
const liveUnits = costUnits(
{
rows_scanned: progress.rows_read,
bytes_scanned: progress.bytes_read,
execution_ms: progress.elapsed_ms,
engine: control.engine,
},
this.opts.costModel,
);
const breach =
progress.rows_read > remainingRows
? 'rows'
: progress.bytes_read > remainingBytes
? 'bytes'
: liveUnits > remainingUnits
? 'units'
: undefined;
if (breach) {
const cancellation = await cancelAndVerify(control, queryId, { timeoutMs: 5_000 });
return { terminated: true, reason: breach, cancellation, observed, polls };
}
await this.sleep(this.opts.pollIntervalMs);
}
}
/** Settle the actual cost. Called for EVERY outcome, including failures. */
async settle(args: {
tenant_id: string;
project_id?: string;
principal_id: string;
query_id: string;
cost: QueryCost;
terminated_by_budget?: boolean;
}): Promise<{ cost_units: number; window: WindowSpend }> {
const units = costUnits(args.cost, this.opts.costModel);
const window = await this.opts.store.add(args.tenant_id, {
rows: args.cost.rows_scanned,
bytes: args.cost.bytes_scanned,
units,
windowMs: this.opts.budget.windowMs,
});
await this.opts.ledger.record({
tenant_id: args.tenant_id,
project_id: args.project_id,
principal_id: args.principal_id,
query_id: args.query_id,
cost: args.cost,
cost_units: units,
// A query the budget killed still COST what it burned before it died.
// Not charging for it is how a tenant discovers that the cheapest query
// is one that gets cancelled.
terminated_by_budget: args.terminated_by_budget ?? false,
at: new Date(this.now()).toISOString(),
});
return { cost_units: units, window };
}
}
File diff suppressed because it is too large Load Diff
@@ -1,449 +0,0 @@
/**
* src/analytics/dashboards/dashboard-release.ts
* ==============================================
* BI-P061 — DASHBOARD VERSIONING.
*
* DRAFT -> PUBLISHED -> SUPERSEDED, and the DoD: "rollback to previous
* dashboard definition".
*
* Three decisions worth stating, because each one is a bug someone would
* otherwise write:
*
* 1. ROLLBACK MINTS A NEW VERSION. It does not resurrect the old release row
* and it does not edit the published one. "We went back to v3" is then a
* fact with a timestamp (v5 = rollback_of_version 3) instead of a hole in
* the history where v4 used to be. `verifyRollback()` proves the restore is
* faithful by comparing BI-P060 canonical hashes, so a rollback that
* silently restored a different document fails loudly.
*
* 2. THE DOCUMENT IS FROZEN, THE RELEASE MOVES. sql/008 makes
* DashboardVersion rows immutable at the database. The release ledger
* (sql/010) carries the state, and its trigger allows exactly two
* transitions and freezes every other column. Un-publishing is refused:
* it is how a rollback gets faked without leaving a trace.
*
* 3. THE APPLICATION CHECK IS NOT THE GUARANTEE. `publish()` checks for an
* existing published release, and that check is a read-then-write race.
* The partial unique index in sql/010 is what actually holds under
* concurrency; the realinfra test drops it, runs the race and shows two
* published releases for one dashboard, so nobody has to take that on
* faith. This module maps the resulting constraint violation onto a
* CONFLICT rather than a 500.
*/
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import { dashboardDocumentHash, parseDashboardDocument, type DashboardDocument } from './dashboard-document';
export const DASHBOARD_RELEASE_STATES = ['draft', 'published', 'superseded'] as const;
export type DashboardReleaseState = (typeof DASHBOARD_RELEASE_STATES)[number];
/** The only transitions that exist. Everything else is a refusal, not a no-op. */
const LEGAL_TRANSITIONS: Readonly<Record<DashboardReleaseState, readonly DashboardReleaseState[]>> = {
draft: ['published'],
published: ['superseded'],
superseded: [],
};
export function isLegalTransition(from: DashboardReleaseState, to: DashboardReleaseState): boolean {
return LEGAL_TRANSITIONS[from].includes(to);
}
export interface DashboardRelease {
release_id: string;
dashboard_id: string;
dashboard_version_id: string;
tenant_id: string;
project_id: string;
version: number;
state: DashboardReleaseState;
/** BI-P060 canonical hash of the released document. */
document_hash: string;
/** Set when this release restores an earlier version. */
rollback_of_version?: number;
created_by?: string;
created_at: string;
published_at?: string;
superseded_at?: string;
superseded_by_release_id?: string;
}
/** The immutable frozen document behind a release (sql/008's DashboardVersion). */
export interface DashboardVersionRecord {
dashboard_version_id: string;
dashboard_id: string;
tenant_id: string;
project_id: string;
version: number;
layout_json: string;
layout_hash: string;
created_at: string;
created_by?: string;
}
export interface TenantScope {
tenant_id: string;
project_id: string;
}
/**
* The persistence port. Deliberately narrow, and every method is tenant-scoped
* — there is no signature that lets a caller forget the tenant.
*/
export interface DashboardReleaseStore {
/** Highest version number ever minted for this dashboard, or 0. */
maxVersion(scope: TenantScope, dashboardId: string): Promise<number>;
insertVersionAndRelease(version: DashboardVersionRecord, release: DashboardRelease): Promise<void>;
getRelease(scope: TenantScope, releaseId: string): Promise<DashboardRelease | undefined>;
getVersion(scope: TenantScope, dashboardVersionId: string): Promise<DashboardVersionRecord | undefined>;
findVersionByNumber(
scope: TenantScope,
dashboardId: string,
version: number,
): Promise<DashboardVersionRecord | undefined>;
findByState(
scope: TenantScope,
dashboardId: string,
state: DashboardReleaseState,
): Promise<DashboardRelease | undefined>;
listReleases(scope: TenantScope, dashboardId: string): Promise<DashboardRelease[]>;
/**
* Publish `releaseId` and supersede `supersedes` in ONE transaction. Both or
* neither: a supersede that lands without its publish leaves a dashboard
* with no live version, and a publish that lands without its supersede
* leaves two.
*/
publishAtomically(args: {
scope: TenantScope;
releaseId: string;
publishedAt: string;
supersedes?: { release_id: string; superseded_at: string };
}): Promise<void>;
}
function conflict(detail: string): never {
throw new SiaxError('CONFLICT', '0pt.analytics.dashboard', detail);
}
function notFound(detail: string): never {
throw new SiaxError('NOT_FOUND', '0pt.analytics.dashboard', detail);
}
function assertScope(scope: TenantScope): void {
if (!scope?.tenant_id?.trim() || !scope?.project_id?.trim()) {
throw new SiaxError(
'UNAUTHENTICATED',
'0pt.analytics.dashboard',
'dashboard releases require a verified tenant_id + project_id',
);
}
}
export interface DraftResult {
release: DashboardRelease;
version: DashboardVersionRecord;
}
/**
* The lifecycle. Stateless apart from its store and its clock; the clock is
* injectable so a test can pin timestamps instead of sleeping.
*/
export class DashboardReleaseService {
constructor(
private readonly store: DashboardReleaseStore,
private readonly now: () => Date = () => new Date(),
private readonly newId: () => string = () => crypto.randomUUID(),
) {}
/**
* Freeze a document as the next version and open a DRAFT release for it.
* The document is re-parsed here even if the caller already parsed it: what
* gets frozen must be what the model accepts, not what a caller assembled.
*/
async draft(args: {
scope: TenantScope;
dashboardId: string;
document: unknown;
createdBy?: string;
rollbackOfVersion?: number;
}): Promise<DraftResult> {
assertScope(args.scope);
const document = parseDashboardDocument(args.document);
const existingDraft = await this.store.findByState(args.scope, args.dashboardId, 'draft');
if (existingDraft) {
conflict(
`dashboard "${args.dashboardId}" already has an open draft (version ${existingDraft.version}); ` +
`publish or abandon it before opening another — two drafts race to publish and the loser's ` +
`edits vanish`,
);
}
const next = (await this.store.maxVersion(args.scope, args.dashboardId)) + 1;
const at = this.now().toISOString();
const hash = dashboardDocumentHash(document);
const version: DashboardVersionRecord = {
dashboard_version_id: this.newId(),
dashboard_id: args.dashboardId,
tenant_id: args.scope.tenant_id,
project_id: args.scope.project_id,
version: next,
layout_json: JSON.stringify(document),
layout_hash: hash,
created_at: at,
...(args.createdBy ? { created_by: args.createdBy } : {}),
};
const release: DashboardRelease = {
release_id: this.newId(),
dashboard_id: args.dashboardId,
dashboard_version_id: version.dashboard_version_id,
tenant_id: args.scope.tenant_id,
project_id: args.scope.project_id,
version: next,
state: 'draft',
document_hash: hash,
created_at: at,
...(args.createdBy ? { created_by: args.createdBy } : {}),
...(args.rollbackOfVersion ? { rollback_of_version: args.rollbackOfVersion } : {}),
};
await this.store.insertVersionAndRelease(version, release);
return { release, version };
}
/**
* DRAFT -> PUBLISHED, superseding whatever was live, in one transaction.
* The pre-check exists to return a friendly CONFLICT; the guarantee is the
* partial unique index (sql/010).
*/
async publish(args: {
scope: TenantScope;
releaseId: string;
}): Promise<{ published: DashboardRelease; superseded?: DashboardRelease }> {
assertScope(args.scope);
const release = await this.store.getRelease(args.scope, args.releaseId);
if (!release) notFound(`dashboard release "${args.releaseId}" does not exist in this tenant`);
if (release.state !== 'draft') {
conflict(
`release "${args.releaseId}" is ${release.state}, not draft — ${release.state} -> published is ` +
`not a legal transition (BI-P061)`,
);
}
const live = await this.store.findByState(args.scope, release.dashboard_id, 'published');
const at = this.now().toISOString();
await this.store.publishAtomically({
scope: args.scope,
releaseId: release.release_id,
publishedAt: at,
...(live ? { supersedes: { release_id: live.release_id, superseded_at: at } } : {}),
});
return {
published: { ...release, state: 'published', published_at: at },
...(live
? {
superseded: {
...live,
state: 'superseded',
superseded_at: at,
superseded_by_release_id: release.release_id,
},
}
: {}),
};
}
/** The release currently serving, or undefined if the dashboard has never been published. */
async live(scope: TenantScope, dashboardId: string): Promise<DashboardRelease | undefined> {
assertScope(scope);
return this.store.findByState(scope, dashboardId, 'published');
}
/** The frozen document behind a release, re-parsed on the way out. */
async documentOf(scope: TenantScope, release: DashboardRelease): Promise<DashboardDocument> {
assertScope(scope);
const version = await this.store.getVersion(scope, release.dashboard_version_id);
if (!version) notFound(`dashboard version "${release.dashboard_version_id}" is missing`);
const document = parseDashboardDocument(JSON.parse(version.layout_json));
const hash = dashboardDocumentHash(document);
if (hash !== release.document_hash) {
// Storage returned something other than what was released. Refusing is
// the only safe answer: a dashboard that renders a document nobody
// approved is worse than a dashboard that will not open.
throw new SiaxError(
'PERMANENT_FAILURE',
'0pt.analytics.dashboard',
`stored document for release "${release.release_id}" hashes to ${hash}, not the released ` +
`${release.document_hash} — refusing to serve an unapproved definition`,
);
}
return document;
}
/**
* BI-P061's DoD. Restores version `toVersion` by minting a NEW version with
* the SAME document and publishing it. Returns the new release plus the
* verification that the restore is faithful.
*/
async rollback(args: {
scope: TenantScope;
dashboardId: string;
toVersion: number;
createdBy?: string;
}): Promise<{ release: DashboardRelease; restored_from: number; document_hash: string }> {
assertScope(args.scope);
const target = await this.store.findVersionByNumber(args.scope, args.dashboardId, args.toVersion);
if (!target) {
notFound(`dashboard "${args.dashboardId}" has no version ${args.toVersion} in this tenant`);
}
const live = await this.store.findByState(args.scope, args.dashboardId, 'published');
if (live && live.version === args.toVersion) {
conflict(`version ${args.toVersion} is already live; a rollback to the live version is a no-op`);
}
const document = parseDashboardDocument(JSON.parse(target.layout_json));
const hash = dashboardDocumentHash(document);
if (hash !== target.layout_hash) {
throw new SiaxError(
'PERMANENT_FAILURE',
'0pt.analytics.dashboard',
`version ${args.toVersion} hashes to ${hash} but was stored as ${target.layout_hash} — ` +
`refusing to roll back to a definition that has changed underneath us`,
);
}
const { release } = await this.draft({
scope: args.scope,
dashboardId: args.dashboardId,
document,
...(args.createdBy ? { createdBy: args.createdBy } : {}),
rollbackOfVersion: args.toVersion,
});
const { published } = await this.publish({ scope: args.scope, releaseId: release.release_id });
if (published.document_hash !== target.layout_hash) {
throw new SiaxError(
'PERMANENT_FAILURE',
'0pt.analytics.dashboard',
`rollback published ${published.document_hash}, not the requested ${target.layout_hash}`,
);
}
return { release: published, restored_from: args.toVersion, document_hash: published.document_hash };
}
/** Full ledger, oldest first. A rollback is an entry here, never a deletion. */
async history(scope: TenantScope, dashboardId: string): Promise<DashboardRelease[]> {
assertScope(scope);
const rows = await this.store.listReleases(scope, dashboardId);
return [...rows].sort((a, b) => a.version - b.version);
}
}
/**
* In-memory store. Used by the unit tests, and it enforces the same two
* uniqueness rules the SQL does — a store that is laxer than the database
* makes the unit tests pass on states production can never reach.
*/
export class InMemoryDashboardReleaseStore implements DashboardReleaseStore {
private readonly versions: DashboardVersionRecord[] = [];
private readonly releases: DashboardRelease[] = [];
private scoped<T extends { tenant_id: string; project_id: string }>(scope: TenantScope, rows: T[]): T[] {
return rows.filter((r) => r.tenant_id === scope.tenant_id && r.project_id === scope.project_id);
}
async maxVersion(scope: TenantScope, dashboardId: string): Promise<number> {
return this.scoped(scope, this.versions)
.filter((v) => v.dashboard_id === dashboardId)
.reduce((max, v) => Math.max(max, v.version), 0);
}
async insertVersionAndRelease(version: DashboardVersionRecord, release: DashboardRelease): Promise<void> {
const scope = { tenant_id: release.tenant_id, project_id: release.project_id };
if (
release.state === 'draft' &&
this.scoped(scope, this.releases).some(
(r) => r.dashboard_id === release.dashboard_id && r.state === 'draft',
)
) {
conflict('one open draft per dashboard');
}
if (this.versions.some((v) => v.dashboard_id === version.dashboard_id && v.version === version.version)) {
conflict(`version ${version.version} already exists for "${version.dashboard_id}"`);
}
this.versions.push({ ...version });
this.releases.push({ ...release });
}
async getRelease(scope: TenantScope, releaseId: string): Promise<DashboardRelease | undefined> {
const r = this.scoped(scope, this.releases).find((x) => x.release_id === releaseId);
return r ? { ...r } : undefined;
}
async getVersion(scope: TenantScope, id: string): Promise<DashboardVersionRecord | undefined> {
const v = this.scoped(scope, this.versions).find((x) => x.dashboard_version_id === id);
return v ? { ...v } : undefined;
}
async findVersionByNumber(
scope: TenantScope,
dashboardId: string,
version: number,
): Promise<DashboardVersionRecord | undefined> {
const v = this.scoped(scope, this.versions).find(
(x) => x.dashboard_id === dashboardId && x.version === version,
);
return v ? { ...v } : undefined;
}
async findByState(
scope: TenantScope,
dashboardId: string,
state: DashboardReleaseState,
): Promise<DashboardRelease | undefined> {
const r = this.scoped(scope, this.releases).find(
(x) => x.dashboard_id === dashboardId && x.state === state,
);
return r ? { ...r } : undefined;
}
async listReleases(scope: TenantScope, dashboardId: string): Promise<DashboardRelease[]> {
return this.scoped(scope, this.releases)
.filter((r) => r.dashboard_id === dashboardId)
.map((r) => ({ ...r }));
}
async publishAtomically(args: {
scope: TenantScope;
releaseId: string;
publishedAt: string;
supersedes?: { release_id: string; superseded_at: string };
}): Promise<void> {
const target = this.releases.find(
(r) =>
r.release_id === args.releaseId &&
r.tenant_id === args.scope.tenant_id &&
r.project_id === args.scope.project_id,
);
if (!target) notFound(`release "${args.releaseId}" not found`);
if (!isLegalTransition(target.state, 'published')) {
conflict(`illegal transition ${target.state} -> published`);
}
const alreadyLive = this.releases.find(
(r) =>
r.dashboard_id === target.dashboard_id &&
r.state === 'published' &&
r.release_id !== args.supersedes?.release_id,
);
if (alreadyLive) conflict('one published release per dashboard');
if (args.supersedes) {
const live = this.releases.find((r) => r.release_id === args.supersedes?.release_id);
if (!live) notFound(`release "${args.supersedes.release_id}" not found`);
if (!isLegalTransition(live.state, 'superseded')) {
conflict(`illegal transition ${live.state} -> superseded`);
}
live.state = 'superseded';
live.superseded_at = args.supersedes.superseded_at;
live.superseded_by_release_id = target.release_id;
}
target.state = 'published';
target.published_at = args.publishedAt;
}
}
-474
View File
@@ -1,474 +0,0 @@
/**
* src/analytics/domain/contract.ts
* =================================
* BI-P004 — ANALYTICS DATA CONTRACT.
*
* `DatasetContract` is the machine-checkable promise a dataset makes to every
* consumer downstream of it. BI-P004's DoD is a GATE, not a document:
*
* "Breaking dataset schema changes fail compatibility gate unless
* explicitly versioned."
*
* so `checkContractCompatibility` is the deliverable and the prose is the
* commentary. The gate is fail-closed: an unrecognised change is BREAKING,
* never "probably fine".
*
* Versioning is semver-shaped (`major.minor.patch`) with one rule that is not
* negotiable: a BREAKING change requires a MAJOR bump. A breaking change
* shipped under a minor bump is exactly the failure this gate exists to
* catch, so it is reported as a violation rather than tolerated.
*/
import crypto from "node:crypto";
import { SiaxError } from "../../platform/errors";
import type { AnalyticsFieldType, FieldRole, PiiClassification } from "./entities";
import type { AnalyticsTier } from "./tiers";
export interface ContractField {
name: string;
type: AnalyticsFieldType;
nullable: boolean;
role: FieldRole;
/** Part of the dataset's primary identifier. */
primary_identifier?: boolean;
classification?: PiiClassification;
description?: string;
}
export interface ContractQualityRule {
rule_id: string;
kind: string;
field_name?: string;
severity: "warn" | "block";
}
/** BI-P004's named contents, one field each. */
export interface DatasetContract {
dataset_id: string;
/** semver `major.minor.patch`. */
version: string;
tier: AnalyticsTier;
fields: ContractField[];
/** Field names forming the primary identifier, in order. */
primary_identifiers: string[];
/** Field names usable as dimensions (subset of `fields`). */
dimensions: string[];
/** Field names usable as measures (subset of `fields`). */
measures: string[];
/** Freshness SLO in seconds. */
freshness_slo_seconds: number;
retention_days: number;
/** Dataset-level PII classification (the max of its fields, at least). */
pii_classification: PiiClassification;
/** Upstream refs: source ids, dataset ids, external system refs. */
source_lineage: string[];
quality_rules: ContractQualityRule[];
/** GDPR purpose limitation — what this data may be USED for. */
allowed_purposes: string[];
}
export interface SemVer {
major: number;
minor: number;
patch: number;
}
const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)$/;
export function parseSemVer(v: string): SemVer {
const m = SEMVER_RE.exec(v);
if (!m) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `contract version "${v}" is not major.minor.patch`);
}
return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) };
}
// ── change classification ──────────────────────────────────────────────────
export type ChangeSeverity = "compatible" | "breaking";
export interface ContractChange {
severity: ChangeSeverity;
/** Stable machine code so callers can allow-list specific changes. */
code: string;
field?: string;
detail: string;
}
/**
* Type widening that does NOT break a reader. Deliberately conservative:
* int64 -> float64 loses exactness for large integers, so it is NOT here.
* Everything absent from this table is breaking.
*/
const SAFE_TYPE_WIDENING: Partial<Record<AnalyticsFieldType, readonly AnalyticsFieldType[]>> = {
date: ["timestamp"],
};
function typeChangeIsCompatible(from: AnalyticsFieldType, to: AnalyticsFieldType): boolean {
if (from === to) return true;
return (SAFE_TYPE_WIDENING[from] ?? []).includes(to);
}
/**
* Diff two contracts for the SAME dataset and classify every change.
*
* Breaking (a reader written against `previous` can now fail or silently
* change meaning):
* - field removed
* - field type changed other than a listed safe widening
* - nullable false -> true (readers may not handle nulls)
* - a field's role changes (a measure becoming a dimension changes meaning)
* - primary identifier set changes
* - a field leaves `measures` or `dimensions`
* - freshness SLO loosened (a consumer's own SLO may depend on it)
* - retention shortened (history a consumer relied on disappears)
* - an allowed purpose is removed (a legitimate consumer becomes illegitimate)
* - PII classification raised (consumers may lack clearance)
* - a blocking quality rule is removed or downgraded to warn
*
* Compatible: additive nullable fields, new dimensions/measures, new quality
* rules, loosened PII classification, added purposes, longer retention,
* tightened freshness.
*/
export function diffContracts(previous: DatasetContract, next: DatasetContract): ContractChange[] {
if (previous.dataset_id !== next.dataset_id) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
"contract compatibility is only defined between versions of the SAME dataset",
);
}
const changes: ContractChange[] = [];
const prevFields = new Map(previous.fields.map((f) => [f.name, f]));
const nextFields = new Map(next.fields.map((f) => [f.name, f]));
for (const [name, pf] of prevFields) {
const nf = nextFields.get(name);
if (!nf) {
changes.push({ severity: "breaking", code: "field_removed", field: name, detail: `field "${name}" removed` });
continue;
}
if (!typeChangeIsCompatible(pf.type, nf.type)) {
changes.push({
severity: "breaking",
code: "field_type_changed",
field: name,
detail: `field "${name}" type ${pf.type} -> ${nf.type}`,
});
} else if (pf.type !== nf.type) {
changes.push({
severity: "compatible",
code: "field_type_widened",
field: name,
detail: `field "${name}" widened ${pf.type} -> ${nf.type}`,
});
}
if (!pf.nullable && nf.nullable) {
changes.push({
severity: "breaking",
code: "field_became_nullable",
field: name,
detail: `field "${name}" became nullable`,
});
}
if (pf.nullable && !nf.nullable) {
changes.push({
severity: "compatible",
code: "field_became_required",
field: name,
detail: `field "${name}" is no longer nullable`,
});
}
if (pf.role !== nf.role) {
changes.push({
severity: "breaking",
code: "field_role_changed",
field: name,
detail: `field "${name}" role ${pf.role} -> ${nf.role}`,
});
}
}
for (const [name, nf] of nextFields) {
if (prevFields.has(name)) continue;
if (nf.nullable) {
changes.push({
severity: "compatible",
code: "nullable_field_added",
field: name,
detail: `nullable field "${name}" added`,
});
} else {
// A required new field breaks producers, and breaks readers that
// reconstruct rows (they now have no value to supply).
changes.push({
severity: "breaking",
code: "required_field_added",
field: name,
detail: `required (non-nullable) field "${name}" added`,
});
}
}
const idsEqual =
previous.primary_identifiers.length === next.primary_identifiers.length &&
previous.primary_identifiers.every((v, i) => next.primary_identifiers[i] === v);
if (!idsEqual) {
changes.push({
severity: "breaking",
code: "primary_identifier_changed",
detail: `primary identifier [${previous.primary_identifiers.join(",")}] -> [${next.primary_identifiers.join(",")}]`,
});
}
for (const d of previous.dimensions) {
if (!next.dimensions.includes(d)) {
changes.push({ severity: "breaking", code: "dimension_removed", field: d, detail: `dimension "${d}" removed` });
}
}
for (const d of next.dimensions) {
if (!previous.dimensions.includes(d)) {
changes.push({ severity: "compatible", code: "dimension_added", field: d, detail: `dimension "${d}" added` });
}
}
for (const m of previous.measures) {
if (!next.measures.includes(m)) {
changes.push({ severity: "breaking", code: "measure_removed", field: m, detail: `measure "${m}" removed` });
}
}
for (const m of next.measures) {
if (!previous.measures.includes(m)) {
changes.push({ severity: "compatible", code: "measure_added", field: m, detail: `measure "${m}" added` });
}
}
if (next.freshness_slo_seconds > previous.freshness_slo_seconds) {
changes.push({
severity: "breaking",
code: "freshness_slo_loosened",
detail: `freshness SLO ${previous.freshness_slo_seconds}s -> ${next.freshness_slo_seconds}s`,
});
}
if (next.retention_days < previous.retention_days) {
changes.push({
severity: "breaking",
code: "retention_shortened",
detail: `retention ${previous.retention_days}d -> ${next.retention_days}d`,
});
}
for (const p of previous.allowed_purposes) {
if (!next.allowed_purposes.includes(p)) {
changes.push({ severity: "breaking", code: "purpose_removed", detail: `allowed purpose "${p}" removed` });
}
}
const PII_RANK: Record<PiiClassification, number> = {
none: 0,
pseudonymous: 1,
personal: 2,
sensitive: 3,
};
if (PII_RANK[next.pii_classification] > PII_RANK[previous.pii_classification]) {
changes.push({
severity: "breaking",
code: "pii_classification_raised",
detail: `PII classification ${previous.pii_classification} -> ${next.pii_classification}`,
});
}
const prevRules = new Map(previous.quality_rules.map((r) => [r.rule_id, r]));
for (const [id, pr] of prevRules) {
const nr = next.quality_rules.find((r) => r.rule_id === id);
if (!nr && pr.severity === "block") {
changes.push({
severity: "breaking",
code: "blocking_quality_rule_removed",
detail: `blocking quality rule "${id}" removed`,
});
} else if (nr && pr.severity === "block" && nr.severity === "warn") {
changes.push({
severity: "breaking",
code: "blocking_quality_rule_downgraded",
detail: `quality rule "${id}" downgraded block -> warn`,
});
}
}
if (previous.tier !== next.tier) {
changes.push({
severity: "breaking",
code: "tier_changed",
detail: `tier ${previous.tier} -> ${next.tier}`,
});
}
return changes;
}
export interface CompatibilityVerdict {
compatible: boolean;
/** True when a MAJOR bump legitimises the breaking changes. */
explicitly_versioned: boolean;
changes: ContractChange[];
breaking: ContractChange[];
previous_version: string;
next_version: string;
/** Human-readable reason when `compatible` is false. */
reason?: string;
}
/**
* BI-P004's gate. Returns a verdict; `assertContractCompatible` throws.
*
* Rules, in order:
* 1. the version must move FORWARD (equal or lower is rejected outright);
* 2. breaking changes REQUIRE a major bump — that is what "explicitly
* versioned" means;
* 3. a major bump with no breaking change is allowed (over-declaring is
* safe; under-declaring is what we refuse).
*/
export function checkContractCompatibility(
previous: DatasetContract,
next: DatasetContract,
): CompatibilityVerdict {
const pv = parseSemVer(previous.version);
const nv = parseSemVer(next.version);
const changes = diffContracts(previous, next);
const breaking = changes.filter((c) => c.severity === "breaking");
const forward =
nv.major > pv.major ||
(nv.major === pv.major && nv.minor > pv.minor) ||
(nv.major === pv.major && nv.minor === pv.minor && nv.patch > pv.patch);
if (!forward) {
return {
compatible: false,
explicitly_versioned: false,
changes,
breaking,
previous_version: previous.version,
next_version: next.version,
reason: `version must move forward: ${previous.version} -> ${next.version}`,
};
}
const majorBumped = nv.major > pv.major;
if (breaking.length > 0 && !majorBumped) {
return {
compatible: false,
explicitly_versioned: false,
changes,
breaking,
previous_version: previous.version,
next_version: next.version,
reason:
`${breaking.length} breaking change(s) require a MAJOR version bump ` +
`(${previous.version} -> ${next.version} is not one): ` +
breaking.map((b) => b.code).join(", "),
};
}
return {
compatible: true,
explicitly_versioned: majorBumped && breaking.length > 0,
changes,
breaking,
previous_version: previous.version,
next_version: next.version,
};
}
/** Throwing form for call sites that treat incompatibility as a failure. */
export function assertContractCompatible(previous: DatasetContract, next: DatasetContract): CompatibilityVerdict {
const verdict = checkContractCompatibility(previous, next);
if (!verdict.compatible) {
throw new SiaxError("CONFLICT", "0pt.analytics", verdict.reason ?? "dataset contract compatibility gate failed");
}
return verdict;
}
/**
* Structural validation of a single contract (independent of history).
* Catches the contract that is internally inconsistent before it is ever
* compared to anything.
*/
export function validateContract(contract: DatasetContract): void {
parseSemVer(contract.version);
if (!contract.dataset_id.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "contract needs a dataset_id");
}
if (contract.fields.length === 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `contract ${contract.dataset_id} declares no fields`);
}
const names = new Set<string>();
for (const f of contract.fields) {
if (names.has(f.name)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `duplicate field "${f.name}"`);
}
names.add(f.name);
}
for (const label of ["primary_identifiers", "dimensions", "measures"] as const) {
for (const n of contract[label]) {
if (!names.has(n)) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
`${label} references unknown field "${n}" in ${contract.dataset_id}`,
);
}
}
}
if (contract.primary_identifiers.length === 0) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
`contract ${contract.dataset_id} declares no primary identifier`,
);
}
if (contract.allowed_purposes.length === 0) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
`contract ${contract.dataset_id} declares no allowed_purposes (purpose limitation is not optional)`,
);
}
if (contract.freshness_slo_seconds <= 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "freshness_slo_seconds must be positive");
}
if (contract.retention_days < 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "retention_days must not be negative");
}
}
/**
* Stable hash of a contract's MEANING (field order-insensitive), used as
* `DatasetVersion.contract_hash` so two versions that differ only in comment
* text do not look like schema drift.
*/
export function contractHash(contract: DatasetContract): string {
const canonical = {
dataset_id: contract.dataset_id,
version: contract.version,
tier: contract.tier,
fields: [...contract.fields]
.map((f) => ({
name: f.name,
type: f.type,
nullable: f.nullable,
role: f.role,
primary_identifier: f.primary_identifier ?? false,
classification: f.classification ?? "none",
}))
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)),
primary_identifiers: contract.primary_identifiers,
dimensions: [...contract.dimensions].sort(),
measures: [...contract.measures].sort(),
freshness_slo_seconds: contract.freshness_slo_seconds,
retention_days: contract.retention_days,
pii_classification: contract.pii_classification,
source_lineage: [...contract.source_lineage].sort(),
quality_rules: [...contract.quality_rules].sort((a, b) => (a.rule_id < b.rule_id ? -1 : 1)),
allowed_purposes: [...contract.allowed_purposes].sort(),
};
return crypto.createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
}
File diff suppressed because it is too large Load Diff
-83
View File
@@ -1,83 +0,0 @@
/**
* src/analytics/domain/tiers.ts
* ==============================
* BI-P003 — ANALYTICS DATA TIERS.
*
* The four canonical tiers every analytics dataset in SIAX belongs to. The
* tier is a CONTRACT about where a dataset may be read from and by whom, not
* a naming convention:
*
* RAW -> ST0RE Parquet/Iceberg (as-ingested, no business meaning)
* NORMALIZED -> ST0RE Iceberg (typed, deduplicated, still source-shaped)
* CURATED -> ST0RE Iceberg (business entities, modelled)
* SERVING -> ClickHouse / projection (query-optimised, dashboard-facing)
*
* BI-P003's normative sentence is "No business dashboard reads arbitrary raw
* ingestion tables by default" — `assertReadableByBiSurface` is where that
* sentence stops being prose. A BI surface (dashboard, report, embedded
* chart) may read SERVING and CURATED; RAW and NORMALIZED require an
* explicit, recorded exception on the dataset itself.
*
* ARCHITECTURE BOUNDARY (BI program §0): 0pt owns tier semantics. Product
* repos (VehIQ et al) own what the rows MEAN; they never re-declare tiers.
*/
import { SiaxError } from "../../platform/errors";
export const ANALYTICS_TIERS = ["RAW", "NORMALIZED", "CURATED", "SERVING"] as const;
export type AnalyticsTier = (typeof ANALYTICS_TIERS)[number];
/** Physical home a tier is expected to live in (BI-P003 "suggested" mapping). */
export const TIER_PHYSICAL_HOME: Record<AnalyticsTier, string> = {
RAW: "st0re:iceberg|parquet",
NORMALIZED: "st0re:iceberg",
CURATED: "st0re:iceberg",
SERVING: "clickhouse:projection",
};
/** Tiers a BI presentation surface may read without an explicit exception. */
export const BI_READABLE_TIERS: readonly AnalyticsTier[] = ["SERVING", "CURATED"];
export function isAnalyticsTier(v: unknown): v is AnalyticsTier {
return typeof v === "string" && (ANALYTICS_TIERS as readonly string[]).includes(v);
}
/**
* Rank used for promotion checks: a dataset may only be BUILT FROM a tier at
* or below its own (SERVING can be built from CURATED; CURATED must never be
* built from SERVING, which would make the projection its own source).
*/
export const TIER_RANK: Record<AnalyticsTier, number> = {
RAW: 0,
NORMALIZED: 1,
CURATED: 2,
SERVING: 3,
};
/**
* BI-P003 DoD gate. `raw_access_exception` is the recorded, auditable escape
* hatch — absent it, a RAW/NORMALIZED dataset is invisible to dashboards.
*/
export function assertReadableByBiSurface(
dataset: { dataset_id: string; tier: AnalyticsTier; raw_access_exception?: string },
surface: string,
): void {
if (BI_READABLE_TIERS.includes(dataset.tier)) return;
if (dataset.raw_access_exception && dataset.raw_access_exception.trim().length > 0) return;
throw new SiaxError(
"AUTHORIZATION_DENIED",
"0pt.analytics",
`BI surface "${surface}" may not read ${dataset.tier} dataset ${dataset.dataset_id} ` +
`without a recorded raw_access_exception (BI-P003)`,
);
}
/** A dataset may not declare a source tier ABOVE its own tier. */
export function assertTierLineageSane(datasetTier: AnalyticsTier, sourceTier: AnalyticsTier): void {
if (TIER_RANK[sourceTier] > TIER_RANK[datasetTier]) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
`a ${datasetTier} dataset cannot be built from a ${sourceTier} dataset (BI-P003 tier order)`,
);
}
}
File diff suppressed because it is too large Load Diff
-304
View File
@@ -1,304 +0,0 @@
/**
* src/analytics/engine/query-compiler.ts
* =======================================
* BI-P011 — CLICKHOUSE TENANT ISOLATION, layer 2:
* "`0pt` query compiler forces tenant".
*
* The compiler is the ONLY thing in this repo that turns an analytics request
* into SQL text. Its contract:
*
* * `tenant_id` is not an argument the caller may omit — it comes from the
* VERIFIED CL0UD identity (layer 1) and is written into the WHERE clause
* by this function, unconditionally, as a bound parameter.
* * caller-supplied VALUES are never spliced into SQL text. They travel as
* ClickHouse HTTP `param_*` query parameters.
* * caller-supplied IDENTIFIERS (a dimension name, a group-by column) are
* never spliced either. They are RESOLVED against a declared allow-list
* of `DimensionDefinition`s and only the resolved, already-known physical
* name reaches the SQL — so "dimension identifier injection" has no
* surface, because caller text never becomes an identifier.
* * there is no raw-SQL entry point. `compileMetricQuery` cannot express a
* UNION, a subquery, or a second table, so a caller cannot reach a table
* the compiler did not choose.
*
* WHY A SEPARATE MODULE from clickhouse-analytics.ts: that file's compiler
* already forces the tenant predicate correctly and BI-P009 says PRESERVE IT.
* This module is the generalised compiler for the BI-P010 tables; it repeats
* the guarantee rather than replacing it, and
* tests/analytics/tenant-predicate-regression.test.ts asserts BOTH.
*/
import { SiaxError } from "../../platform/errors";
import type { AnalyticsTable } from "./schema";
/** A physical identifier that has been VALIDATED, not merely received. */
const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
export function assertSafeIdentifier(value: string, what: string): string {
if (!IDENT_RE.test(value)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `invalid ${what} identifier`);
}
return value;
}
export const METRIC_AGGREGATES = ["sum", "avg", "min", "max", "count", "count_distinct"] as const;
export type MetricAggregate = (typeof METRIC_AGGREGATES)[number];
/**
* The dimensions a caller is allowed to name, resolved from
* `DimensionDefinition` rows. The compiler looks a caller's dimension name up
* HERE; a miss is a rejection, never a pass-through.
*/
export interface DimensionCatalog {
/** caller-facing dimension name -> physical dimension key in dim_names. */
resolve(name: string): string | undefined;
}
export function dimensionCatalogFrom(pairs: Record<string, string>): DimensionCatalog {
const map = new Map(Object.entries(pairs));
return {
resolve(name: string): string | undefined {
// Own-property lookup on a Map — no prototype-chain surprises
// ("constructor", "__proto__" resolve to undefined, as they must).
return map.get(name);
},
};
}
export interface MetricQueryRequest {
/** Supplied by the engine from the verified identity, NOT by the caller. */
tenant_id: string;
project_id?: string;
dataset_id?: string;
metric: string;
aggregate: MetricAggregate;
/** Caller-facing dimension names; resolved through the catalog. */
group_by?: string[];
/** Equality filters on dimensions: caller-facing name -> value. */
filters?: Record<string, string>;
from_time?: string;
to_time?: string;
limit?: number;
/** Which BI-P010 table to read. Chosen by the engine, not the caller. */
table?: AnalyticsTable;
}
export interface CompiledQuery {
sql: string;
/** ClickHouse HTTP `param_*` entries. Values NEVER appear in `sql`. */
params: Record<string, string>;
/** The predicate the compiler forced, for assertion in tests. */
forcedTenantPredicate: string;
table: AnalyticsTable;
}
/**
* The exact predicate text every compiled query must contain. Exported so a
* regression test can assert on the literal string — if someone deletes the
* forcing, the test fails on a missing substring rather than on a subtle
* behavioural difference that a mocked engine would happily hide.
*/
export const FORCED_TENANT_PREDICATE = "tenant_id = {tenant:String}";
const AGG_SQL: Record<MetricAggregate, string> = {
sum: "sum(value)",
avg: "avg(value)",
min: "min(value)",
max: "max(value)",
count: "count()",
count_distinct: "uniqExact(event_id)",
};
const MAX_GROUP_BY = 8;
/**
* Compile a closed-DSL metric request into tenant-forced SQL.
*
* @param req the request; `tenant_id` MUST already be the verified identity.
* @param db the analytics database name (engine-controlled, validated).
* @param catalog the tenant's declared dimensions.
* @param maxResultRows the governance ceiling (BI-P012); `limit` is clamped.
*/
export function compileMetricQuery(
req: MetricQueryRequest,
db: string,
catalog: DimensionCatalog,
maxResultRows: number,
): CompiledQuery {
if (!req.tenant_id || !req.tenant_id.trim()) {
// Fail closed. A blank tenant must never compile to "no predicate".
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant_id is required on every analytics query");
}
assertSafeIdentifier(db, "database");
const table: AnalyticsTable = req.table ?? "opt_analytics_event";
assertSafeIdentifier(table, "table");
if (!METRIC_AGGREGATES.includes(req.aggregate)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "unsupported aggregate");
}
const params: Record<string, string> = {
param_tenant: req.tenant_id,
param_metric: req.metric,
};
// ── the forced predicate. First condition, always, no branch. ─────────
const conditions: string[] = [FORCED_TENANT_PREDICATE, "metric = {metric:String}"];
if (req.project_id) {
conditions.push("project_id = {project:String}");
params.param_project = req.project_id;
}
if (req.dataset_id) {
conditions.push("dataset_id = {dataset:String}");
params.param_dataset = req.dataset_id;
}
if (req.from_time) {
conditions.push("event_time >= parseDateTime64BestEffort({fromTime:String})");
params.param_fromTime = req.from_time;
}
if (req.to_time) {
conditions.push("event_time < parseDateTime64BestEffort({toTime:String})");
params.param_toTime = req.to_time;
}
// ── filters: names resolved through the catalog, values parameterized ──
let filterIdx = 0;
for (const [name, value] of Object.entries(req.filters ?? {})) {
const physical = catalog.resolve(name);
if (physical === undefined) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `unknown filter dimension "${name}"`);
}
// `physical` came from the catalog, but validate anyway: a corrupted or
// hostile catalog row must not become an injection vector either.
assertSafeIdentifier(physical, "dimension");
const nameKey = `f${filterIdx}n`;
const valKey = `f${filterIdx}v`;
conditions.push(
`dim_values[indexOf(dim_names, {${nameKey}:String})] = {${valKey}:String}`,
);
params[`param_${nameKey}`] = physical;
params[`param_${valKey}`] = value;
filterIdx += 1;
}
// ── group by: same resolution, plus a hard cardinality ceiling ─────────
const groupBy = req.group_by ?? [];
if (groupBy.length > MAX_GROUP_BY) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
`at most ${MAX_GROUP_BY} group-by dimensions (got ${groupBy.length})`,
);
}
const selectParts: string[] = [];
const groupParts: string[] = [];
groupBy.forEach((name, i) => {
const physical = catalog.resolve(name);
if (physical === undefined) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `unknown group_by dimension "${name}"`);
}
assertSafeIdentifier(physical, "dimension");
const key = `g${i}`;
// The ALIAS is compiler-generated (`grp0`, `grp1`), never caller text.
selectParts.push(`dim_values[indexOf(dim_names, {${key}:String})] AS grp${i}`);
groupParts.push(`grp${i}`);
params[`param_${key}`] = physical;
});
const limit = Math.max(1, Math.min(Math.floor(req.limit ?? 1000), maxResultRows));
const sql =
`SELECT ${selectParts.length ? selectParts.join(", ") + ", " : ""}${AGG_SQL[req.aggregate]} AS value ` +
`FROM ${db}.${table} ` +
`WHERE ${conditions.join(" AND ")} ` +
(groupParts.length ? `GROUP BY ${groupParts.join(", ")} ORDER BY value DESC ` : "") +
`LIMIT ${limit} FORMAT JSON`;
return { sql, params, forcedTenantPredicate: FORCED_TENANT_PREDICATE, table };
}
/**
* Compile a projection lookup (SERVING tier, BI-P010's opt_dataset_projection).
* Same forcing, different table and key.
*/
export function compileProjectionQuery(
req: { tenant_id: string; project_id?: string; dataset_id: string; entity_keys?: string[]; limit?: number },
db: string,
maxResultRows: number,
): CompiledQuery {
if (!req.tenant_id || !req.tenant_id.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant_id is required on every analytics query");
}
assertSafeIdentifier(db, "database");
const params: Record<string, string> = {
param_tenant: req.tenant_id,
param_dataset: req.dataset_id,
};
const conditions = [FORCED_TENANT_PREDICATE, "dataset_id = {dataset:String}"];
if (req.project_id) {
conditions.push("project_id = {project:String}");
params.param_project = req.project_id;
}
if (req.entity_keys && req.entity_keys.length > 0) {
conditions.push("has({entityKeys:Array(String)}, entity_key)");
params.param_entityKeys = JSON.stringify(req.entity_keys);
}
const limit = Math.max(1, Math.min(Math.floor(req.limit ?? 1000), maxResultRows));
const sql =
`SELECT entity_key, as_of, version, attributes, measures ` +
`FROM ${db}.opt_dataset_projection ` +
`WHERE ${conditions.join(" AND ")} ` +
`ORDER BY entity_key LIMIT ${limit} FORMAT JSON`;
return { sql, params, forcedTenantPredicate: FORCED_TENANT_PREDICATE, table: "opt_dataset_projection" };
}
/**
* BI-P011 layer-3 bootstrap: the DDL for a RESTRICTED per-tenant ClickHouse
* user with a row policy pinning `tenant_id`.
*
* This is the layer that survives a compiler bug. The compiler forcing the
* predicate is layer 2; if a future refactor drops it, layer 3 still returns
* zero foreign rows because the SERVER filters them. The BI-P011 proof runs
* the adversarial suite twice — once through an unrestricted user (hole open)
* and once through this restricted user (hole closed) — because a claim of
* defence in depth that has never been tested with one layer removed is not
* evidence.
*
* `tenantId` is validated as an identifier-safe token AND embedded as a
* quoted literal; ClickHouse's CREATE ROW POLICY takes no bound parameters,
* so validation is the only protection available and it is applied strictly.
*/
export function restrictedTenantUserDdl(args: {
db: string;
tenantId: string;
userName: string;
password: string;
tables: readonly string[];
settingsProfile?: string;
}): string[] {
assertSafeIdentifier(args.db, "database");
assertSafeIdentifier(args.userName, "user");
// A tenant id is `t_<slug>` in this estate; enforce that shape strictly
// rather than trusting the caller.
if (!/^[A-Za-z0-9_-]{1,64}$/.test(args.tenantId)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant id is not policy-safe");
}
if (args.password.includes("'") || args.password.includes("\\")) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "password contains characters that cannot be embedded");
}
const profile = args.settingsProfile;
if (profile) assertSafeIdentifier(profile, "settings profile");
const stmts: string[] = [
`CREATE USER IF NOT EXISTS ${args.userName} IDENTIFIED WITH sha256_password BY '${args.password}'` +
(profile ? ` SETTINGS PROFILE ${profile}` : ` SETTINGS readonly = 1`),
];
for (const table of args.tables) {
assertSafeIdentifier(table, "table");
stmts.push(
`CREATE ROW POLICY IF NOT EXISTS ${args.userName}_${table}_rp ON ${args.db}.${table} ` +
`FOR SELECT USING tenant_id = '${args.tenantId}' TO ${args.userName}`,
);
stmts.push(`GRANT SELECT ON ${args.db}.${table} TO ${args.userName}`);
}
return stmts;
}
-222
View File
@@ -1,222 +0,0 @@
/**
* src/analytics/engine/resource-governance.ts
* ============================================
* BI-P012 — CLICKHOUSE RESOURCE GOVERNANCE.
*
* Every setting BI-P012 names, in one place, with a value:
*
* max_execution_time max_result_rows max_rows_to_read
* max_bytes_to_read max_memory_usage max_concurrent_queries
*
* Three layers, and the order matters:
*
* 1. SERVER-SIDE SETTINGS travel with every statement on the HTTP
* interface. ClickHouse enforces them; the client cannot opt out
* because the client is what writes them. `readonly=1` on top means a
* SELECT cannot re-set them mid-query (readonly=1 forbids SETTINGS
* changes as well as writes — that is the whole reason it is here and
* not merely `readonly=2`).
* 2. `max_concurrent_queries` is NOT a per-query setting in ClickHouse; it
* is a per-USER quota. `concurrencySlotSql` renders the CREATE
* SETTINGS PROFILE that carries it, applied to the tenant's restricted
* user (BI-P011 layer 3) so one tenant's fan-out cannot consume the
* whole server.
* 3. A local admission gate (`ConcurrencyGate`) refuses the N+1st
* in-flight query per tenant before it ever reaches the network. Two
* layers because the ClickHouse quota is per-user and one 0pt process
* can still queue work faster than the server rejects it.
*
* Budget tiers exist because "one limit for everyone" is how a small tenant
* subsidises a query bomb. `INTERACTIVE` is the dashboard default and is
* deliberately mean.
*/
import { SiaxError } from "../../platform/errors";
export interface ResourceBudget {
/** Seconds. ClickHouse `max_execution_time`. */
maxExecutionTimeSec: number;
/** Rows returned to the caller. ClickHouse `max_result_rows`. */
maxResultRows: number;
/** Rows SCANNED (not returned). ClickHouse `max_rows_to_read`. */
maxRowsToRead: number;
/** Bytes scanned. ClickHouse `max_bytes_to_read`. */
maxBytesToRead: number;
/** Bytes of RAM per query. ClickHouse `max_memory_usage`. */
maxMemoryUsageBytes: number;
/** In-flight queries per tenant. Enforced by quota + local gate. */
maxConcurrentQueries: number;
}
export const BUDGET_TIERS = ["INTERACTIVE", "ANALYTICAL", "BATCH"] as const;
export type BudgetTier = (typeof BUDGET_TIERS)[number];
/**
* Defaults. Chosen against the shape of the analytics tables in
* `src/analytics/engine/schema.ts`, not plucked from the air:
* INTERACTIVE must answer a dashboard panel inside a human's patience budget,
* so it caps the SCAN, which is what actually costs time on a MergeTree.
*/
export const DEFAULT_BUDGETS: Record<BudgetTier, ResourceBudget> = {
INTERACTIVE: {
maxExecutionTimeSec: 10,
maxResultRows: 10_000,
maxRowsToRead: 50_000_000,
maxBytesToRead: 2 * 1024 * 1024 * 1024,
maxMemoryUsageBytes: 2 * 1024 * 1024 * 1024,
maxConcurrentQueries: 8,
},
ANALYTICAL: {
maxExecutionTimeSec: 60,
maxResultRows: 500_000,
maxRowsToRead: 2_000_000_000,
maxBytesToRead: 32 * 1024 * 1024 * 1024,
maxMemoryUsageBytes: 8 * 1024 * 1024 * 1024,
maxConcurrentQueries: 4,
},
BATCH: {
maxExecutionTimeSec: 900,
maxResultRows: 10_000_000,
maxRowsToRead: 50_000_000_000,
maxBytesToRead: 512 * 1024 * 1024 * 1024,
maxMemoryUsageBytes: 24 * 1024 * 1024 * 1024,
maxConcurrentQueries: 2,
},
};
/**
* A CL0UD-issued quota may only ever TIGHTEN a tier, never loosen it. A
* control-plane bug that hands out a generous number must not be able to
* disarm the engine's own ceiling.
*/
export function applyQuota(base: ResourceBudget, quota: Partial<ResourceBudget> | undefined): ResourceBudget {
if (!quota) return { ...base };
const pick = (b: number, q: number | undefined): number =>
typeof q === "number" && Number.isFinite(q) && q > 0 ? Math.min(b, q) : b;
return {
maxExecutionTimeSec: pick(base.maxExecutionTimeSec, quota.maxExecutionTimeSec),
maxResultRows: pick(base.maxResultRows, quota.maxResultRows),
maxRowsToRead: pick(base.maxRowsToRead, quota.maxRowsToRead),
maxBytesToRead: pick(base.maxBytesToRead, quota.maxBytesToRead),
maxMemoryUsageBytes: pick(base.maxMemoryUsageBytes, quota.maxMemoryUsageBytes),
maxConcurrentQueries: pick(base.maxConcurrentQueries, quota.maxConcurrentQueries),
};
}
/**
* The settings that ride along on the HTTP request. `readonly: "1"` is what
* makes them un-overridable from inside the query text.
*
* `timeout_overflow_mode` / `result_overflow_mode` / `read_overflow_mode` are
* set to `throw` EXPLICITLY: ClickHouse's default for some of these is
* `break`, which silently returns a PARTIAL result. A partial result that
* looks complete is the analytics equivalent of a false green, so the engine
* refuses it.
*/
export function clickhouseSettings(budget: ResourceBudget): Record<string, string> {
return {
readonly: "1",
max_execution_time: String(budget.maxExecutionTimeSec),
timeout_overflow_mode: "throw",
max_result_rows: String(budget.maxResultRows),
result_overflow_mode: "throw",
max_rows_to_read: String(budget.maxRowsToRead),
max_bytes_to_read: String(budget.maxBytesToRead),
read_overflow_mode: "throw",
max_memory_usage: String(budget.maxMemoryUsageBytes),
};
}
/**
* Settings for a PLANNER call (`EXPLAIN ESTIMATE`, `EXPLAIN PLAN`).
*
* Measured, not assumed: running `EXPLAIN ESTIMATE` under the caller's own
* `max_rows_to_read` makes ClickHouse refuse the ESTIMATE itself with code 158
* whenever the estimate would be over budget — i.e. exactly the case the
* estimate exists to detect. An estimator that cannot describe an expensive
* query is useless, so the read ceilings are deliberately NOT applied here.
* The planner still runs `readonly = 1` under a short deadline and a memory
* cap, so this is a narrower envelope, never an unbounded one.
*/
export function planningSettings(budget: ResourceBudget): Record<string, string> {
return {
readonly: "1",
max_execution_time: String(Math.min(budget.maxExecutionTimeSec, 15)),
timeout_overflow_mode: "throw",
max_memory_usage: String(budget.maxMemoryUsageBytes),
};
}
/** Every setting name BI-P012 requires, for the DoD assertion. */
export const REQUIRED_GOVERNANCE_SETTINGS = [
"max_execution_time",
"max_result_rows",
"max_rows_to_read",
"max_bytes_to_read",
"max_memory_usage",
"max_concurrent_queries",
] as const;
/**
* `max_concurrent_queries` lives on a SETTINGS PROFILE, not on a statement.
* Rendered here so BI-P011's restricted-user bootstrap and BI-P012's budget
* come from one source.
*/
export function concurrencyProfileSql(profileName: string, budget: ResourceBudget): string[] {
return [
`CREATE SETTINGS PROFILE IF NOT EXISTS ${profileName} SETTINGS ` +
`max_execution_time = ${budget.maxExecutionTimeSec}, ` +
`max_result_rows = ${budget.maxResultRows}, ` +
`max_rows_to_read = ${budget.maxRowsToRead}, ` +
`max_bytes_to_read = ${budget.maxBytesToRead}, ` +
`max_memory_usage = ${budget.maxMemoryUsageBytes}, ` +
`readonly = 1`,
`CREATE QUOTA IF NOT EXISTS ${profileName}_quota ` +
`FOR INTERVAL 1 SECOND MAX queries = ${budget.maxConcurrentQueries * 20} ` +
`TO ALL EXCEPT default`,
];
}
/**
* Local admission control. One instance per process; keyed by tenant so a
* noisy tenant is throttled without touching anyone else's slots — which is
* exactly BI-P012's DoD wording ("without degrading unrelated tenant").
*/
export class ConcurrencyGate {
private readonly inFlight = new Map<string, number>();
constructor(private readonly limitFor: (tenantId: string) => number) {}
/** Returns a release function. Throws RATE_LIMITED when the tenant is full. */
acquire(tenantId: string): () => void {
const limit = this.limitFor(tenantId);
const current = this.inFlight.get(tenantId) ?? 0;
if (current >= limit) {
throw new SiaxError(
"RATE_LIMITED",
"0pt.analytics",
`tenant already has ${current} analytics queries in flight (limit ${limit})`,
);
}
this.inFlight.set(tenantId, current + 1);
let released = false;
return () => {
if (released) return;
released = true;
const n = (this.inFlight.get(tenantId) ?? 1) - 1;
if (n <= 0) this.inFlight.delete(tenantId);
else this.inFlight.set(tenantId, n);
};
}
/** Observability: in-flight count for a tenant (0 when idle). */
inFlightFor(tenantId: string): number {
return this.inFlight.get(tenantId) ?? 0;
}
/** Total in-flight across all tenants. */
totalInFlight(): number {
let n = 0;
for (const v of this.inFlight.values()) n += v;
return n;
}
}
-169
View File
@@ -1,169 +0,0 @@
/**
* src/analytics/engine/schema.ts
* ===============================
* BI-P010 — CLICKHOUSE PRODUCTION SCHEMA.
*
* BI-P010's explicit warning is "Avoid one giant unbounded table for every
* analytics use case." The existing `opt_metric_events` (owned by
* src/analytics/clickhouse-analytics.ts, PRESERVED untouched) is exactly one
* table for one job: low-cardinality capability metrics. It stays, and it is
* NOT extended into the catch-all.
*
* Four tables, four jobs, four retention profiles:
*
* opt_metric_events (PRE-EXISTING, not defined here) — capability
* metrics, Map(String,String) dimensions, 90d.
* opt_analytics_event — high-volume per-tenant event stream. Wide
* dimension arrays, SHORT TTL (raw events are not
* the serving tier; they age into the rollups).
* opt_metric_daily — AggregatingMergeTree rollup fed by a
* MATERIALIZED VIEW off opt_analytics_event.
* This is what a dashboard time-series reads;
* long TTL, tiny footprint.
* opt_dataset_projection — the SERVING tier (BI-P003) for a CURATED
* dataset: one row per (tenant, dataset, entity),
* ReplacingMergeTree so a refresh is idempotent.
*
* Why the split is load-bearing, not cosmetic:
* * different ORDER BY keys. A dashboard filtering (tenant, metric, day)
* and a projection looked up by (tenant, dataset, entity_key) cannot
* share one primary key without one of them degenerating to a full scan.
* * different TTLs. Raw events must expire fast; rollups must not.
* * different cardinality. `LowCardinality(String)` is a win on
* tenant/metric/dataset and a LOSS on a free-form entity key, so they
* cannot be the same column type in the same table.
*
* EVERY table leads its ORDER BY with `tenant_id`. That is not stylistic: it
* is what makes the forced tenant predicate (BI-P011) a primary-key range
* scan instead of a filter applied after reading everyone's rows, and it is
* what makes a per-tenant row policy cheap.
*
* LEGAL BOUNDARY (inherited verbatim from clickhouse-analytics.ts): this
* schema is for generic 0pt analytics. It MUST NEVER be pointed at the b0ts
* ClickHouse pipelines or quarantined market data.
*/
export interface AnalyticsSchemaOptions {
database: string;
/** Raw event retention. Deliberately short — rollups carry the history. */
eventRetentionDays?: number;
/** Rollup retention. */
rollupRetentionDays?: number;
/** Serving-projection retention. */
projectionRetentionDays?: number;
}
/** Physical tables this module owns (opt_metric_events is NOT one of them). */
export const ANALYTICS_TABLES = [
"opt_analytics_event",
"opt_metric_daily",
"opt_dataset_projection",
] as const;
export type AnalyticsTable = (typeof ANALYTICS_TABLES)[number];
/** The materialized view wiring opt_analytics_event -> opt_metric_daily. */
export const ANALYTICS_MATERIALIZED_VIEWS = ["opt_metric_daily_mv"] as const;
/**
* DDL, in dependency order. Every statement is CREATE ... IF NOT EXISTS so
* applying it to a live database is idempotent (the same contract
* `ClickHouseAnalytics.ensureSchema` already keeps).
*/
export function analyticsSchemaDdl(opts: AnalyticsSchemaOptions): string[] {
const db = opts.database;
const eventTtl = Math.floor(opts.eventRetentionDays ?? 30);
const rollupTtl = Math.floor(opts.rollupRetentionDays ?? 1095);
const projectionTtl = Math.floor(opts.projectionRetentionDays ?? 365);
return [
`CREATE DATABASE IF NOT EXISTS ${db}`,
// ── raw event stream ────────────────────────────────────────────────
// Dimensions as parallel arrays (not Map) so ClickHouse can prune on
// dimension VALUES via the bloom filter index; Map(String,String) forces
// reading the whole map. `event_id` makes deduplication possible on
// replay without a ReplacingMergeTree's merge latency.
`CREATE TABLE IF NOT EXISTS ${db}.opt_analytics_event (
tenant_id LowCardinality(String),
project_id LowCardinality(String),
dataset_id LowCardinality(String),
metric LowCardinality(String),
event_id String,
event_time DateTime64(3, 'UTC'),
value Float64,
dim_names Array(LowCardinality(String)),
dim_values Array(String),
ingested_at DateTime64(3, 'UTC') DEFAULT now64(3),
INDEX idx_dim_values dim_values TYPE bloom_filter(0.01) GRANULARITY 4
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(event_time)
ORDER BY (tenant_id, project_id, dataset_id, metric, event_time)
TTL toDateTime(event_time) + INTERVAL ${eventTtl} DAY
SETTINGS index_granularity = 8192`,
// ── daily rollup (serving tier for time series) ─────────────────────
`CREATE TABLE IF NOT EXISTS ${db}.opt_metric_daily (
tenant_id LowCardinality(String),
project_id LowCardinality(String),
dataset_id LowCardinality(String),
metric LowCardinality(String),
day Date,
sum_state AggregateFunction(sum, Float64),
count_state AggregateFunction(count, Float64),
min_state AggregateFunction(min, Float64),
max_state AggregateFunction(max, Float64)
)
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(day)
ORDER BY (tenant_id, project_id, dataset_id, metric, day)
TTL day + INTERVAL ${rollupTtl} DAY`,
`CREATE MATERIALIZED VIEW IF NOT EXISTS ${db}.opt_metric_daily_mv
TO ${db}.opt_metric_daily AS
SELECT
tenant_id,
project_id,
dataset_id,
metric,
toDate(event_time) AS day,
sumState(value) AS sum_state,
countState(value) AS count_state,
minState(value) AS min_state,
maxState(value) AS max_state
FROM ${db}.opt_analytics_event
GROUP BY tenant_id, project_id, dataset_id, metric, day`,
// ── serving projection for a CURATED dataset ────────────────────────
// ReplacingMergeTree(version) so refreshProjection is idempotent: the
// same (tenant, dataset, entity_key) re-ingested at a higher version
// supersedes rather than duplicates.
`CREATE TABLE IF NOT EXISTS ${db}.opt_dataset_projection (
tenant_id LowCardinality(String),
project_id LowCardinality(String),
dataset_id LowCardinality(String),
entity_key String,
as_of DateTime64(3, 'UTC'),
version UInt64,
attributes Map(String, String),
measures Map(String, Float64),
INDEX idx_entity entity_key TYPE bloom_filter(0.01) GRANULARITY 4
)
ENGINE = ReplacingMergeTree(version)
PARTITION BY (tenant_id)
ORDER BY (tenant_id, project_id, dataset_id, entity_key)
TTL toDateTime(as_of) + INTERVAL ${projectionTtl} DAY`,
];
}
/**
* Statement that proves a table's ORDER BY leads with tenant_id — used by the
* BI-P011 test suite so "tenant-first primary key" is asserted against the
* live server, not against this file's own comments.
*/
export function sortingKeySql(db: string, table: string): string {
return (
`SELECT sorting_key FROM system.tables ` +
`WHERE database = '${db}' AND name = '${table}' FORMAT TSV`
);
}
@@ -1,180 +0,0 @@
/**
* src/analytics/engine/siax-analytics-engine.ts
* ==============================================
* BI-P009 — the provider-neutral analytics engine interface.
*
* Eight capabilities, named exactly as BI-P009 lists them:
*
* health executeMetric executeQuery estimateQuery
* explain cancelQuery ingestProjection refreshProjection
*
* ClickHouse is the CANONICAL provider (BI-P009); DuckDB (BI-P014) and Trino
* (BI-P015) implement the same interface later. Nothing above this interface
* may import a provider module directly — that is what makes "replaceable
* provider" true rather than aspirational.
*
* NORMATIVE OWNERSHIP (BI program §0): every method takes an
* `AnalyticsIdentity` that the CALLER cannot forge, because it is produced by
* CL0UD verification upstream, not by request-body parsing. Product repos
* (VehIQ) call an API in front of this interface; they never hold a provider
* credential and never construct an engine.
*/
import type { CompiledQuery, MetricAggregate } from "./query-compiler";
import type { AnalyticsTable } from "./schema";
import type { BudgetTier, ResourceBudget } from "./resource-governance";
/**
* The VERIFIED caller. `tenant_id` here is the one the engine forces into
* every predicate — it comes from CL0UD identity verification (BI-P011 layer
* 1), never from a request body. This estate has already been burned once by
* a tenant read out of a request body (INF0 Wave 2, cross-tenant RAG access),
* which is why the type is separate from the request rather than a field on
* it.
*/
export interface AnalyticsIdentity {
tenant_id: string;
project_id?: string;
/** CL0UD principal, for audit + per-principal quota. */
principal_id: string;
correlation_id?: string;
/** Budget tier granted by CL0UD entitlements (BI-P012). */
budget_tier?: BudgetTier;
/** CL0UD quota, which may only TIGHTEN the tier. */
quota?: Partial<ResourceBudget>;
}
export interface MetricRequest {
metric: string;
aggregate: MetricAggregate;
dataset_id?: string;
group_by?: string[];
filters?: Record<string, string>;
from_time?: string;
to_time?: string;
limit?: number;
table?: AnalyticsTable;
}
export interface AnalyticsRow {
/** Resolved group values, keyed by the CALLER-FACING dimension name. */
groups?: Record<string, string>;
value: number;
}
export interface EngineResult {
rows: AnalyticsRow[];
/** Engine-side id; the handle `cancelQuery` needs. */
query_id: string;
/** True when the governance ceiling cut the result short (BI-P012). */
truncated: boolean;
stats: QueryStats;
}
export interface QueryStats {
duration_ms: number;
rows_read?: number;
bytes_read?: number;
result_rows: number;
}
export interface QueryEstimate {
/** Rows the engine expects to SCAN. */
estimated_rows_to_read: number;
estimated_bytes_to_read: number;
/** False when the estimate exceeds the caller's budget (BI-P012). */
within_budget: boolean;
budget: ResourceBudget;
/** Why it was refused, when `within_budget` is false. */
reason?: string;
}
export interface QueryExplanation {
/** Provider's plan text. Never contains caller-supplied SQL fragments. */
plan: string;
/** The predicate the compiler forced — assertable, not narrated. */
forced_tenant_predicate: string;
table: string;
}
export interface ProjectionRow {
entity_key: string;
as_of?: string;
version?: number;
attributes?: Record<string, string>;
measures?: Record<string, number>;
}
export interface ProjectionIngestRequest {
dataset_id: string;
rows: ProjectionRow[];
}
export interface ProjectionRefreshResult {
dataset_id: string;
/** Rows visible after the refresh settled. */
row_count: number;
refreshed_at: string;
}
export interface HealthReport {
healthy: boolean;
provider: string;
/** Provider version when reachable. */
version?: string;
/** Short operator-facing reason. Never a raw engine body. */
detail?: string;
}
/**
* A raw, ANALYST-facing query (BI-P017 will govern its SQL dialect). It is a
* SEPARATE method from `executeMetric` on purpose: `executeMetric` has no
* raw-SQL surface at all, and keeping them apart means the closed DSL cannot
* silently grow one.
*
* The canonical ClickHouse provider in this pass DELIBERATELY refuses this
* method (`CAPABILITY_UNAVAILABLE`): opening an analyst SQL surface before
* BI-P017's dialect contract and BI-P033's authorization exist would be
* exactly the "raw SQL attempt" BI-P011's adversarial list names. Declaring
* it and refusing it is honest; implementing it early is not.
*/
export interface AnalystQueryRequest {
sql: string;
dataset_ids: string[];
limit?: number;
}
export interface SiaxAnalyticsEngine {
readonly provider: string;
health(): Promise<HealthReport>;
executeMetric(identity: AnalyticsIdentity, request: MetricRequest): Promise<EngineResult>;
executeQuery(identity: AnalyticsIdentity, request: AnalystQueryRequest): Promise<EngineResult>;
estimateQuery(identity: AnalyticsIdentity, request: MetricRequest): Promise<QueryEstimate>;
cancelQuery(identity: AnalyticsIdentity, queryId: string): Promise<boolean>;
explain(identity: AnalyticsIdentity, request: MetricRequest): Promise<QueryExplanation>;
ingestProjection(identity: AnalyticsIdentity, request: ProjectionIngestRequest): Promise<{ ingested: number }>;
refreshProjection(identity: AnalyticsIdentity, dataset_id: string): Promise<ProjectionRefreshResult>;
}
/** The eight capability names, for the provider contract test. */
export const SIAX_ANALYTICS_ENGINE_CAPABILITIES = [
"health",
"executeMetric",
"executeQuery",
"estimateQuery",
"cancelQuery",
"explain",
"ingestProjection",
"refreshProjection",
] as const;
export type SiaxAnalyticsEngineCapability = (typeof SIAX_ANALYTICS_ENGINE_CAPABILITIES)[number];
/** Re-exported so provider modules do not reach across into the compiler. */
export type { CompiledQuery };
-183
View File
@@ -1,183 +0,0 @@
/**
* src/analytics/execution/cancellation.ts
* ========================================
* BI-P019 — QUERY CANCELLATION.
*
* "Integrate engine cancellation. DoD: User cancellation stops expensive
* query within defined timeout."
*
* THE THING THAT MAKES THIS REAL: "stops" is VERIFIED, not requested.
*
* The obvious implementation aborts the HTTP request and issues a KILL. Both
* of those are requests. The client abort stops US waiting; it does not stop
* the server, which keeps burning CPU on a query nobody will read. `KILL QUERY`
* without `SYNC` returns immediately and tells you nothing. Even `KILL QUERY
* SYNC` can return while the query is still winding down.
*
* So `cancelAndVerify` does three things and reports on all three:
* 1. abort the client side;
* 2. issue the engine's kill;
* 3. POLL the engine's process list until the query is GONE, or the deadline
* passes — and if the deadline passes, it says so with
* `verified_stopped: false` rather than returning a cheerful `true`.
*
* A caller that treats `cancelQuery()` returning `true` as "the query stopped"
* is the failure this module exists to prevent, which is why the return type
* is an outcome object and not a boolean.
*/
import { SiaxError } from '../../platform/errors';
/** Whatever can list and kill running queries. ClickHouse and Trino both can. */
export interface EngineProcessControl {
readonly engine: string;
/** True when a query with this id is still running on the engine. */
isRunning(queryId: string): Promise<boolean>;
/** Ask the engine to stop it. Returning true means "accepted", not "stopped". */
requestKill(queryId: string): Promise<boolean>;
/** Live progress for the running query, when the engine exposes it (BI-P021). */
progress?(queryId: string): Promise<QueryProgress | undefined>;
}
export interface QueryProgress {
rows_read: number;
bytes_read: number;
elapsed_ms: number;
}
export interface CancellationOutcome {
query_id: string;
requested_at: string;
/** The engine accepted the kill request. */
kill_accepted: boolean;
/**
* The query was OBSERVED to be gone from the engine's process list.
* `false` means it may still be running — the honest answer.
*/
verified_stopped: boolean;
/** Milliseconds from the cancel request to the observation. */
elapsed_ms: number;
/** The deadline this cancellation was held to. */
timeout_ms: number;
/** Present when the query had already finished before the request landed. */
already_finished: boolean;
}
export interface CancellationOptions {
/** The defined timeout BI-P019's DoD refers to. */
timeoutMs?: number;
pollIntervalMs?: number;
/** Aborts the client-side wait. */
abort?: () => void;
now?: () => number;
sleep?: (ms: number) => Promise<void>;
}
export const DEFAULT_CANCELLATION_TIMEOUT_MS = 5_000;
const DEFAULT_POLL_INTERVAL_MS = 100;
const defaultSleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
export async function cancelAndVerify(
control: EngineProcessControl,
queryId: string,
opts: CancellationOptions = {},
): Promise<CancellationOutcome> {
if (!queryId?.trim()) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'cancellation requires a query id');
}
const timeoutMs = opts.timeoutMs ?? DEFAULT_CANCELLATION_TIMEOUT_MS;
const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const now = opts.now ?? Date.now;
const sleep = opts.sleep ?? defaultSleep;
const startedMs = now();
const requestedAt = new Date(startedMs).toISOString();
// Was it even running? Cancelling a finished query is a no-op, and reporting
// it as a successful stop would overstate what happened.
//
// FAIL CLOSED when the engine cannot be asked: an unreachable engine means
// "unknown", and the safe reading of unknown is "still running" — so the
// kill is still issued and the verification loop still has to observe the
// query gone. Letting this throw would abandon the cancellation entirely at
// the exact moment the operator most needs it to be attempted.
let runningBefore: boolean;
try {
runningBefore = await control.isRunning(queryId);
} catch {
runningBefore = true;
}
// 1. client side: stop waiting.
opts.abort?.();
// 2. engine side: ask it to stop.
let killAccepted = false;
try {
killAccepted = await control.requestKill(queryId);
} catch {
killAccepted = false;
}
if (!runningBefore) {
return {
query_id: queryId,
requested_at: requestedAt,
kill_accepted: killAccepted,
verified_stopped: true,
elapsed_ms: now() - startedMs,
timeout_ms: timeoutMs,
already_finished: true,
};
}
// 3. VERIFY. This loop is the whole point of the module.
let verified = false;
for (;;) {
let stillRunning: boolean;
try {
stillRunning = await control.isRunning(queryId);
} catch {
// An engine we cannot ask is an engine we cannot vouch for. Keep trying
// until the deadline, then report unverified.
stillRunning = true;
}
if (!stillRunning) {
verified = true;
break;
}
if (now() - startedMs >= timeoutMs) break;
await sleep(pollIntervalMs);
}
return {
query_id: queryId,
requested_at: requestedAt,
kill_accepted: killAccepted,
verified_stopped: verified,
elapsed_ms: now() - startedMs,
timeout_ms: timeoutMs,
already_finished: false,
};
}
/**
* The same call, for a caller that wants a failure rather than a report.
* Throws `RETRYABLE_FAILURE` when the query outlived the deadline — because
* "we asked it to stop and it did not" is an operational condition someone
* has to see, not a value to ignore.
*/
export async function cancelOrThrow(
control: EngineProcessControl,
queryId: string,
opts: CancellationOptions = {},
): Promise<CancellationOutcome> {
const outcome = await cancelAndVerify(control, queryId, opts);
if (!outcome.verified_stopped) {
throw new SiaxError(
'RETRYABLE_FAILURE',
`0pt.analytics.${control.engine}`,
`query was not observed to stop within ${outcome.timeout_ms}ms of cancellation`,
);
}
return outcome;
}
@@ -1,138 +0,0 @@
/**
* src/analytics/execution/clickhouse-process-control.ts
* ======================================================
* BI-P019/BI-P021 — the ClickHouse implementation of `EngineProcessControl`.
*
* Three statements, each chosen for a measured reason:
*
* isRunning `SELECT count() FROM system.processes WHERE query_id = …`
* — the authority on whether the server is still working. Note
* that `KILL QUERY SYNC` returning is NOT this: a killed query
* can still appear here briefly while it unwinds, which is
* exactly why cancellation polls instead of trusting the kill.
*
* requestKill `KILL QUERY WHERE query_id = … ASYNC` — ASYNC, not SYNC,
* because the verification loop is what establishes the stop and
* a SYNC kill would block this call for up to the query's
* remaining lifetime while providing no stronger guarantee.
*
* progress `read_rows`, `read_bytes` and `elapsed` from the same table —
* live counters, which is what makes BI-P021's in-flight budget
* enforcement possible at all.
*
* KILL and the system-table reads are ADMINISTRATIVE. They run on the engine's
* own credential, never on the tenant's restricted user (which has no access
* to system.processes — measured: ACCESS_DENIED, code 497). The tenant-scoping
* check therefore happens HERE, on the query id, before any statement is sent.
*/
import { SiaxError } from '../../platform/errors';
import type { EngineProcessControl, QueryProgress } from './cancellation';
export interface ClickHouseProcessControlOptions {
baseUrl: string;
/** "user:password" for the ADMIN credential. From a secret ref. */
basicAuth?: string;
timeoutMs?: number;
/**
* Restricts every operation to query ids carrying this prefix, so a caller
* cannot kill or inspect another tenant's work through this object.
*/
queryIdPrefix?: string;
}
export class ClickHouseProcessControl implements EngineProcessControl {
readonly engine = 'clickhouse';
private readonly baseUrl: string;
private readonly authHeader?: string;
private readonly timeoutMs: number;
private readonly prefix?: string;
constructor(opts: ClickHouseProcessControlOptions) {
this.baseUrl = opts.baseUrl.replace(/\/+$/, '');
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString('base64')}` : undefined;
this.timeoutMs = opts.timeoutMs ?? 10_000;
this.prefix = opts.queryIdPrefix;
}
private assertScoped(queryId: string): void {
if (this.prefix && !queryId.startsWith(this.prefix)) {
throw new SiaxError('AUTHORIZATION_DENIED', '0pt.analytics', 'query does not belong to this scope');
}
if (!/^[A-Za-z0-9_-]{1,128}$/.test(queryId)) {
// The id reaches ClickHouse as a bound parameter, but a malformed id is
// a bug worth surfacing rather than a string worth binding.
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'malformed query id');
}
}
async isRunning(queryId: string): Promise<boolean> {
this.assertScoped(queryId);
const body = await this.send(
'SELECT count() AS n FROM system.processes WHERE query_id = {qid:String} FORMAT JSON',
{ param_qid: queryId },
);
const n = Number((JSON.parse(body) as { data: Array<{ n: string | number }> }).data[0]?.n ?? 0);
return n > 0;
}
async requestKill(queryId: string): Promise<boolean> {
this.assertScoped(queryId);
await this.send(
'KILL QUERY WHERE query_id = {qid:String} ASYNC FORMAT JSON',
{ param_qid: queryId },
false,
);
return true;
}
async progress(queryId: string): Promise<QueryProgress | undefined> {
this.assertScoped(queryId);
const body = await this.send(
'SELECT read_rows, read_bytes, toUInt64(elapsed * 1000) AS elapsed_ms FROM system.processes ' +
'WHERE query_id = {qid:String} FORMAT JSON',
{ param_qid: queryId },
);
const row = (JSON.parse(body) as { data: Array<Record<string, string | number>> }).data[0];
if (!row) return undefined;
return {
rows_read: Number(row.read_rows ?? 0),
bytes_read: Number(row.read_bytes ?? 0),
elapsed_ms: Number(row.elapsed_ms ?? 0),
};
}
private async send(sql: string, params: Record<string, string>, expectJson = true): Promise<string> {
const url = new URL(this.baseUrl);
url.searchParams.set('query', sql);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
// NOT readonly: KILL mutates server state. The other two would tolerate
// readonly, but sharing one path keeps the credential story simple.
url.searchParams.set('max_execution_time', '10');
const headers: Record<string, string> = {};
if (this.authHeader) headers.Authorization = this.authHeader;
let res: Response;
try {
res = await fetch(url.toString(), {
method: 'POST',
headers,
body: '',
signal: AbortSignal.timeout(this.timeoutMs),
});
} catch (cause) {
throw new SiaxError('DEPENDENCY_UNAVAILABLE', 'clickhouse', 'clickhouse unreachable', { cause });
}
const text = await res.text();
if (!res.ok) {
const code = /Code:\s*(\d+)/.exec(text)?.[1] ?? String(res.status);
throw new SiaxError(
'PERMANENT_FAILURE',
'clickhouse',
`process-control statement failed (CH code ${code})`,
);
}
if (expectJson && !text.trim()) {
throw new SiaxError('PERMANENT_FAILURE', 'clickhouse', 'empty response from process-control statement');
}
return text;
}
}
@@ -1,274 +0,0 @@
/**
* src/analytics/execution/query-execution-record.ts
* ==================================================
* BI-P018 — QUERY EXECUTION MODEL.
*
* Every field BI-P018 lists, verbatim, and one it lists by its absence:
*
* "Every production query has traceable execution metadata WITHOUT
* unnecessarily storing sensitive raw SQL."
*
* So the record carries `compiled_query_hash` and never the statement. That is
* enforced, not documented: `assertNoRawSql` scans a finished record for the
* statement it describes, and
* tests/analytics/query-execution-model.test.ts fails if any field carries it.
*
* The ONE place raw SQL is retained is the analyst statement history
* (BI-P017), where a privileged human ran unreviewed SQL against tenant data
* and "who ran what" has to survive. That history is a separate record with a
* separate retention posture; this one is the per-execution telemetry that
* every query in the estate produces, and it must be safe to keep for a long
* time and to ship to AUD0.
*
* BI-P002's `QueryExecution` entity is the persisted row; this module is the
* lifecycle that produces it, plus the four fields BI-P018 adds to it
* (compiled_query_hash, datasets, metrics, cache_status, cost_units).
*/
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import type { ExecutionState } from '../domain/entities';
/** BI-P020's outcome, recorded per execution so cache behaviour is measurable. */
export const CACHE_STATUSES = ['hit', 'miss', 'bypass', 'stale_refused', 'not_cacheable'] as const;
export type CacheStatus = (typeof CACHE_STATUSES)[number];
/** Which surface produced the query — the "user/workload" axis BI-P018 names. */
export const WORKLOAD_KINDS = [
'dashboard',
'report',
'api',
'analyst_sql',
'ai_analyst',
'scheduled',
'internal',
] as const;
export type WorkloadKind = (typeof WORKLOAD_KINDS)[number];
export interface QueryExecutionRecord {
query_id: string;
execution_id: string;
tenant_id: string;
project_id?: string;
/** The CL0UD principal. A human, a service, or a job — never absent. */
principal_id: string;
workload: WorkloadKind;
submitted_at: string;
started_at?: string;
completed_at?: string;
engine: string;
/**
* sha256 of the COMPILED statement plus its bound parameter values.
*
* Parameters are included deliberately: two executions of the same SQL with
* different filters are different work with different cost, and a hash that
* collapsed them would make the cost record meaningless. They are HASHED,
* not stored, so the record still carries no tenant data.
*/
compiled_query_hash: string;
datasets: string[];
metrics: string[];
status: ExecutionState;
/** Rows RETURNED to the caller. */
rows?: number;
/** Rows and bytes SCANNED — the cost axis, not the result size. */
rows_scanned?: number;
bytes_scanned?: number;
duration_ms?: number;
cache_status: CacheStatus;
/** BI-P021 units. Present once the query has settled, including on failure. */
cost_units?: number;
/** A SiaxErrorCode. Never an engine body, never a fragment of the statement. */
error?: string;
correlation_id?: string;
}
/**
* Hash a compiled statement and its bound parameters into the one value the
* record keeps.
*
* Parameters are sorted so two logically identical executions hash equal
* regardless of key iteration order — otherwise the cache-key and cost
* aggregations built on this hash would fragment for no reason.
*/
export function compiledQueryHash(sql: string, params: Record<string, string> = {}): string {
const canonical = JSON.stringify([
sql.trim(),
Object.keys(params)
.sort()
.map((k) => [k, params[k]]),
]);
return crypto.createHash('sha256').update(canonical).digest('hex');
}
/**
* The legal state machine. Written down because "status" fields drift into
* meaninglessness when any value can follow any other — a `succeeded` row that
* later becomes `running` makes every downstream aggregation a lie.
*/
const LEGAL_TRANSITIONS: Record<ExecutionState, readonly ExecutionState[]> = {
queued: ['running', 'cancelled', 'rejected', 'failed'],
running: ['succeeded', 'failed', 'cancelled'],
succeeded: [],
failed: [],
cancelled: [],
rejected: [],
};
export function assertLegalTransition(from: ExecutionState, to: ExecutionState): void {
if (!LEGAL_TRANSITIONS[from].includes(to)) {
throw new SiaxError('CONFLICT', '0pt.analytics', `illegal execution transition ${from} -> ${to}`);
}
}
/** Terminal states: a record in one of these will never change again. */
export const TERMINAL_STATES: readonly ExecutionState[] = ['succeeded', 'failed', 'cancelled', 'rejected'];
export interface ExecutionSink {
write(record: QueryExecutionRecord): Promise<void> | void;
}
export interface ExecutionRecorderOptions {
tenant_id: string;
project_id?: string;
principal_id: string;
workload: WorkloadKind;
engine: string;
correlation_id?: string;
sink: ExecutionSink;
now?: () => number;
}
/**
* Owns one execution's record from submission to a terminal state.
*
* Every transition WRITES. A recorder that only writes at the end loses
* exactly the executions that matter: the ones that never finished.
*/
export class QueryExecutionRecorder {
private record: QueryExecutionRecord;
private readonly sink: ExecutionSink;
private readonly now: () => number;
constructor(
opts: ExecutionRecorderOptions,
queryId: string,
compiled: { hash: string; datasets: string[]; metrics: string[] },
) {
if (!opts.tenant_id?.trim()) {
throw new SiaxError(
'UNAUTHENTICATED',
'0pt.analytics',
'an execution record requires a verified tenant',
);
}
if (!opts.principal_id?.trim()) {
throw new SiaxError(
'UNAUTHENTICATED',
'0pt.analytics',
'an execution record requires a verified principal',
);
}
this.now = opts.now ?? Date.now;
this.sink = opts.sink;
this.record = {
query_id: queryId,
execution_id: crypto.randomUUID(),
tenant_id: opts.tenant_id,
project_id: opts.project_id,
principal_id: opts.principal_id,
workload: opts.workload,
submitted_at: new Date(this.now()).toISOString(),
engine: opts.engine,
compiled_query_hash: compiled.hash,
datasets: [...compiled.datasets],
metrics: [...compiled.metrics],
status: 'queued',
cache_status: 'miss',
correlation_id: opts.correlation_id,
};
}
get current(): QueryExecutionRecord {
return { ...this.record, datasets: [...this.record.datasets], metrics: [...this.record.metrics] };
}
async submitted(): Promise<void> {
await this.sink.write(this.current);
}
async started(): Promise<void> {
assertLegalTransition(this.record.status, 'running');
this.record.status = 'running';
this.record.started_at = new Date(this.now()).toISOString();
await this.sink.write(this.current);
}
/** A cache hit never reached the engine; record it as such, not as a fast query. */
async servedFromCache(rows: number, costUnits = 0): Promise<void> {
assertLegalTransition(this.record.status, 'running');
this.record.status = 'running';
this.record.started_at = this.record.started_at ?? new Date(this.now()).toISOString();
this.record.cache_status = 'hit';
await this.finish('succeeded', { rows, rows_scanned: 0, bytes_scanned: 0, cost_units: costUnits });
}
setCacheStatus(status: CacheStatus): void {
this.record.cache_status = status;
}
async finish(
status: ExecutionState,
stats: {
rows?: number;
rows_scanned?: number;
bytes_scanned?: number;
cost_units?: number;
error?: string;
},
): Promise<QueryExecutionRecord> {
assertLegalTransition(this.record.status, status);
const completedMs = this.now();
this.record.status = status;
this.record.completed_at = new Date(completedMs).toISOString();
const startedMs = this.record.started_at
? Date.parse(this.record.started_at)
: Date.parse(this.record.submitted_at);
this.record.duration_ms = Math.max(0, completedMs - startedMs);
if (stats.rows !== undefined) this.record.rows = stats.rows;
if (stats.rows_scanned !== undefined) this.record.rows_scanned = stats.rows_scanned;
if (stats.bytes_scanned !== undefined) this.record.bytes_scanned = stats.bytes_scanned;
if (stats.cost_units !== undefined) this.record.cost_units = stats.cost_units;
if (stats.error !== undefined) this.record.error = stats.error;
assertNoRawSql(this.record);
await this.sink.write(this.current);
return this.current;
}
}
/**
* Refuse to emit a record that carries statement text.
*
* Checked at runtime rather than trusted to the type, because the fields that
* leak are the string ones a future change widens — `error` becoming an engine
* body is the obvious one, and ClickHouse's error text echoes the query.
*/
export function assertNoRawSql(record: QueryExecutionRecord): void {
const suspicious = /\b(select|insert|update|delete|drop|create|alter|from|where|join|union)\b/i;
const stringFields: Array<[string, string | undefined]> = [
['error', record.error],
['query_id', record.query_id],
['compiled_query_hash', record.compiled_query_hash],
['correlation_id', record.correlation_id],
...record.datasets.map((d, i) => [`datasets[${i}]`, d] as [string, string]),
...record.metrics.map((m, i) => [`metrics[${i}]`, m] as [string, string]),
];
for (const [name, value] of stringFields) {
if (value && suspicious.test(value)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
`execution record field "${name}" looks like SQL; BI-P018 stores a hash, never the statement`,
);
}
}
}
@@ -1,143 +0,0 @@
/**
* src/analytics/ingestion/analytics-ingestion-service.ts
* =======================================================
* BI-P129: one entry point that takes an `AnalyticsIngestionSpec` and lands
* rows in a canonical analytics tier, whichever provider supplies the
* connector.
*
* The sequence, and why it is this sequence:
*
* 1. plan — every gate checkable without touching the source
* (tier, physical home, licence, provider readiness).
* Cheap checks first: a spec that can never be legal
* should not open a session to find that out.
* 2. connect+discover— ask the source what it actually looks like.
* 3. landability — the discovered shape must satisfy the BI-P004
* contract. This is the check that cannot be done at
* step 1, and doing it here is the whole reason the
* service exists rather than a bare `planX()` call.
* 4. run — hand the connector to the EXISTING P062 runner with
* a landing sink. The runner owns paging, envelopes,
* schema conformance, quality gating, the idempotency
* ledger and the durable checkpoint. None of that is
* re-implemented here.
* 5. disconnect — always, including on failure.
*
* Step 4 is worth spelling out because it is where a "new ingestion system"
* would normally get built by accident. There is no second runner. The
* analytics plane contributes a TARGET and four GATES; the highway is the one
* that already exists and already has crash/resume tests.
*/
import { SiaxError } from '../../platform/errors';
import { IngestionRunner, type IngestionRunReport } from '../../ingestion/ingestion-runner';
import type { IngestionRepository } from '../../repositories/ingestion-repository';
import type { SchemaRegistry } from '../../schema/schema-registry';
import type { LineageStore } from '../../lineage/lineage-store';
import type { QualityEnforcementPolicy } from '../../quality/quality-policy';
import type { RecordSchemaFields } from '../../schema/record-schema';
import {
planAnalyticsIngestion,
type AnalyticsConnectorProvider,
type AnalyticsIngestionSpec,
type PlannedAnalyticsIngestion,
} from './connector-provider';
import { assertDiscoveryLandable, landingSink, type LandingWriter } from './landing';
export interface AnalyticsIngestionDeps {
repo: IngestionRepository;
schemas: SchemaRegistry;
writer: LandingWriter;
lineage?: LineageStore;
/** Runtime environment name; "production" turns gate 4 on. */
runtimeEnv: string;
}
export interface AnalyticsIngestionResult {
plan: PlannedAnalyticsIngestion;
/** What discovery reported, per partition — recorded so a later drift is provable. */
discovered: Record<string, RecordSchemaFields>;
run: IngestionRunReport;
}
export interface AnalyticsIngestionOptions {
run_id?: string;
page_size?: number;
max_pages?: number;
partition_key?: string;
quality_policy?: QualityEnforcementPolicy;
correlation_id?: string;
}
export class AnalyticsIngestionService {
constructor(private readonly deps: AnalyticsIngestionDeps) {}
/** Gates 1, 3 and 4 — no IO, no session. Safe to call from a UI pre-flight. */
plan(provider: AnalyticsConnectorProvider, spec: AnalyticsIngestionSpec): PlannedAnalyticsIngestion {
return planAnalyticsIngestion(provider, spec, this.deps.runtimeEnv);
}
async ingest(
provider: AnalyticsConnectorProvider,
spec: AnalyticsIngestionSpec,
options: AnalyticsIngestionOptions = {},
): Promise<AnalyticsIngestionResult> {
const plan = this.plan(provider, spec);
const runId = options.run_id ?? `run_${spec.source_id}_${Date.now()}`;
const connector = plan.connector;
const discovered: Record<string, RecordSchemaFields> = {};
await connector.connect(spec.config, {
tenant_id: spec.tenant_id,
project_id: spec.project_id,
source_id: spec.source_id,
run_id: runId,
});
try {
const discovery = await connector.discover();
for (const partition of discovery.partitions) {
if (options.partition_key && partition.partition_key !== options.partition_key) continue;
discovered[partition.partition_key] = partition.schema;
}
// Gate 2 — the one that needs the source to have answered.
assertDiscoveryLandable(spec.target, discovered);
} finally {
// The runner opens its own session; this discovery session is ours to close.
await connector.disconnect();
}
const runner = new IngestionRunner(this.deps.repo, this.deps.schemas, this.deps.lineage);
const run = await runner.run({
source_id: spec.source_id,
tenant_id: spec.tenant_id,
project_id: spec.project_id,
mode: spec.mode,
connector,
config: spec.config,
sink: landingSink({
target: spec.target,
tenant_id: spec.tenant_id,
project_id: spec.project_id,
run_id: runId,
writer: this.deps.writer,
}),
run_id: runId,
page_size: options.page_size,
max_pages: options.max_pages,
partition_key: options.partition_key,
quality_policy: options.quality_policy,
output_ref: `0pt:dataset:${spec.target.dataset_id}`,
correlation_id: options.correlation_id,
});
if (run.status === 'failed') {
throw new SiaxError(
'RETRYABLE_FAILURE',
'0pt.analytics.ingestion',
`ingestion run ${run.run_id} for dataset ${spec.target.dataset_id} failed: ` +
`${run.failure?.code ?? 'unknown'} ${run.failure?.detail ?? ''}`.trim(),
);
}
return { plan, discovered, run };
}
}
@@ -1,442 +0,0 @@
/**
* src/analytics/ingestion/connector-provider.ts
* ==============================================
* BI-P129 — ANALYTICS DATA INGESTION.
*
* BI-P129 names four provider kinds for 0pt's `ConnectorProvider`:
*
* native — connectors 0pt implements and owns (P061 contract)
* dlt — the dlt Python framework (BI-P130)
* Meltano/Singer — the Singer tap ecosystem (BI-P131)
* Airbyte — "only optional where legal/license architecture accepts it"
*
* WHAT THIS FILE IS. It is the seam between 0pt's EXISTING ingestion highway
* (`src/connectors/connector.ts` P061 + `src/ingestion/ingestion-runner.ts`
* P062) and the ANALYTICS tier/contract model (BI-P003 tiers, BI-P004
* `DatasetContract`). It deliberately does NOT define a second connector
* interface: a provider's job is to hand back a P061 `Connector`, and the
* runner that already exists then does the reading, checkpointing and
* quality gating. A parallel ingestion stack would be exactly the "do not
* define parallel models" failure this programme keeps paying for.
*
* WHAT IT ADDS, which the P061 stack has no opinion about: an ingestion run
* must LAND somewhere, and where it lands is an analytics contract question.
* Four gates, all fail-closed, all attacked in
* tests/analytics/analytics-ingestion-providers.test.ts:
*
* 1. assertLandingTierIngestible — source data may land in RAW, or in
* NORMALIZED with a declared normalization. It may NEVER land directly
* in CURATED or SERVING. BI-P003's rule ("no business dashboard reads
* arbitrary raw ingestion tables by default") is trivially defeated by
* relabelling the raw landing table SERVING; this gate is what stops
* that, because the tier is checked at the point of WRITE, not only at
* the point of read.
*
* 2. assertContractCoversDiscovery — every field the connector actually
* discovered must be declared in the target `DatasetContract`, with a
* compatible type. An UNDECLARED field is refused rather than landed:
* an undeclared column is an unclassified column, and an unclassified
* column carrying personal data is a GDPR incident that every freshness
* and quality check would still report green.
*
* 3. assertPhysicalHomeMatchesTier — a RAW/NORMALIZED landing goes to
* ST0RE Parquet/Iceberg (the shapes st0re#45 standardised), never
* straight into ClickHouse. Writing ingestion output into the serving
* engine skips the lake, and with it every replay, backfill and
* erasure path that depends on the files existing.
*
* 4. assertProviderRunnable — a provider whose own `providerReadiness()`
* says `verified: false` cannot execute in a production runtime without
* a recorded exception naming a human. This is the structural version
* of the honesty rule `0pt#35` set with MetricFlow: an unverified
* provider may exist, may be planned, may be tested — but it cannot
* quietly become production capability because someone forgot it was
* unverified.
*
* ARCHITECTURE BOUNDARY (BI programme §0): 0pt owns ingestion into analytics
* tiers. A product repo declares what the rows MEAN through
* `BIApplicationBinding`; it never runs its own ingestion into these tiers
* and never receives ClickHouse credentials.
*/
import { SiaxError } from '../../platform/errors';
import type { Connector, ConnectorConfig, ValidationResult } from '../../connectors/connector';
import type { RecordSchemaFields, FieldType } from '../../schema/record-schema';
import type { IngestionMode } from '../../types/ingestion';
import type { AnalyticsFieldType } from '../domain/entities';
import type { AnalyticsTier } from '../domain/tiers';
import type { DatasetContract } from '../domain/contract';
import type { ProviderReadiness } from '../metrics/semantic-provider';
import type { N0dRequiredRole } from '../../clients/n0d-client';
/**
* Deliberately the SAME `ProviderReadiness` shape BI-P029 introduced, not a
* second one. An estate with two readiness vocabularies has none.
*/
export type { ProviderReadiness };
// ── provider kinds ─────────────────────────────────────────────────────────
export const CONNECTOR_PROVIDER_KINDS = ['native', 'dlt', 'singer', 'airbyte'] as const;
export type ConnectorProviderKind = (typeof CONNECTOR_PROVIDER_KINDS)[number];
/**
* BI-P129: "Airbyte only optional where legal/license architecture accepts
* it." That acceptance has NOT been given in this estate — Airbyte's server
* is Elastic License 2.0 (ELv2), which restricts offering the software as a
* managed service to third parties, and 0pt's whole purpose is offering
* managed data capability to customers. So `airbyte` is a declared kind with
* no implementation, and registering one is refused here rather than
* somewhere downstream. When a licence review says otherwise, this constant
* is the single place that changes.
*/
export const PROVIDER_KINDS_REQUIRING_LICENCE_ACCEPTANCE: readonly ConnectorProviderKind[] = ['airbyte'];
// ── landing target ─────────────────────────────────────────────────────────
/** Physical formats an analytics landing may use. st0re#45's shapes. */
export const LANDING_FORMATS = ['parquet', 'iceberg'] as const;
export type LandingFormat = (typeof LANDING_FORMATS)[number];
/** Where an ingestion run's output physically goes. */
export interface LandingPhysical {
format: LandingFormat;
/** ST0RE lakehouse namespace. */
namespace: string;
table_name: string;
}
export interface AnalyticsLandingTarget {
dataset_id: string;
tier: AnalyticsTier;
/** The BI-P004 contract the landed rows must satisfy. */
contract: DatasetContract;
physical: LandingPhysical;
/**
* Required when `tier` is NORMALIZED: what normalization was applied
* between the source bytes and the landed rows. Free text, recorded — an
* empty or missing value means the dataset is really RAW wearing a
* NORMALIZED label, and is refused.
*/
normalization?: string;
}
/** One ingestion the analytics plane is asked to perform. */
export interface AnalyticsIngestionSpec {
source_id: string;
tenant_id: string;
project_id: string;
mode: IngestionMode;
provider: ConnectorProviderKind;
/** Provider-specific connector selector (a native connector id, a tap name, a dlt source). */
connector_ref: string;
config: ConnectorConfig;
target: AnalyticsLandingTarget;
/**
* Records the human who accepted running an UNVERIFIED provider in a
* production runtime. Absent = an unverified provider is refused.
*/
unverified_provider_exception?: string;
}
// ── execution plan ─────────────────────────────────────────────────────────
export type ProviderRuntime = 'in_process' | 'n0d';
/**
* Where a provider's work actually runs. BI-P130 says dlt executes on N0D;
* this is the type that carries that decision instead of a comment.
*/
export interface ProviderExecutionPlan {
runtime: ProviderRuntime;
/** N0D job_type; set iff runtime is "n0d". */
job_type?: string;
required_role?: N0dRequiredRole;
/** Named profile from N0D_RESOURCE_PROFILES; set iff runtime is "n0d". */
resource_profile?: string;
/** Operator-facing reason, in plain words. */
reason: string;
}
// ── the port ───────────────────────────────────────────────────────────────
export interface AnalyticsConnectorProvider {
readonly provider: ConnectorProviderKind;
/** What this provider has and has NOT demonstrated. Never optimistic. */
providerReadiness(): ProviderReadiness;
/** Pure, no IO, never throws — the P061 `validate` posture, at spec level. */
validateSpec(spec: AnalyticsIngestionSpec): ValidationResult;
/** The P061 connector this spec ingests through. */
connectorFor(spec: AnalyticsIngestionSpec): Connector;
executionPlan(spec: AnalyticsIngestionSpec): ProviderExecutionPlan;
}
// ── gate 1: landing tier ───────────────────────────────────────────────────
/** Tiers an ingestion run may write into at all. */
export const INGESTIBLE_TIERS: readonly AnalyticsTier[] = ['RAW', 'NORMALIZED'];
export function assertLandingTierIngestible(target: AnalyticsLandingTarget): void {
if (!INGESTIBLE_TIERS.includes(target.tier)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`ingestion may not land directly in ${target.tier} (dataset ${target.dataset_id}): ` +
`CURATED and SERVING are DERIVED tiers, built from a landed RAW/NORMALIZED dataset. ` +
`Landing source data there relabels raw ingestion as dashboard-readable and defeats BI-P003.`,
);
}
if (target.tier === 'NORMALIZED' && !(target.normalization ?? '').trim()) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`dataset ${target.dataset_id} lands in NORMALIZED but declares no normalization — ` +
`that is a RAW dataset wearing a NORMALIZED label (BI-P003)`,
);
}
}
// ── gate 2: contract covers what was discovered ────────────────────────────
/**
* How a connector's wire-level field type maps onto the analytics type
* vocabulary. Conservative on purpose: a connector's `number` may be an
* integer or a float, so it satisfies EITHER analytics numeric type, but
* nothing else. Anything not listed here is a mismatch, not a guess.
*/
const CONNECTOR_TYPE_SATISFIES: Record<FieldType, readonly AnalyticsFieldType[]> = {
string: ['string', 'decimal', 'date', 'timestamp'],
number: ['int64', 'float64', 'decimal'],
boolean: ['bool'],
timestamp: ['timestamp', 'date'],
object: ['json'],
array: ['json'],
};
export interface ContractCoverageProblem {
code: 'undeclared_field' | 'type_mismatch' | 'missing_required_field' | 'nullability_mismatch';
field: string;
detail: string;
}
/**
* Compare what the connector says the source LOOKS LIKE against what the
* contract says the dataset IS. Returns every problem; never throws.
*/
export function contractCoverageProblems(
contract: DatasetContract,
discovered: RecordSchemaFields,
): ContractCoverageProblem[] {
const problems: ContractCoverageProblem[] = [];
const byName = new Map(contract.fields.map((f) => [f.name, f]));
for (const [name, spec] of Object.entries(discovered)) {
const field = byName.get(name);
if (!field) {
problems.push({
code: 'undeclared_field',
field: name,
detail:
`source field "${name}" is not declared in contract ${contract.dataset_id}@${contract.version}; ` +
`an undeclared field is an unclassified field and is refused, not landed`,
});
continue;
}
const satisfies = CONNECTOR_TYPE_SATISFIES[spec.type] ?? [];
if (!satisfies.includes(field.type)) {
problems.push({
code: 'type_mismatch',
field: name,
detail: `source field "${name}" is ${spec.type}; contract declares ${field.type}`,
});
}
// `FieldSpec.required` is the connector-side vocabulary; the contract
// speaks `nullable`. required:false === nullable:true.
if (spec.required === false && field.nullable === false) {
problems.push({
code: 'nullability_mismatch',
field: name,
detail: `source field "${name}" is optional at the source; contract declares it NOT NULL`,
});
}
}
for (const field of contract.fields) {
if (field.nullable === false && !(field.name in discovered)) {
problems.push({
code: 'missing_required_field',
field: field.name,
detail: `contract requires non-null field "${field.name}" but the source does not produce it`,
});
}
}
return problems;
}
export function assertContractCoversDiscovery(
contract: DatasetContract,
discovered: RecordSchemaFields,
): void {
const problems = contractCoverageProblems(contract, discovered);
if (problems.length > 0) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`source shape does not satisfy dataset contract ${contract.dataset_id}@${contract.version}: ` +
problems.map((p) => `[${p.code}] ${p.detail}`).join('; '),
);
}
}
// ── gate 3: physical home ──────────────────────────────────────────────────
export function assertPhysicalHomeMatchesTier(target: AnalyticsLandingTarget): void {
if (!(LANDING_FORMATS as readonly string[]).includes(target.physical.format)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`landing format "${target.physical.format}" is not a lakehouse format; ` +
`RAW/NORMALIZED land as Parquet or Iceberg in ST0RE (BI-P003, st0re#45)`,
);
}
if (!target.physical.namespace.trim() || !target.physical.table_name.trim()) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`landing target for ${target.dataset_id} is missing a ST0RE namespace/table name`,
);
}
}
// ── gate 4: unverified providers may not run in production ─────────────────
export function assertProviderRunnable(
provider: AnalyticsConnectorProvider,
spec: AnalyticsIngestionSpec,
runtimeEnv: string,
): void {
const readiness = provider.providerReadiness();
if (readiness.verified) return;
const isProduction = runtimeEnv === 'production';
const exception = (spec.unverified_provider_exception ?? '').trim();
if (!isProduction) return;
if (exception.length === 0) {
throw new SiaxError(
'CAPABILITY_UNAVAILABLE',
'0pt.analytics.ingestion',
`provider "${provider.provider}" reports verified: false ` +
`(open: ${readiness.open.join('; ')}) and may not run in production ` +
`without a recorded unverified_provider_exception`,
);
}
}
// ── planning ───────────────────────────────────────────────────────────────
export interface PlannedAnalyticsIngestion {
spec: AnalyticsIngestionSpec;
connector: Connector;
execution: ProviderExecutionPlan;
readiness: ProviderReadiness;
/** The tier the rows land in — echoed so a caller cannot claim a different one later. */
landing_tier: AnalyticsTier;
}
/**
* Run every gate that can be checked WITHOUT touching the source, then hand
* back the connector. `assertContractCoversDiscovery` is deliberately NOT
* here: discovery requires a live session, so it runs in `landingSink`'s
* caller / `AnalyticsIngestionService` once `discover()` has answered.
*/
export function planAnalyticsIngestion(
provider: AnalyticsConnectorProvider,
spec: AnalyticsIngestionSpec,
runtimeEnv: string,
): PlannedAnalyticsIngestion {
if (provider.provider !== spec.provider) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`spec asks for provider "${spec.provider}" but was given "${provider.provider}"`,
);
}
if (PROVIDER_KINDS_REQUIRING_LICENCE_ACCEPTANCE.includes(spec.provider)) {
throw new SiaxError(
'CAPABILITY_UNAVAILABLE',
'0pt.analytics.ingestion',
`provider "${spec.provider}" requires a licence/architecture acceptance this estate has not given ` +
`(BI-P129: "Airbyte only optional where legal/license architecture accepts it")`,
);
}
const verdict = provider.validateSpec(spec);
if (!verdict.valid) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`provider "${provider.provider}" rejected the spec: ${verdict.errors.join('; ')}`,
);
}
assertLandingTierIngestible(spec.target);
assertPhysicalHomeMatchesTier(spec.target);
assertProviderRunnable(provider, spec, runtimeEnv);
return {
spec,
connector: provider.connectorFor(spec),
execution: provider.executionPlan(spec),
readiness: provider.providerReadiness(),
landing_tier: spec.target.tier,
};
}
// ── registry ───────────────────────────────────────────────────────────────
/**
* The set of providers a runtime actually has. Registration is explicit:
* there is no discovery-by-filename, because a provider appearing in the
* registry because a file exists is how an unreviewed integration becomes
* live.
*/
export class ConnectorProviderRegistry {
private readonly providers = new Map<ConnectorProviderKind, AnalyticsConnectorProvider>();
register(provider: AnalyticsConnectorProvider): this {
if (this.providers.has(provider.provider)) {
throw new SiaxError(
'CONFLICT',
'0pt.analytics.ingestion',
`provider "${provider.provider}" is already registered`,
);
}
if (PROVIDER_KINDS_REQUIRING_LICENCE_ACCEPTANCE.includes(provider.provider)) {
throw new SiaxError(
'CAPABILITY_UNAVAILABLE',
'0pt.analytics.ingestion',
`provider "${provider.provider}" may not be registered: no licence/architecture acceptance exists ` +
`for it in this estate (BI-P129)`,
);
}
this.providers.set(provider.provider, provider);
return this;
}
get(kind: ConnectorProviderKind): AnalyticsConnectorProvider {
const p = this.providers.get(kind);
if (!p) {
throw new SiaxError(
'NOT_FOUND',
'0pt.analytics.ingestion',
`no connector provider registered for kind "${kind}"`,
);
}
return p;
}
has(kind: ConnectorProviderKind): boolean {
return this.providers.has(kind);
}
/** Readiness of every registered provider — the operator's one-screen answer. */
readinessReport(): ProviderReadiness[] {
return [...this.providers.values()].map((p) => p.providerReadiness());
}
}
-160
View File
@@ -1,160 +0,0 @@
/**
* src/analytics/ingestion/landing.ts
* ===================================
* BI-P129: the write side. An ingestion run's envelopes have to become FILES
* in a canonical tier, and this is the only place in the analytics plane that
* decides what those files look like.
*
* WHERE THE BOUNDARY IS. 0pt does not own object storage. ST0RE owns the
* lakehouse (namespaces, Iceberg tables, snapshots — `st0re#45`), and 0pt's
* existing `src/services/iceberg-write-service.ts` is already the client for
* it. So `LandingWriter` is a PORT, not an implementation: it names exactly
* what the analytics plane needs from a lake writer (append a batch to one
* tier-owned table, tell me what landed) and nothing more. The default
* implementation here is in-memory and is used by tests and by dry runs; the
* ST0RE-backed one is the existing service, injected.
*
* WHAT THIS FILE ENFORCES, and why each rule is not decoration:
*
* - Every landed batch carries `tier` and `dataset_id`. A batch of rows
* with no tier is a batch nobody can decide the read rules for later.
*
* - `assertContractCoversDiscovery` (BI-P129 gate 2) runs HERE, at the
* point discovery has actually answered, not at plan time when the
* source has not been asked yet. A gate that runs before the fact it
* checks is available is a gate that checks nothing.
*
* - Deletes are LANDED, not dropped. `IngestionEnvelope` with
* `operation: "delete"` carries `payload: null`; a landing that silently
* skipped it would produce exactly the failure this programme has already
* paid for once — an aggregate that never sees a DELETE and overstates a
* number while every freshness check reports green. Staleness is not
* correctness, and a delete that never lands is not staleness at all,
* it is permanent wrongness.
*
* - The batch records `envelope_id`s, so a replay is detectable downstream.
* The runner's guarantee is at-least-once (documented in
* src/ingestion/ingestion-runner.ts); a landing that pretended otherwise
* would be lying about the pipeline it sits in.
*/
import { SiaxError } from '../../platform/errors';
import type { IngestionEnvelope } from '../../types/ingestion';
import type { RecordSchemaFields } from '../../schema/record-schema';
import type { AnalyticsTier } from '../domain/tiers';
import {
assertContractCoversDiscovery,
type AnalyticsLandingTarget,
type LandingFormat,
} from './connector-provider';
/** One physical batch appended to a tier-owned table. */
export interface LandedBatch {
dataset_id: string;
tier: AnalyticsTier;
format: LandingFormat;
namespace: string;
table_name: string;
tenant_id: string;
project_id: string;
run_id: string;
partition_key: string;
/** Rows written, including tombstones. */
row_count: number;
/** Rows whose payload was null (CDC deletes). Counted separately, never dropped. */
tombstone_count: number;
envelope_ids: string[];
}
/**
* The port. One method: append a batch. Deliberately narrow — every extra
* method here is a piece of ST0RE's contract leaking into 0pt's.
*/
export interface LandingWriter {
append(batch: LandedBatch): Promise<void>;
}
/** Test/dry-run writer. Keeps everything it was given so a test can assert on it. */
export class InMemoryLandingWriter implements LandingWriter {
readonly batches: LandedBatch[] = [];
async append(batch: LandedBatch): Promise<void> {
this.batches.push(batch);
}
get rowsLanded(): number {
return this.batches.reduce((n, b) => n + b.row_count, 0);
}
get tombstonesLanded(): number {
return this.batches.reduce((n, b) => n + b.tombstone_count, 0);
}
}
export interface LandingSinkInput {
target: AnalyticsLandingTarget;
tenant_id: string;
project_id: string;
run_id: string;
writer: LandingWriter;
}
/**
* Build an `IngestionSink` (the runner's own type) that lands envelopes into
* the declared analytics tier.
*
* Note the sink is per-run: the runner commits its checkpoint only AFTER
* this resolves, so a writer that throws leaves the page unconsumed and the
* next run re-reads it. That ordering belongs to the runner and is not
* re-implemented here — it is relied upon.
*/
export function landingSink(input: LandingSinkInput): (envelopes: IngestionEnvelope[]) => Promise<void> {
return async (envelopes: IngestionEnvelope[]): Promise<void> => {
if (envelopes.length === 0) return;
const partitions = new Set(envelopes.map((e) => e.partition_key));
for (const partition of partitions) {
const forPartition = envelopes.filter((e) => e.partition_key === partition);
await input.writer.append({
dataset_id: input.target.dataset_id,
tier: input.target.tier,
format: input.target.physical.format,
namespace: input.target.physical.namespace,
table_name: input.target.physical.table_name,
tenant_id: input.tenant_id,
project_id: input.project_id,
run_id: input.run_id,
partition_key: partition,
row_count: forPartition.length,
tombstone_count: forPartition.filter((e) => e.payload === null).length,
envelope_ids: forPartition.map((e) => e.envelope_id),
});
}
};
}
/**
* BI-P129 gate 2, applied once the connector's `discover()` has answered.
* Called by `AnalyticsIngestionService`; exported so an operator pre-flight
* can run it without starting a run.
*/
export function assertDiscoveryLandable(
target: AnalyticsLandingTarget,
discoveredByPartition: Record<string, RecordSchemaFields>,
): void {
const partitions = Object.keys(discoveredByPartition);
if (partitions.length === 0) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`source for dataset ${target.dataset_id} discovered no partitions; there is nothing to land`,
);
}
for (const partition of partitions) {
try {
assertContractCoversDiscovery(target.contract, discoveredByPartition[partition]);
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.ingestion',
`partition "${partition}": ${detail}`,
);
}
}
}
@@ -1,97 +0,0 @@
/**
* src/analytics/ingestion/native-provider.ts
* ===========================================
* BI-P129, provider kind `native`: connectors 0pt implements and owns.
*
* There is nothing to integrate here — the connectors already exist and are
* already conformance-tested (`src/connectors/conformance.ts`, P061). This
* provider's whole job is to select one and report, honestly, that it is
* verified: these connectors run in this repo's CI, in-process, with no
* third-party runtime and no unreviewed dependency.
*
* The two shipped natives are deliberately heterogeneous (that was P061's
* point and it is BI-P129's DoD too — "two real source types"):
*
* http_json — remote HTTP API, opaque server-issued page token, health
* is a network round trip, record count unknown until the
* server says it is done.
* jsonl_file — local file drop, cursor is a line offset the connector
* computes itself, health is a stat(), record count exact,
* and it emits real CDC deletes.
*
* They share no code but the contract, so "both land in a canonical tier"
* is a statement about the SEAM, not about one connector.
*/
import { HttpJsonConnector, type FetchImpl } from '../../connectors/http-json-connector';
import { JsonlFileConnector } from '../../connectors/jsonl-file-connector';
import type { Connector, ValidationResult } from '../../connectors/connector';
import type {
AnalyticsConnectorProvider,
AnalyticsIngestionSpec,
ProviderExecutionPlan,
ProviderReadiness,
} from './connector-provider';
/** Native connector ids this provider can build. */
export const NATIVE_CONNECTOR_IDS = ['http_json', 'jsonl_file'] as const;
export type NativeConnectorId = (typeof NATIVE_CONNECTOR_IDS)[number];
export class NativeConnectorProvider implements AnalyticsConnectorProvider {
readonly provider = 'native' as const;
/**
* Optional injection point so a caller can supply an `HttpJsonConnector`
* with a specific `fetchImpl` (the connector's own documented test seam).
* With nothing supplied, a real connector talking to the configured URL is
* built — this is not a mock fallback.
*/
constructor(private readonly fetchImpl?: FetchImpl) {}
providerReadiness(): ProviderReadiness {
return {
provider: this.provider,
pinned_version: 'in-repo',
verified: true,
proven: [
'both native connectors pass the P061 conformance suite (tests/p0/connector-conformance.test.ts)',
'both land into a canonical analytics tier through the P062 ingestion runner ' +
'(tests/analytics/analytics-ingestion-providers.test.ts)',
'no third-party runtime and no unreviewed dependency is involved',
],
open: [
'only http_json and jsonl_file exist natively; every other source type needs dlt/Singer or a new native connector',
],
};
}
validateSpec(spec: AnalyticsIngestionSpec): ValidationResult {
const errors: string[] = [];
if (!(NATIVE_CONNECTOR_IDS as readonly string[]).includes(spec.connector_ref)) {
errors.push(
`unknown native connector "${spec.connector_ref}" (have: ${NATIVE_CONNECTOR_IDS.join(', ')})`,
);
return { valid: false, errors };
}
// Delegate the config check to the connector itself — it is the authority
// on its own config, and its `validate` is pure and never throws.
const connector = this.connectorFor(spec);
const verdict = connector.validate(spec.config);
errors.push(...verdict.errors);
return { valid: errors.length === 0, errors };
}
connectorFor(spec: AnalyticsIngestionSpec): Connector {
if (spec.connector_ref === 'http_json') {
return this.fetchImpl ? new HttpJsonConnector(this.fetchImpl) : new HttpJsonConnector();
}
if (spec.connector_ref === 'jsonl_file') return new JsonlFileConnector();
throw new Error(`unknown native connector "${spec.connector_ref}"`);
}
executionPlan(_spec: AnalyticsIngestionSpec): ProviderExecutionPlan {
return {
runtime: 'in_process',
reason: 'native connectors are Node code in this repo; they need no separate runtime and no N0D job',
};
}
}
@@ -1,170 +0,0 @@
/**
* src/analytics/materialization/drift-detector.ts
* ================================================
* BI-P105 — is the pre-aggregate still telling the truth?
*
* The comparison is bucket-by-bucket between the aggregate and a recomputation
* from the source over the same window. Three things make it a real detector
* rather than a ceremony:
*
* 1. A MISSING BUCKET IS DRIFT. The nastiest pre-aggregate failure is not a
* wrong value, it is an absent row: late-arriving data, a materialized view
* that was created after the backfill, a refresh that failed silently. Every
* value it DOES hold is correct, so a value-only comparison passes while the
* total is wrong. Set difference is checked first, before any arithmetic.
*
* 2. ZERO BUCKETS IS `insufficient_data`, NEVER `match`. A comparison over an
* empty window finds no discrepancies — the same false green BI-P025 found
* in a quality check over an empty table. The router treats
* `insufficient_data` as "do not serve", not as "fine".
*
* 3. RELATIVE AND ABSOLUTE TOLERANCE BOTH HAVE TO HOLD. A 0.1% tolerance on a
* revenue bucket of 40M is 40 000 kr of invisible error; an absolute-only
* tolerance flags every rounding difference on a large bucket. Requiring
* both means a discrepancy has to be small in kronor AND small in
* proportion.
*/
import type { DriftTolerance, DriftVerdict, MaterializationStatus } from './materialization';
/** One aggregated row, keyed by its dimension tuple. */
export interface AggregateBucket {
/** Stable key for the dimension tuple, e.g. "2026-09-01|SE". */
key: string;
/** metric name -> value. */
values: Record<string, number>;
}
export interface DriftDiscrepancy {
key: string;
metric: string;
source_value: number;
aggregate_value: number;
absolute_delta: number;
/** |delta| / |source|, or Infinity when the source value is 0 and the aggregate is not. */
relative_delta: number;
}
export interface DriftReport {
verdict: DriftVerdict;
checked_at: string;
buckets_compared: number;
/** In the source recomputation, absent from the aggregate. Always drift. */
missing_in_aggregate: string[];
/** In the aggregate, absent from the source. Always drift (deleted rows). */
extra_in_aggregate: string[];
discrepancies: DriftDiscrepancy[];
worst?: DriftDiscrepancy;
tolerance: DriftTolerance;
/**
* What a caller would have been told if it had trusted the aggregate: the
* total the aggregate reports vs the total the source computes, per metric.
* This is the number that makes a drift report actionable — "0.4% off" means
* nothing until it is "1 284 500 kr reported, 1 271 900 kr true".
*/
totals: Record<string, { source: number; aggregate: number; delta: number }>;
}
const MAX_REPORTED_DISCREPANCIES = 50;
function relative(sourceValue: number, delta: number): number {
if (sourceValue === 0) return delta === 0 ? 0 : Number.POSITIVE_INFINITY;
return Math.abs(delta / sourceValue);
}
/**
* Compare a recomputation from source against the pre-aggregate.
*
* `fromSource` is the truth. Both sides must cover the same window; the caller
* is responsible for that, and `missing_in_aggregate` will catch it loudly if
* they do not.
*/
export function detectDrift(args: {
fromSource: AggregateBucket[];
fromAggregate: AggregateBucket[];
tolerance: DriftTolerance;
metrics: string[];
now?: Date;
}): DriftReport {
const { fromSource, fromAggregate, tolerance, metrics } = args;
const checked_at = (args.now ?? new Date()).toISOString();
const sourceByKey = new Map(fromSource.map((b) => [b.key, b]));
const aggByKey = new Map(fromAggregate.map((b) => [b.key, b]));
const missing_in_aggregate = [...sourceByKey.keys()].filter((k) => !aggByKey.has(k)).sort();
const extra_in_aggregate = [...aggByKey.keys()].filter((k) => !sourceByKey.has(k)).sort();
const discrepancies: DriftDiscrepancy[] = [];
let buckets_compared = 0;
const totals: DriftReport['totals'] = {};
for (const m of metrics) totals[m] = { source: 0, aggregate: 0, delta: 0 };
for (const [key, sourceBucket] of sourceByKey) {
for (const m of metrics) totals[m].source += sourceBucket.values[m] ?? 0;
const aggBucket = aggByKey.get(key);
if (!aggBucket) continue;
buckets_compared += 1;
for (const m of metrics) {
const sv = sourceBucket.values[m] ?? 0;
const av = aggBucket.values[m] ?? 0;
const delta = av - sv;
const rel = relative(sv, delta);
if (Math.abs(delta) > tolerance.absolute || rel > tolerance.relative) {
discrepancies.push({
key,
metric: m,
source_value: sv,
aggregate_value: av,
absolute_delta: delta,
relative_delta: rel,
});
}
}
}
for (const bucket of aggByKey.values()) {
for (const m of metrics) totals[m].aggregate += bucket.values[m] ?? 0;
}
for (const m of metrics) totals[m].delta = totals[m].aggregate - totals[m].source;
discrepancies.sort((a, b) => Math.abs(b.absolute_delta) - Math.abs(a.absolute_delta));
// A comparison that compared nothing has not proved anything. This is the
// BI-P025 false green, restated for pre-aggregates.
const verdict: DriftVerdict =
buckets_compared === 0 && missing_in_aggregate.length === 0 && extra_in_aggregate.length === 0
? 'insufficient_data'
: discrepancies.length > 0 || missing_in_aggregate.length > 0 || extra_in_aggregate.length > 0
? 'drifted'
: 'match';
const report: DriftReport = {
verdict,
checked_at,
buckets_compared,
missing_in_aggregate,
extra_in_aggregate,
discrepancies: discrepancies.slice(0, MAX_REPORTED_DISCREPANCIES),
tolerance,
totals,
};
if (discrepancies.length > 0) report.worst = discrepancies[0];
return report;
}
/**
* Fold a drift report into the runtime status. A drifted aggregate is taken
* OUT of service here rather than merely annotated: leaving it `serving` with
* a bad verdict relies on every future reader remembering to check the
* verdict, and one that forgets serves the wrong number.
*
* `insufficient_data` also stops service. It means the check could not prove
* anything, and an unproven aggregate is not a current one.
*/
export function applyDriftReport(status: MaterializationStatus, report: DriftReport): MaterializationStatus {
return {
...status,
state: report.verdict === 'match' ? status.state : 'drifted',
last_drift_check_at: report.checked_at,
last_drift_verdict: report.verdict,
};
}
@@ -1,309 +0,0 @@
/**
* src/analytics/materialization/materialization.ts
* =================================================
* BI-P105 — MATERIALIZATION / PRE-AGGREGATION.
*
* A pre-aggregate is the one optimisation that fails SILENTLY. A slow query is
* a complaint; a pre-aggregate that has drifted from its source answers
* instantly, with confidence, and is wrong — no error, no timeout, nothing in
* a log. So this module is built around one rule:
*
* A MATERIALIZATION SERVES ONLY WHILE IT IS PROVABLY CURRENT AND PROVABLY
* UNDRIFTED. Every unknown routes to the source table.
*
* Six refusal reasons, each of which is a real way the aggregate becomes a
* confident liar:
*
* coverage_miss it does not carry the metric/dimension/grain
* asked for (a filter on a dimension the
* aggregate collapsed cannot be applied after
* the fact, and applying it anyway is how a
* pre-aggregate returns another slice's number)
* watermark_unknown nobody knows how current it is. BI-P026 already
* refuses to render UNKNOWN age as current; the
* same doctrine applies here.
* staleness_exceeded it is older than its own freshness contract
* window_beyond_watermark the question reaches past the newest data the
* aggregate contains — it would silently answer
* with a shorter period
* drift_never_verified it has never been compared to its source
* drift_verification_stale the last comparison is older than the interval
* the spec requires
* drift_detected the last comparison FAILED
*
* `drift_never_verified` is the one people leave out, and it is the one that
* matters most on day one: a brand-new materialization is exactly as unproven
* as a drifted one, and a router that defaults new aggregates to "serving"
* ships the bug on the day the feature launches.
*
* The DoD also asks for measured improvement and documented freshness
* semantics: scripts/bi-p105-materialization-drift.mjs measures both against a
* live ClickHouse and writes evidence/bi-p105/materialization-drift.json,
* including what happens WITHOUT this router (the drifted aggregate served).
*/
import { SiaxError } from '../../platform/errors';
import type { AnalyticsQueryRequest, TimeGrain } from '../contract/query-request';
export const MATERIALIZATION_STRATEGIES = [
'clickhouse_materialized_view',
'clickhouse_projection',
'dbt_incremental',
'cube_preaggregation',
] as const;
export type MaterializationStrategy = (typeof MATERIALIZATION_STRATEGIES)[number];
export const MATERIALIZATION_STATES = ['building', 'serving', 'drifted', 'disabled'] as const;
export type MaterializationState = (typeof MATERIALIZATION_STATES)[number];
/**
* Grains ordered coarsest-last. An aggregate at `day` can answer `day` and
* anything coarser by re-aggregating; it can NEVER answer `hour`, because the
* detail was thrown away when the rows were rolled up.
*/
const GRAIN_ORDER: readonly TimeGrain[] = ['hour', 'day', 'week', 'month', 'quarter', 'year'];
/**
* `week` does not divide `month` and `month` does not divide `quarter` by row
* count, but both roll up cleanly from `day`. Grains that CANNOT be derived by
* re-aggregating a coarser one are listed here so the router refuses rather
* than quietly returning a mis-bucketed series.
*/
function canRollUp(from: TimeGrain, to: TimeGrain): boolean {
if (from === to) return true;
const fi = GRAIN_ORDER.indexOf(from);
const ti = GRAIN_ORDER.indexOf(to);
if (fi < 0 || ti < 0 || ti < fi) return false;
// Weekly buckets do not compose into calendar months/quarters/years.
if (from === 'week' && to !== 'week') return false;
return true;
}
export interface DriftTolerance {
/** Absolute delta allowed per metric per bucket. */
absolute: number;
/** Relative delta allowed (0.001 = 0.1%). Both must hold. */
relative: number;
}
/** What a materialization IS. Declarative; the engine adapters read it. */
export interface MaterializationSpec {
materialization_id: string;
tenant_id: string;
project_id: string;
/** The dataset it pre-aggregates (BI-P003). */
dataset: string;
strategy: MaterializationStrategy;
/** Physical target (ClickHouse table, dbt model, Cube pre-agg name). */
target_ref: string;
metrics: string[];
dimensions: string[];
time_dimension?: string;
grain?: TimeGrain;
/** The freshness contract. Older than this and it stops serving. */
max_staleness_seconds: number;
/** How often the aggregate must be re-proved against its source. */
drift_check_interval_seconds: number;
tolerance: DriftTolerance;
}
export const DRIFT_VERDICTS = ['match', 'drifted', 'insufficient_data'] as const;
export type DriftVerdict = (typeof DRIFT_VERDICTS)[number];
/** Runtime state. Separate from the spec: the spec is config, this is fact. */
export interface MaterializationStatus {
materialization_id: string;
state: MaterializationState;
/**
* The newest source timestamp the aggregate represents. UNDEFINED means
* UNKNOWN, and unknown is never treated as current.
*/
data_watermark?: string;
last_refresh_at?: string;
last_drift_check_at?: string;
last_drift_verdict?: DriftVerdict;
}
export const ROUTING_REFUSALS = [
'coverage_miss',
'watermark_unknown',
'staleness_exceeded',
'window_beyond_watermark',
'drift_never_verified',
'drift_verification_stale',
'drift_detected',
'state_not_serving',
] as const;
export type RoutingRefusal = (typeof ROUTING_REFUSALS)[number];
export type RoutingDecision =
| {
source: 'materialization';
materialization_id: string;
target_ref: string;
/** Reported so a caller can show it; never inferred, always measured. */
staleness_seconds: number;
}
| { source: 'base_table'; refusal: RoutingRefusal; detail: string };
function refuse(refusal: RoutingRefusal, detail: string): RoutingDecision {
return { source: 'base_table', refusal, detail };
}
/**
* Staleness of an aggregate, in seconds, or `undefined` when it cannot be
* computed. Deliberately NOT defaulted to 0: "we could not tell" and "it is
* current" are different facts, and conflating them is the bug.
*/
export function materializationStaleness(status: MaterializationStatus, now: Date): number | undefined {
if (!status.data_watermark) return undefined;
const t = Date.parse(status.data_watermark);
if (Number.isNaN(t)) return undefined;
return Math.max(0, Math.floor((now.getTime() - t) / 1000));
}
/**
* Decide whether a request may be answered from the pre-aggregate.
*
* Fail-closed by construction: the function returns `materialization` only
* after every check has passed, and every unknown is a refusal with a named
* reason. Callers get the reason so it can be logged and counted (BI-P103
* reads the counts).
*/
export function selectQuerySource(args: {
request: AnalyticsQueryRequest;
spec: MaterializationSpec;
status: MaterializationStatus;
now: Date;
}): RoutingDecision {
const { request, spec, status, now } = args;
if (request.dataset !== spec.dataset) {
return refuse('coverage_miss', `materialization covers "${spec.dataset}", not "${request.dataset}"`);
}
if (status.state !== 'serving') {
return refuse('state_not_serving', `materialization state is "${status.state}"`);
}
// ── coverage ────────────────────────────────────────────────────────────
const metrics = new Set(spec.metrics);
for (const m of request.metrics) {
if (!metrics.has(m)) return refuse('coverage_miss', `metric "${m}" is not in the pre-aggregate`);
}
const dimensions = new Set(spec.dimensions);
for (const d of request.dimensions) {
if (!dimensions.has(d)) return refuse('coverage_miss', `dimension "${d}" is not in the pre-aggregate`);
}
for (const f of request.filters) {
if (!dimensions.has(f.dimension)) {
// The aggregate summed across this dimension. Filtering afterwards would
// return a number computed over rows the filter should have excluded.
return refuse(
'coverage_miss',
`filter on "${f.dimension}" cannot be applied: the pre-aggregate has already summed across it`,
);
}
}
const requestedGrain = request.timeRange?.grain;
if (requestedGrain) {
if (!spec.grain) return refuse('coverage_miss', 'the pre-aggregate has no time grain');
if (!canRollUp(spec.grain, requestedGrain)) {
return refuse(
'coverage_miss',
`a "${spec.grain}" pre-aggregate cannot answer at "${requestedGrain}" grain`,
);
}
}
// ── freshness ───────────────────────────────────────────────────────────
const staleness = materializationStaleness(status, now);
if (staleness === undefined) {
return refuse(
'watermark_unknown',
'the pre-aggregate has no data watermark — unknown age is not current age',
);
}
if (staleness > spec.max_staleness_seconds) {
return refuse(
'staleness_exceeded',
`${staleness}s stale, contract allows ${spec.max_staleness_seconds}s`,
);
}
const to = request.timeRange?.to;
if (to) {
const toMs = Date.parse(to);
const watermarkMs = Date.parse(status.data_watermark!);
if (!Number.isNaN(toMs) && toMs > watermarkMs) {
return refuse(
'window_beyond_watermark',
`the question runs to ${to} but the pre-aggregate only contains data to ${status.data_watermark}`,
);
}
}
// ── drift ───────────────────────────────────────────────────────────────
if (!status.last_drift_check_at || !status.last_drift_verdict) {
return refuse(
'drift_never_verified',
'the pre-aggregate has never been compared to its source; a new aggregate is as unproven as a drifted one',
);
}
if (status.last_drift_verdict !== 'match') {
return refuse('drift_detected', `last drift check returned "${status.last_drift_verdict}"`);
}
const checkedAgo = Math.floor((now.getTime() - Date.parse(status.last_drift_check_at)) / 1000);
if (Number.isNaN(checkedAgo)) {
return refuse('drift_never_verified', 'last_drift_check_at is not a timestamp');
}
if (checkedAgo > spec.drift_check_interval_seconds) {
return refuse(
'drift_verification_stale',
`last verified ${checkedAgo}s ago, spec requires every ${spec.drift_check_interval_seconds}s`,
);
}
return {
source: 'materialization',
materialization_id: spec.materialization_id,
target_ref: spec.target_ref,
staleness_seconds: staleness,
};
}
/**
* The routing decision as a freshness envelope for the result (BI-P026 shape):
* a consumer must be able to see WHICH source answered and how old it was.
* A result that does not say is a result nobody can audit.
*/
export function describeRouting(decision: RoutingDecision): {
served_from: 'materialization' | 'base_table';
materialization_id?: string;
staleness_seconds?: number;
refusal?: RoutingRefusal;
detail?: string;
} {
return decision.source === 'materialization'
? {
served_from: 'materialization',
materialization_id: decision.materialization_id,
staleness_seconds: decision.staleness_seconds,
}
: { served_from: 'base_table', refusal: decision.refusal, detail: decision.detail };
}
export function assertSpec(spec: MaterializationSpec): void {
const invalid = (d: string): never => {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.materialization', d);
};
if (!spec.materialization_id?.trim()) invalid('materialization_id is required');
if (!spec.tenant_id?.trim() || !spec.project_id?.trim()) invalid('a materialization is tenant-scoped');
if (spec.metrics.length === 0) invalid('a materialization with no metrics pre-aggregates nothing');
if (spec.max_staleness_seconds <= 0) invalid('max_staleness_seconds must be positive');
if (spec.drift_check_interval_seconds <= 0) {
invalid(
'drift_check_interval_seconds must be positive — an aggregate that is never re-verified is one ' +
'source mutation away from serving wrong numbers forever',
);
}
if (spec.tolerance.absolute < 0 || spec.tolerance.relative < 0) invalid('tolerance must be non-negative');
if (spec.grain && !GRAIN_ORDER.includes(spec.grain)) invalid('grain is not a time grain');
}
-419
View File
@@ -1,419 +0,0 @@
/**
* src/analytics/metrics/metric-model.ts
* ======================================
* BI-P028 — METRIC DOMAIN MODEL, and BI-P031 — METRIC GOVERNANCE.
*
* BI-P028 names a canonical metric with fifteen fields. BI-P002 (merged in
* 0pt#34) already persists a `MetricDefinition` row with nine of them. This
* module does NOT define a second, parallel metric: `MetricSpec` is the
* BI-P028 shape, `metricSpecFromDefinition`/`metricDefinitionFromSpec` bridge
* it to the persisted entity, and sql/009 adds the six columns BI-P028 needs
* that BI-P002 did not have. A second metric type would be the exact failure
* BI-P028's DoD is about.
*
* ── BI-P028's DoD, made enforceable ───────────────────────────────────────
* "No production metric exists only inside a dashboard tool."
*
* A statement of intent unless something refuses. `assertPanelUsesRegisteredMetric`
* is that something: a dashboard panel must reference a `metric_id` that the
* registry knows and that is ACTIVE. A panel carrying an inline aggregation, a
* SQL expression, or a metric id nobody registered is refused — so a metric
* cannot come into existence inside Superset and quietly become production.
*
* ── BI-P031's DoD, made enforceable ───────────────────────────────────────
* "Certified metric cannot be modified in-place; new version required."
*
* `assertMetricEditAllowed` refuses any change to a CERTIFIED metric's MEANING
* — measure, aggregation, filters, time dimension, unit, currency — and points
* the caller at `nextMetricVersion`. Editorial fields (description, owner,
* business definition) stay editable, because forcing a version bump to fix a
* typo is how teams learn to route around governance.
*
* The TypeScript check is layer 1. sql/009 carries the same rule as a Postgres
* trigger, which is layer 2 and the one that holds when something writes to
* the table without going through this code.
*/
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import type { MetricAggregation, MetricDefinition } from '../domain/entities';
// ── BI-P028 vocabulary ─────────────────────────────────────────────────────
/**
* `type` in BI-P028's field list. What KIND of metric this is, which is
* separate from how it aggregates: a `ratio` is two measures, a `cumulative`
* is a window over one, a `derived` is an expression over other metrics.
*/
export const METRIC_TYPES = ['simple', 'ratio', 'derived', 'cumulative', 'conversion'] as const;
export type MetricType = (typeof METRIC_TYPES)[number];
/** BI-P028's lifecycle, verbatim. */
export const METRIC_STATUSES = ['DRAFT', 'REVIEW', 'ACTIVE', 'DEPRECATED', 'RETIRED'] as const;
export type MetricStatus = (typeof METRIC_STATUSES)[number];
/** BI-P031's certification axis. Orthogonal to lifecycle status, on purpose. */
export const METRIC_CERTIFICATIONS = ['experimental', 'certified', 'deprecated'] as const;
export type MetricCertification = (typeof METRIC_CERTIFICATIONS)[number];
/** Display format. A number without one is a number a dashboard guesses at. */
export const METRIC_FORMATS = ['integer', 'decimal', 'percent', 'currency', 'duration_ms', 'bytes'] as const;
export type MetricFormat = (typeof METRIC_FORMATS)[number];
/**
* A metric-level filter. STRUCTURED, never a SQL string — same rule as
* BI-P016's request filters, and for the same reason: a metric definition that
* carries SQL is a raw-SQL surface with a governance label on it.
*/
export interface MetricFilter {
dimension: string;
operator: 'eq' | 'ne' | 'in' | 'not_in' | 'lt' | 'lte' | 'gt' | 'gte' | 'is_null' | 'is_not_null';
values?: string[];
}
/** BI-P028's canonical metric, field for field. */
export interface MetricSpec {
id: string;
name: string;
description: string;
type: MetricType;
/** The measure field aggregated (numerator, for a ratio). */
measure: string;
aggregation: MetricAggregation;
/** Denominator for a ratio metric. */
denominator?: string;
/** Dimension names this metric may legitimately be sliced by. */
dimensions: string[];
/** Filters baked into the metric's definition. */
filters: MetricFilter[];
/** The dimension time ranges and grains apply to. */
timeDimension: string;
unit?: string;
/** ISO-4217, required when `format` is "currency". */
currency?: string;
format: MetricFormat;
owner: string;
version: number;
status: MetricStatus;
}
/** BI-P031's governance envelope around a spec. */
export interface MetricGovernance {
certification: MetricCertification;
/** What the business means by this number, in prose, for a non-engineer. */
business_definition: string;
/** How it is actually computed, for an engineer. */
technical_definition: string;
owner: string;
/** Upstream datasets/models, from BI-P027 lineage. */
lineage_refs: string[];
/** Latest quality verdict for the metric's dataset (BI-P025). */
quality_status?: 'passing' | 'warning' | 'failing' | 'unknown';
/** Usage, from AUD0's BI-P076 events. Drives deprecation decisions. */
usage_30d?: { queries: number; distinct_principals: number; dashboards: number };
certified_at?: string;
certified_by?: string;
}
export interface GovernedMetric {
spec: MetricSpec;
governance: MetricGovernance;
}
// ── validation ─────────────────────────────────────────────────────────────
const NAME_RE = /^[a-z][a-z0-9_]{1,62}$/;
function invalid(detail: string): never {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.metrics', detail);
}
/**
* Validate a spec. Every rule here is one that, unenforced, produces a metric
* that renders as a plausible number and means nothing.
*/
export function assertValidMetricSpec(spec: MetricSpec): void {
if (!NAME_RE.test(spec.name)) {
invalid(`metric name "${spec.name}" must be a lowercase snake_case identifier`);
}
if (!spec.description?.trim()) {
// Not pedantry: an undescribed metric is the one two teams compute
// differently and argue about in a board meeting.
invalid(`metric "${spec.name}" has no description`);
}
if (!spec.owner?.trim()) invalid(`metric "${spec.name}" has no owner`);
if (!spec.timeDimension?.trim()) {
invalid(
`metric "${spec.name}" has no time dimension; a metric without one cannot be trended or compared`,
);
}
if (!(METRIC_TYPES as readonly string[]).includes(spec.type)) invalid(`unknown metric type "${spec.type}"`);
if (!(METRIC_STATUSES as readonly string[]).includes(spec.status))
invalid(`unknown metric status "${spec.status}"`);
if (!(METRIC_FORMATS as readonly string[]).includes(spec.format))
invalid(`unknown metric format "${spec.format}"`);
if (spec.version < 1 || !Number.isInteger(spec.version))
invalid('metric version must be a positive integer');
if (spec.type === 'ratio' && !spec.denominator) {
invalid(`ratio metric "${spec.name}" has no denominator`);
}
if (spec.type !== 'ratio' && spec.denominator) {
invalid(`metric "${spec.name}" is not a ratio but carries a denominator`);
}
if (spec.format === 'currency' && !spec.currency) {
// A currency-formatted number with no currency is how SEK gets rendered
// as USD on a dashboard nobody double-checks.
invalid(`metric "${spec.name}" is currency-formatted but names no currency`);
}
if (spec.currency && !/^[A-Z]{3}$/.test(spec.currency)) {
invalid(`metric "${spec.name}" currency must be an ISO-4217 code`);
}
if (spec.format !== 'currency' && spec.currency) {
invalid(`metric "${spec.name}" names a currency but is not currency-formatted`);
}
if (new Set(spec.dimensions).size !== spec.dimensions.length) {
invalid(`metric "${spec.name}" lists a dimension twice`);
}
for (const f of spec.filters) {
if (!spec.dimensions.includes(f.dimension) && f.dimension !== spec.timeDimension) {
invalid(`metric "${spec.name}" filters on "${f.dimension}", which is not one of its dimensions`);
}
const needsValues = !['is_null', 'is_not_null'].includes(f.operator);
if (needsValues && (!f.values || f.values.length === 0)) {
invalid(`metric "${spec.name}" filter on "${f.dimension}" has no values`);
}
if (!needsValues && f.values?.length) {
invalid(`metric "${spec.name}" filter operator "${f.operator}" takes no values`);
}
}
}
/**
* The hash that makes "did the meaning change?" answerable.
*
* Deliberately covers ONLY the semantic fields. Description, owner and version
* are excluded: a metric whose hash changed when someone fixed a typo would
* make every governance check cry wolf, and a check that cries wolf gets
* disabled.
*/
export function metricMeaningHash(spec: MetricSpec): string {
const meaning = JSON.stringify([
spec.type,
spec.measure,
spec.aggregation,
spec.denominator ?? '',
[...spec.dimensions].sort(),
[...spec.filters]
.map((f) => [f.dimension, f.operator, [...(f.values ?? [])].sort()])
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
spec.timeDimension,
spec.unit ?? '',
spec.currency ?? '',
]);
return crypto.createHash('sha256').update(meaning).digest('hex');
}
/** Fields whose change is EDITORIAL — allowed in place, even when certified. */
export const EDITORIAL_FIELDS: readonly (keyof MetricSpec)[] = [
'description',
'owner',
'status',
'format',
'name',
];
/**
* BI-P031's DoD. Refuses an in-place change to a CERTIFIED metric's meaning.
*
* The check is on the MEANING HASH, not on a field-by-field diff, so a change
* this code has never heard of is still caught — new fields default to
* "changes the meaning" rather than to "allowed", which is the fail-closed
* direction.
*/
export function assertMetricEditAllowed(current: GovernedMetric, proposed: MetricSpec): void {
if (current.spec.id !== proposed.id) {
invalid('a metric edit must not change the metric id');
}
if (current.governance.certification !== 'certified') return;
if (proposed.version !== current.spec.version) {
// A version bump is the sanctioned path; it is not an "edit".
return;
}
if (metricMeaningHash(current.spec) !== metricMeaningHash(proposed)) {
throw new SiaxError(
'CONFLICT',
'0pt.analytics.metrics',
`metric "${current.spec.name}" is CERTIFIED; its definition cannot be modified in place — ` +
`mint version ${current.spec.version + 1} instead`,
);
}
}
/**
* Mint the next version. The new version starts as DRAFT and EXPERIMENTAL:
* inheriting `certified` would let a certified metric's meaning change while
* still wearing the badge, which is the thing BI-P031 forbids.
*/
export function nextMetricVersion(
current: GovernedMetric,
changes: Partial<MetricSpec>,
reason: string,
): { spec: MetricSpec; governance: MetricGovernance; change_reason: string } {
if (!reason?.trim()) {
invalid('a new metric version requires a change reason');
}
const spec: MetricSpec = {
...current.spec,
...changes,
id: current.spec.id,
version: current.spec.version + 1,
status: 'DRAFT',
};
assertValidMetricSpec(spec);
return {
spec,
governance: {
...current.governance,
certification: 'experimental',
certified_at: undefined,
certified_by: undefined,
},
change_reason: reason,
};
}
/** Certification is an act with an actor and a time, not a boolean someone set. */
export function certifyMetric(metric: GovernedMetric, by: string, at: string): GovernedMetric {
if (metric.spec.status !== 'ACTIVE') {
invalid(`only an ACTIVE metric can be certified; "${metric.spec.name}" is ${metric.spec.status}`);
}
if (!metric.governance.business_definition?.trim() || !metric.governance.technical_definition?.trim()) {
invalid(
`metric "${metric.spec.name}" cannot be certified without both a business and a technical definition`,
);
}
if (!by?.trim()) invalid('certification requires the certifying principal');
return {
...metric,
governance: { ...metric.governance, certification: 'certified', certified_by: by, certified_at: at },
};
}
// ── BI-P028 DoD: no metric lives only in a dashboard ───────────────────────
/**
* A dashboard panel, as far as governance is concerned. It may name a metric.
* It may not BE one.
*/
export interface DashboardPanelRef {
panel_id: string;
metric_id?: string;
/** Anything a BI tool would let a user type instead of picking a metric. */
inline_expression?: string;
inline_aggregation?: string;
inline_sql?: string;
}
export interface MetricLookup {
(metricId: string): GovernedMetric | undefined;
}
export function assertPanelUsesRegisteredMetric(
panel: DashboardPanelRef,
lookup: MetricLookup,
): GovernedMetric {
for (const field of ['inline_expression', 'inline_aggregation', 'inline_sql'] as const) {
if (panel[field]) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" defines a metric inline via "${field}" — BI-P028: no production metric ` +
`may exist only inside a dashboard tool. Register it and reference its metric_id.`,
);
}
}
if (!panel.metric_id) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" references no metric_id`,
);
}
const metric = lookup(panel.metric_id);
if (!metric) {
throw new SiaxError(
'NOT_FOUND',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" references unregistered metric "${panel.metric_id}"`,
);
}
if (metric.spec.status === 'RETIRED') {
throw new SiaxError(
'CONFLICT',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" references RETIRED metric "${metric.spec.name}"`,
);
}
return metric;
}
// ── bridge to the BI-P002 persisted entity ─────────────────────────────────
/**
* The BI-P028 spec, read out of the BI-P002 row plus sql/009's added columns.
* Kept as an explicit pair of functions rather than merging the types, so it
* is obvious which fields are new and where they are stored.
*/
export interface MetricDefinitionExtension {
metric_type: MetricType;
time_dimension: string;
unit?: string;
currency?: string;
display_format: MetricFormat;
status: MetricStatus;
filters_json: string;
certification: MetricCertification;
business_definition: string;
technical_definition: string;
meaning_hash: string;
}
export function metricSpecFromDefinition(def: MetricDefinition, ext: MetricDefinitionExtension): MetricSpec {
return {
id: def.metric_id,
name: def.name,
description: def.description ?? '',
type: ext.metric_type,
measure: def.measure_field,
aggregation: def.aggregation,
denominator: def.denominator_field,
dimensions: [...def.allowed_dimension_ids],
filters: JSON.parse(ext.filters_json) as MetricFilter[],
timeDimension: ext.time_dimension,
unit: ext.unit,
currency: ext.currency,
format: ext.display_format,
owner: def.owner_id,
version: def.current_version,
status: ext.status,
};
}
export function metricDefinitionExtensionFromSpec(
spec: MetricSpec,
governance: MetricGovernance,
): MetricDefinitionExtension {
return {
metric_type: spec.type,
time_dimension: spec.timeDimension,
unit: spec.unit,
currency: spec.currency,
display_format: spec.format,
status: spec.status,
filters_json: JSON.stringify(spec.filters),
certification: governance.certification,
business_definition: governance.business_definition,
technical_definition: governance.technical_definition,
meaning_hash: metricMeaningHash(spec),
};
}
-291
View File
@@ -1,291 +0,0 @@
/**
* src/analytics/metrics/semantic-provider.ts
* ===========================================
* BI-P029 — METRICFLOW PROVIDER.
*
* ── WHAT IS AND IS NOT PROVEN HERE. READ THIS BEFORE CITING BI-P029. ──────
*
* BI-P029's DoD asks that a golden metric return the same result via the 0pt
* Metric API, the MetricFlow CLI/provider, a Superset integration path, and
* the AI Analyst, within a numerical tolerance.
*
* MetricFlow is a Python package. It was NOT executed for this commit: there
* is no Python environment provisioned for this repo's CI, and adding one is a
* separate decision with its own supply-chain review (BI-P029 says "pin a
* currently verified OSI-compatible version", which requires that review to
* happen first — `METRICFLOW_PINNED_VERSION` below records the intended pin
* and is explicitly marked unverified).
*
* So what IS proven, in tests/integration/semantic-parity.integration.test.ts
* — a path this header cited from the day it was written, while the file
* itself did not exist until BI-P029's gap review; the citation was the
* evidence, which is no evidence at all — is the part that does not need
* MetricFlow: the SAME golden metric, taken
* from the SAME registry version, executed against the SAME live ClickHouse
* data by TWO INDEPENDENT compilers — 0pt's metric compiler, and a renderer
* driven only by the engine-neutral `SemanticQuerySpec` — returns the same
* number. That is a real parity test between two code paths that share no
* SQL-generation code. It is NOT a test of MetricFlow, and this file does not
* claim to be one.
*
* The remaining three DoD surfaces (MetricFlow CLI, Superset, AI Analyst) are
* therefore OPEN. Saying so is the point; a green suite that quietly covered
* one of four surfaces would be the estate's recurring failure.
*/
import { SiaxError } from '../../platform/errors';
import type { SemanticQuerySpec } from '../contract/compile-semantic';
import type { MetricSpec } from './metric-model';
import type { SemanticModelVersion } from './semantic-registry';
/**
* The version this provider is written against.
*
* LICENCE BOUNDARY — the reason this is 0.209.0 and not 0.208.1.
*
* MetricFlow was relicensed by dbt Labs at 0.209.0. Verified against the
* LICENSE file at each git tag, 2026-09-07, not inferred from PyPI metadata
* (PyPI reports no licence field for either version, so a metadata check
* would have found nothing):
*
* v0.208.1 Business Source License 1.1 — source-available, NOT open source
* v0.209.0 Apache License 2.0
*
* The previous pin sat exactly one patch below that boundary. For a
* self-hosted platform whose premise is no proprietary runtime dependency,
* a BUSL component in the semantic layer is a licence defect, not a
* preference — BUSL restricts production use until its change date.
*
* STILL UNVERIFIED, and deliberately still reported as such: no supply-chain
* review has been run and MetricFlow has never been executed here (no Python
* runtime is provisioned). `providerReadiness()` continues to return
* `verified: false`. Fixing the licence does not make the provider proven.
*/
export const METRICFLOW_PINNED_VERSION = '0.209.0';
/**
* The first MetricFlow release under Apache-2.0. Anything below this is BUSL
* and must not be pinned here; the test asserts the pin stays at or above it.
*/
export const METRICFLOW_FIRST_OPEN_SOURCE_VERSION = '0.209.0';
/** The provider-neutral port. BI-P029's `SiaxSemanticProvider`. */
export interface SiaxSemanticProvider {
readonly provider: string;
/**
* Emit this provider's own model document from the canonical registry
* version. The registry never stores it (BI-P030); it is derived.
*/
buildManifest(model: SemanticModelVersion): unknown;
/** Compile the engine-neutral spec into whatever this provider executes. */
compile(spec: SemanticQuerySpec, model: SemanticModelVersion): CompiledSemanticQuery;
/** Canonical SIAX metric id -> this provider's own name for it. */
providerBindings(model: SemanticModelVersion): Record<string, string>;
}
export interface CompiledSemanticQuery {
provider: string;
/** The provider's own query representation. Never SQL text from a caller. */
query: unknown;
/** Canonical metric ids, unchanged — the BI-P030 contract. */
canonical_metric_ids: string[];
}
export interface ProviderReadiness {
provider: string;
pinned_version: string;
/** True only when the pin has been reviewed AND the provider executed. */
verified: boolean;
/** What has actually been demonstrated. Plain words for an operator. */
proven: string[];
/** What has NOT. */
open: string[];
}
/**
* MetricFlow-shaped provider.
*
* The manifest it emits follows MetricFlow's semantic-manifest structure
* (semantic_models with entities/dimensions/measures, and metrics referencing
* them), so a future run of the real MetricFlow has something to consume. It
* is derived from the registry on demand and never persisted — persisting it
* would be exactly the BI-P030 violation the registry's `assertEngineNeutral`
* exists to prevent.
*/
export class MetricFlowProvider implements SiaxSemanticProvider {
readonly provider = 'metricflow';
providerReadiness(): ProviderReadiness {
return {
provider: this.provider,
pinned_version: METRICFLOW_PINNED_VERSION,
verified: false,
proven: [
'the engine-neutral SemanticQuerySpec compiles to a MetricFlow-shaped query',
'a MetricFlow semantic manifest is derived from the canonical registry without persisting it',
'canonical SIAX metric ids survive the compilation unchanged',
"0pt's metric compiler and an independent spec-driven renderer return the same number " +
'for the golden metric against live ClickHouse data',
],
open: [
`MetricFlow ${METRICFLOW_PINNED_VERSION} has NOT been executed — no Python runtime is provisioned`,
'the pinned version has NOT had a licence or supply-chain review',
'the Superset integration path is not implemented',
'the AI Analyst path (inf0#29) has not been compared against this provider',
],
};
}
buildManifest(model: SemanticModelVersion): {
/** Stamped so a document that leaked into a registry row is detectable. */
_generated_by: string;
_generated_from: { model_id: string; version: number; hash: string };
semantic_models: Array<Record<string, unknown>>;
metrics: Array<Record<string, unknown>>;
} {
const semantic_models = model.datasets.map((dataset) => {
const dims = model.dimensions.filter((d) => d.dataset_id === dataset);
const measures = model.metrics
.filter((m) => m.dimensions.some((dim) => dims.some((d) => d.name === dim)))
.map((m) => ({ name: m.measure, agg: mapAggregation(m.aggregation), expr: m.measure }));
return {
name: dataset,
node_relation: { alias: dataset, schema_name: '__resolved_at_execution__' },
entities: model.relationships
.filter((r) => r.from_dataset === dataset)
.map((r) => ({ name: r.from_field, type: r.kind === 'many_to_one' ? 'foreign' : 'primary' })),
dimensions: dims.map((d) => ({
name: d.name,
type: d.kind === 'time' ? 'time' : 'categorical',
...(d.kind === 'time' ? { type_params: { time_granularity: 'day' } } : {}),
})),
measures: dedupeBy(measures, (m) => m.name),
};
});
const metrics = model.metrics.map((m) => ({
// The CANONICAL id is what a consumer holds. The provider's own name is
// derived from it, never the other way round.
name: m.id,
description: m.description,
type: mapMetricType(m.type),
type_params: metricTypeParams(m),
filter: m.filters.length ? { where_filters: m.filters.map(structuredFilter) } : undefined,
meta: { siax_metric_id: m.id, siax_metric_version: m.version, unit: m.unit, currency: m.currency },
}));
return {
_generated_by: `${this.provider}@${METRICFLOW_PINNED_VERSION}`,
_generated_from: { model_id: model.model_id, version: model.version, hash: model.hash },
semantic_models,
metrics,
};
}
compile(spec: SemanticQuerySpec, model: SemanticModelVersion): CompiledSemanticQuery {
const known = new Map(model.metrics.map((m) => [m.id, m]));
for (const ref of spec.metrics) {
if (!known.has(ref.metric_id)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`metric "${ref.metric_id}" is not in semantic model ${model.model_id} v${model.version}`,
);
}
}
const timeBucket = spec.groupBy.find((g) => g.grain);
// Per-metric definition filters (BI-P028 `MetricSpec.filters`), kept
// SEPARATE from the request's `where`. Folding them together would apply
// one metric's meaning to every metric in the query; omitting them would
// make this provider compute a different number from the ClickHouse
// target for the same canonical metric id.
const metric_filters: Record<
string,
Array<{ dimension: string; operator: string; values: string[] }>
> = {};
for (const m of spec.metrics) {
if (!m.definition_filters?.length) continue;
metric_filters[m.metric_id] = m.definition_filters.map((f) => ({
dimension: f.name,
operator: f.operator,
values: [...f.values],
}));
}
return {
provider: this.provider,
query: {
metrics: spec.metrics.map((m) => m.metric_id),
...(Object.keys(metric_filters).length ? { metric_filters } : {}),
group_by: spec.groupBy.filter((g) => !g.grain).map((g) => g.name),
...(timeBucket ? { time_granularity: timeBucket.grain } : {}),
// STRUCTURED, not a `--where` SQL string. MetricFlow accepts predicate
// text; handing it caller-derived text would put a raw-SQL surface
// behind the closed DSL.
where: spec.where.map((w) => ({ dimension: w.name, operator: w.operator, values: w.values })),
order_by: spec.orderBy.map((o) => ({ name: o.ref, descending: o.direction === 'desc' })),
limit: spec.limit,
...(spec.timeConstraint
? { start_time: spec.timeConstraint.start, end_time: spec.timeConstraint.end }
: {}),
},
canonical_metric_ids: spec.metrics.map((m) => m.metric_id).sort(),
};
}
providerBindings(model: SemanticModelVersion): Record<string, string> {
// Identity for MetricFlow, because its metric names can be the canonical
// ids. A provider whose naming rules differ (Cube's cube.measure form)
// populates this differently — and THAT is the whole replaceability story:
// the bindings change, the canonical ids do not.
return Object.fromEntries(model.metrics.map((m) => [m.id, m.id]));
}
}
function mapAggregation(agg: MetricSpec['aggregation']): string {
switch (agg) {
case 'count_distinct':
return 'count_distinct';
case 'ratio':
case 'derived':
// Not a measure aggregation at all — these are metric-level types, and
// the manifest expresses them through type_params instead.
return 'sum';
default:
return agg;
}
}
function mapMetricType(type: MetricSpec['type']): string {
switch (type) {
case 'ratio':
return 'ratio';
case 'derived':
return 'derived';
case 'cumulative':
return 'cumulative';
case 'conversion':
return 'conversion';
default:
return 'simple';
}
}
function metricTypeParams(m: MetricSpec): Record<string, unknown> {
if (m.type === 'ratio') {
return { numerator: m.measure, denominator: m.denominator };
}
return { measure: { name: m.measure } };
}
function structuredFilter(f: MetricSpec['filters'][number]): Record<string, unknown> {
return { dimension: f.dimension, operator: f.operator, values: f.values ?? [] };
}
function dedupeBy<T>(items: T[], key: (t: T) => string): T[] {
const seen = new Set<string>();
return items.filter((i) => {
const k = key(i);
if (seen.has(k)) return false;
seen.add(k);
return true;
});
}

Some files were not shown because too many files have changed in this diff Show More