Files
0pt/src/analytics/metrics/semantic-registry.ts
T
Claude Opus 5 65cce86144
CI (SIAX Cloud) / security (push) Successful in 29s
CI (SIAX Cloud) / integration (push) Successful in 52s
CI (SIAX Cloud) / quality (push) Successful in 1m10s
Security Scan (SIAX Cloud) / security (push) Successful in 25s
CI (SIAX Cloud) / security (pull_request) Successful in 29s
CI (SIAX Cloud) / integration (pull_request) Successful in 53s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m13s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 22s
feat(analytics): BI-P028/BI-P029/BI-P030/BI-P031 — metric model, semantic registry, governance, semantic provider
BI-P028 extends the BI-P002 MetricDefinition rather than defining a second,
parallel metric — a second metric type would be the exact failure the DoD is
about. `MetricSpec` is the fifteen-field shape the prompt names; explicit
bridge functions map it onto the persisted row plus the six columns it adds.

The DoD ("no production metric exists only inside a dashboard tool") is
enforced by something that refuses: a dashboard panel carrying an inline
expression, inline aggregation or inline SQL is rejected, as is one naming an
unregistered or RETIRED metric. So a metric cannot come into existence inside
Superset and quietly become production.

Validation refuses the metrics that render as a plausible number and mean
nothing: no description, no owner, no time dimension, a ratio without a
denominator, a currency format with no currency (which is how SEK gets
rendered as USD), a filter on a dimension the metric does not declare.

BI-P031's DoD is checked on a MEANING HASH rather than a field diff, so a
field this code has never heard of still counts as changing the meaning —
fail-closed rather than fail-open on future additions. Eight semantic fields
are each mutated and each refused; three editorial fields are each mutated and
each allowed, because forcing a version bump to fix a typo is how teams learn
to route around governance. A new version starts DRAFT and EXPERIMENTAL: it
never inherits the certification, or a certified metric's meaning could change
while still wearing the badge.

BI-P030 stores the semantic model separately from any engine, and that
negative is enforced two ways after the first way turned out to be
insufficient:
  * a VOCABULARY scan rejects a model mentioning metricflow / clickhouse /
    trino / cube / superset anywhere in its serialized form;
  * a STRUCTURAL check rejects any top-level key outside BI-P030's field list.
The second exists because a test expected the vocabulary scan to catch a
MetricFlow-shaped manifest and it did not — the manifest never says
"metricflow". The structural check holds regardless of what a document calls
itself. The manifest is now also stamped with its generator so a leaked copy
is detectable.

The replaceability DoD is tested with TWO providers whose naming rules differ
(MetricFlow-shaped and Cube-shaped, `ds_sales.amount_sek`): the canonical id
set must be identical across both AND the provider bindings must differ —
otherwise the equality would hold trivially for a registry that only ever had
one provider.

BI-P029 — WHAT IS NOT PROVEN IS STATED IN THE MODULE AND RETURNED BY THE CODE.
MetricFlow is a Python package and was NOT executed: no Python runtime is
provisioned here, and BI-P029's "pin a currently verified version" requires a
licence/supply-chain review that has not happened. `providerReadiness()`
returns `verified: false` and names all four open items, including that the
Superset path is unimplemented and the AI Analyst path uncompared. The
constant `METRICFLOW_PINNED_VERSION` is labelled a declared intent, not a
certification. A test asserts the readiness report says so, so the honesty
cannot rot silently.

353 tests. typecheck + eslint clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 02:34:52 +02:00

317 lines
11 KiB
TypeScript

/**
* 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<SemanticModelVersion, 'hash'>): 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<SemanticModelVersion, 'hash' | 'valid_from' | 'status'>,
): 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<void>;
get(tenantId: string, modelId: string, version: number): Promise<SemanticModelVersion | undefined>;
active(tenantId: string, modelId: string): Promise<SemanticModelVersion | undefined>;
versions(tenantId: string, modelId: string): Promise<SemanticModelVersion[]>;
}
export class InMemorySemanticModelStore implements SemanticModelStore {
private readonly rows = new Map<string, SemanticModelVersion>();
private key(t: string, m: string, v: number): string {
return `${t}::${m}::${v}`;
}
async put(model: SemanticModelVersion): Promise<void> {
this.rows.set(this.key(model.tenant_id, model.model_id, model.version), model);
}
async get(t: string, m: string, v: number): Promise<SemanticModelVersion | undefined> {
return this.rows.get(this.key(t, m, v));
}
async versions(t: string, m: string): Promise<SemanticModelVersion[]> {
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<SemanticModelVersion | undefined> {
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<SemanticModelVersion, 'hash'>): Promise<SemanticModelVersion> {
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<SemanticModelVersion> {
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<string[]> {
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<SemanticModelVersion, 'hash'>): 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<string>();
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`,
);
}
}
}
}