/** * src/analytics/metrics/semantic-registry.ts * =========================================== * BI-P030 — SEMANTIC MODEL REGISTRY. * * "Persist semantic model version SEPARATELY FROM IMPLEMENTATION ENGINE. * DoD: MetricFlow can be replaced without breaking canonical SIAX metric IDs." * * Which means exactly one thing in code, and it is a negative: NOTHING in this * file may name MetricFlow, Cube, dbt, ClickHouse, Trino or DuckDB. A registry * that stores a MetricFlow manifest is a MetricFlow registry with a neutral * name on it. `assertEngineNeutral` enforces the negative at runtime by * scanning a serialized version for engine vocabulary, and the test asserts it * catches a manifest that smuggles one in — because the rule is exactly the * kind that decays silently. * * The canonical SIAX metric id is the contract. A provider maps it to whatever * its own model calls that metric (BI-P029's `providerBindings`), and swapping * providers changes the BINDINGS, never the ids — so a dashboard, an API * consumer or a saved query keeps working. */ import crypto from 'node:crypto'; import { SiaxError } from '../../platform/errors'; import type { MetricSpec } from './metric-model'; export const SEMANTIC_MODEL_STATUSES = ['draft', 'active', 'superseded', 'retired'] as const; export type SemanticModelStatus = (typeof SEMANTIC_MODEL_STATUSES)[number]; export const RELATIONSHIP_KINDS = ['one_to_many', 'many_to_one', 'one_to_one'] as const; export type RelationshipKind = (typeof RELATIONSHIP_KINDS)[number]; export interface SemanticRelationship { from_dataset: string; from_field: string; to_dataset: string; to_field: string; kind: RelationshipKind; } export interface SemanticDimension { id: string; name: string; dataset_id: string; /** "categorical" | "time". A time dimension is what grains apply to. */ kind: 'categorical' | 'time'; } /** BI-P030's fields, verbatim. */ export interface SemanticModelVersion { model_id: string; version: number; tenant_id: string; datasets: string[]; relationships: SemanticRelationship[]; /** Canonical SIAX metric ids and their specs at this version. */ metrics: MetricSpec[]; dimensions: SemanticDimension[]; valid_from: string; status: SemanticModelStatus; hash: string; } /** * Engine vocabulary that must never appear in a persisted semantic model. * * Checked against the SERIALIZED version, so it catches an engine name hiding * in a nested field somebody added later — the failure mode a type cannot * prevent. */ const ENGINE_VOCABULARY = [ 'metricflow', 'clickhouse', 'trino', 'duckdb', 'cube.js', 'cubejs', 'dbt_metric', 'superset', 'presto', 'bigquery', 'snowflake', ]; /** The only top-level keys a persisted semantic model may carry. */ export const SEMANTIC_MODEL_KEYS = [ 'model_id', 'version', 'tenant_id', 'datasets', 'relationships', 'metrics', 'dimensions', 'valid_from', 'status', 'hash', ] as const; /** * The STRUCTURAL half of engine neutrality, and the load-bearing one. * * `assertEngineNeutral` below is a VOCABULARY scan: it catches a model that * says "metricflow" or "clickhouse". It cannot catch a document that is * structurally MetricFlow-shaped while avoiding the word — a limitation found * by a test that expected it to and did not. So publishing also rejects any * key outside the BI-P030 field list, which means a provider manifest cannot * be stored in a registry row at all, whatever it calls itself. */ export function assertOnlySemanticModelFields(model: object): void { for (const key of Object.keys(model)) { if (!(SEMANTIC_MODEL_KEYS as readonly string[]).includes(key)) { throw new SiaxError( 'INVALID_REQUEST', '0pt.analytics.semantic', `semantic model carries field "${key}", which is not part of BI-P030's model — ` + `provider manifests are DERIVED on demand, never persisted`, ); } } } export function assertEngineNeutral(model: Omit): void { const serialized = JSON.stringify(model).toLowerCase(); for (const term of ENGINE_VOCABULARY) { if (serialized.includes(term)) { throw new SiaxError( 'INVALID_REQUEST', '0pt.analytics.semantic', `semantic model "${model.model_id}" mentions "${term}" — BI-P030 requires the model to be ` + `persisted separately from any implementation engine, so it can be replaced without ` + `breaking canonical SIAX metric ids`, ); } } } /** * The version hash. Covers everything that defines the model's MEANING; * `valid_from` and `status` are excluded because activating a model does not * change what it says. */ export function semanticModelHash( model: Omit, ): string { const canonical = JSON.stringify([ model.model_id, model.version, model.tenant_id, [...model.datasets].sort(), [...model.relationships] .map((r) => [r.from_dataset, r.from_field, r.to_dataset, r.to_field, r.kind]) .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), [...model.metrics].map((m) => [m.id, m.version]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))), [...model.dimensions].map((d) => [d.id, d.name, d.dataset_id, d.kind]).sort(), ]); return crypto.createHash('sha256').update(canonical).digest('hex'); } export interface SemanticModelStore { put(model: SemanticModelVersion): Promise; get(tenantId: string, modelId: string, version: number): Promise; active(tenantId: string, modelId: string): Promise; versions(tenantId: string, modelId: string): Promise; } export class InMemorySemanticModelStore implements SemanticModelStore { private readonly rows = new Map(); private key(t: string, m: string, v: number): string { return `${t}::${m}::${v}`; } async put(model: SemanticModelVersion): Promise { this.rows.set(this.key(model.tenant_id, model.model_id, model.version), model); } async get(t: string, m: string, v: number): Promise { return this.rows.get(this.key(t, m, v)); } async versions(t: string, m: string): Promise { return [...this.rows.values()] .filter((r) => r.tenant_id === t && r.model_id === m) .sort((a, b) => a.version - b.version); } async active(t: string, m: string): Promise { return (await this.versions(t, m)).find((r) => r.status === 'active'); } } export class SemanticModelRegistry { constructor(private readonly store: SemanticModelStore) {} /** * Publish a new version. Versions are IMMUTABLE — re-publishing an existing * (model, version) is a CONFLICT, not an update, because a dashboard pinned * to version 7 must mean the same thing tomorrow. */ async publish(input: Omit): Promise { if (!input.tenant_id?.trim()) { throw new SiaxError( 'UNAUTHENTICATED', '0pt.analytics.semantic', 'a semantic model requires a verified tenant', ); } if (input.version < 1 || !Number.isInteger(input.version)) { throw new SiaxError('INVALID_REQUEST', '0pt.analytics.semantic', 'version must be a positive integer'); } assertOnlySemanticModelFields(input); assertEngineNeutral(input); this.assertReferentialIntegrity(input); const existing = await this.store.get(input.tenant_id, input.model_id, input.version); if (existing) { throw new SiaxError( 'CONFLICT', '0pt.analytics.semantic', `semantic model ${input.model_id} v${input.version} already exists and is immutable`, ); } const model: SemanticModelVersion = { ...input, hash: semanticModelHash(input) }; await this.store.put(model); return model; } /** Activate a version, superseding the previous active one. */ async activate( tenantId: string, modelId: string, version: number, at: string, ): Promise { const target = await this.store.get(tenantId, modelId, version); if (!target) throw new SiaxError('NOT_FOUND', '0pt.analytics.semantic', 'semantic model version not found'); if (target.status === 'retired') { throw new SiaxError('CONFLICT', '0pt.analytics.semantic', 'a retired version cannot be re-activated'); } const current = await this.store.active(tenantId, modelId); if (current && current.version !== version) { await this.store.put({ ...current, status: 'superseded' }); } const activated = { ...target, status: 'active' as const, valid_from: at }; await this.store.put(activated); return activated; } /** * BI-P030's DoD, as a query: the canonical metric ids a model exposes. * The engine-parity test asserts this set is identical before and after a * provider swap. */ async canonicalMetricIds(tenantId: string, modelId: string, version: number): Promise { const model = await this.store.get(tenantId, modelId, version); if (!model) throw new SiaxError('NOT_FOUND', '0pt.analytics.semantic', 'semantic model version not found'); return model.metrics.map((m) => m.id).sort(); } /** * Every dimension and dataset a metric names must exist in the model. * * A model that passes validation while referencing a dimension nobody * defined produces a metric that fails at query time, per tenant, in * production — the worst place to find out. */ private assertReferentialIntegrity(model: Omit): void { const datasets = new Set(model.datasets); const dimensionNames = new Set(model.dimensions.map((d) => d.name)); const timeDimensions = new Set(model.dimensions.filter((d) => d.kind === 'time').map((d) => d.name)); for (const d of model.dimensions) { if (!datasets.has(d.dataset_id)) { throw new SiaxError( 'INVALID_REQUEST', '0pt.analytics.semantic', `dimension "${d.name}" belongs to dataset "${d.dataset_id}", which the model does not include`, ); } } for (const r of model.relationships) { for (const ds of [r.from_dataset, r.to_dataset]) { if (!datasets.has(ds)) { throw new SiaxError( 'INVALID_REQUEST', '0pt.analytics.semantic', `relationship references dataset "${ds}", which the model does not include`, ); } } } const seenIds = new Set(); for (const m of model.metrics) { if (seenIds.has(m.id)) { throw new SiaxError( 'CONFLICT', '0pt.analytics.semantic', `metric id "${m.id}" appears twice in the model`, ); } seenIds.add(m.id); for (const dim of m.dimensions) { if (!dimensionNames.has(dim)) { throw new SiaxError( 'INVALID_REQUEST', '0pt.analytics.semantic', `metric "${m.name}" names dimension "${dim}", which the model does not define`, ); } } if (!timeDimensions.has(m.timeDimension)) { throw new SiaxError( 'INVALID_REQUEST', '0pt.analytics.semantic', `metric "${m.name}" names time dimension "${m.timeDimension}", which the model does not define as a time dimension`, ); } } } }