feat(analytics): BI-P002..BI-P012 analytics core — domain model, tiers, contracts, Arrow, ClickHouse engine, isolation, governance
CI (SIAX Cloud) / security (push) Successful in 41s
Security Scan (SIAX Cloud) / security (push) Successful in 40s
CI (SIAX Cloud) / integration (push) Successful in 52s
CI (SIAX Cloud) / quality (push) Successful in 1m5s
CI (SIAX Cloud) / security (pull_request) Successful in 31s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 29s
CI (SIAX Cloud) / integration (pull_request) Successful in 45s
CI (SIAX Cloud) / quality (pull_request) Successful in 53s
CI (SIAX Cloud) / security (push) Successful in 41s
Security Scan (SIAX Cloud) / security (push) Successful in 40s
CI (SIAX Cloud) / integration (push) Successful in 52s
CI (SIAX Cloud) / quality (push) Successful in 1m5s
CI (SIAX Cloud) / security (pull_request) Successful in 31s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 29s
CI (SIAX Cloud) / integration (pull_request) Successful in 45s
CI (SIAX Cloud) / quality (pull_request) Successful in 53s
Implements the eight BI program prompts that make 0pt the canonical SIAX
analytics capability. Every file is NEW: not one existing file is modified,
and src/analytics/clickhouse-analytics.ts is byte-identical to main.
BI-P002 — the nineteen canonical entities, verbatim, with tenant_id +
project_id on every tenant-owned record. sql/008 gives each one a table.
The four version entities BI-P002 names as immutable are enforced by BEFORE
UPDATE/DELETE triggers, not by a TypeScript `readonly` — proven by direct SQL
against a live Postgres.
BI-P003 — RAW/NORMALIZED/CURATED/SERVING with the read rule enforced:
assertReadableByBiSurface refuses a RAW dataset to a dashboard unless a
recorded exception exists. All eight required declarations are NOT NULL.
BI-P004 — DatasetContract and a fail-closed compatibility gate. Fifteen
breaking-change classes are each tested twice: refused under a minor bump,
accepted under a major one.
BI-P005 — Arrow IPC alongside JSON, with a hand-written FlatBuffers writer so
no npm dependency (or CVE surface) is added. Conformance comes from three
independent implementations, not from self-agreement: pyarrow 25.0.1 and
DuckDB 1.5.5 read identical values from both ClickHouse's Arrow and ours, and
ClickHouse's own Arrow C++ ingests our 20,000-row batch with exact aggregates.
BI-P009 — SiaxAnalyticsEngine with all eight capabilities. The existing
ClickHouseAnalytics is COMPOSED, never replaced. executeQuery (analyst SQL) is
declared and deliberately refused with CAPABILITY_UNAVAILABLE until BI-P017 and
BI-P033 land, rather than opening the raw-SQL hole BI-P011 enumerates.
BI-P010 — four purpose-built tables, not one giant one, and the difference is
measured against the counterfactual: 48.8ms/40,960 rows vs 174.4ms/5,400,000
rows for the same question; 5/660 granules vs 660/1149.
BI-P011 — layered isolation, each layer proven with the layer above removed.
Without the forced predicate the same statement returns 50,050 (both tenants);
with it, t_alpha gets 50. Without a row policy an unrestricted user sees 2
tenants; the restricted user running the IDENTICAL statement sees 1.
BI-P012 — every named limit, fired individually and identified by ClickHouse
error code, plus the half usually skipped: an unrelated tenant is timed while
a real CPU bomb is in flight and must still return the CORRECT answer.
Three defects found by writing tests that can fail:
* `CHECK (array_length(purposes,1) >= 1)` can NEVER fail — array_length is
NULL for '{}' and a NULL CHECK passes. Fixed with coalesce(); the test
that caught it is pinned.
* EXPLAIN ESTIMATE run under the caller's own max_rows_to_read fails with
code 158 exactly when the estimate would be over budget. Planner calls now
use a narrower envelope.
* result_overflow_mode=break returns HTTP 200 with 65,409 of 100,000 rows
and no indication it is short. Every SELECT ships `throw`.
Verified rather than assumed: server7's ClickHouse holds `opt_scraped` (51
tables, 407,793,471 rows, `persons`/`cz_owners` included) — the b0ts plane this
module is prohibited from touching — has no `opt_analytics` database, zero
tenant_id columns and zero row policies. Nothing there was modified; every
proof ran against disposable containers.
Evidence: evidence/bi-p002-p012/{test-transcript.txt,bi-p010-benchmark.json,
bi-p005-arrow-roundtrip.json,server7-clickhouse-probe.md}
Docs: docs/analytics/BI_ANALYTICS_CORE.md
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,474 @@
|
||||
/**
|
||||
* 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");
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
/**
|
||||
* src/analytics/domain/entities.ts
|
||||
* =================================
|
||||
* BI-P002 — ANALYTICS DOMAIN MODEL.
|
||||
*
|
||||
* The nineteen canonical analytics entities, named EXACTLY as the program
|
||||
* lists them (no renaming, no merging, no "we already have something like
|
||||
* that"):
|
||||
*
|
||||
* AnalyticsDataset DatasetVersion DatasetField
|
||||
* DatasetGrant MetricDefinition MetricVersion
|
||||
* DimensionDefinition SemanticModel AnalyticsQuery
|
||||
* QueryExecution QueryResult DashboardDefinition
|
||||
* DashboardVersion ReportDefinition ReportRun
|
||||
* DataQualityRule DataQualityRun LineageReference
|
||||
* BIApplicationBinding
|
||||
*
|
||||
* Every tenant-owned record carries `tenant_id` + `project_id` where
|
||||
* applicable. The four version entities the program names as immutable
|
||||
* (MetricVersion, SemanticModel version, DashboardVersion, DatasetVersion)
|
||||
* are `readonly` here AND immutable in the database — sql/008 installs BEFORE
|
||||
* UPDATE/DELETE triggers, because a TypeScript `readonly` is a compiler
|
||||
* opinion, not a storage guarantee.
|
||||
*
|
||||
* NAME COLLISION, deliberate: src/services/dataset-version-service.ts already
|
||||
* exports an interface called `DatasetVersion` for the ST0RE-artifact-backed
|
||||
* dataset versioning that predates this program. That one is about *dataset
|
||||
* content artifacts*; this one is about *analytics dataset schema versions*
|
||||
* and lives in its own module namespace (`AnalyticsDatasetVersion` is NOT
|
||||
* used as the name — BI-P002 lists `DatasetVersion` verbatim and that is what
|
||||
* ships). Import them qualified when both are needed in one file.
|
||||
*
|
||||
* ARCHITECTURE BOUNDARY: these entities are owned by 0pt. A product repo
|
||||
* (VehIQ) supplies domain MEANING through `BIApplicationBinding`; it never
|
||||
* defines its own copies of these tables and never receives engine
|
||||
* credentials.
|
||||
*/
|
||||
import type { AnalyticsTier } from "./tiers";
|
||||
|
||||
/** Every tenant-owned analytics record. */
|
||||
export interface TenantScoped {
|
||||
tenant_id: string;
|
||||
project_id: string;
|
||||
}
|
||||
|
||||
// ── field/typing vocabulary ────────────────────────────────────────────────
|
||||
|
||||
export const ANALYTICS_FIELD_TYPES = [
|
||||
"string",
|
||||
"int64",
|
||||
"float64",
|
||||
"bool",
|
||||
"date",
|
||||
"timestamp",
|
||||
"decimal",
|
||||
"json",
|
||||
] as const;
|
||||
export type AnalyticsFieldType = (typeof ANALYTICS_FIELD_TYPES)[number];
|
||||
|
||||
/** A field's analytical role. Measures aggregate; dimensions group. */
|
||||
export const FIELD_ROLES = ["identifier", "dimension", "measure", "attribute"] as const;
|
||||
export type FieldRole = (typeof FIELD_ROLES)[number];
|
||||
|
||||
/** PII classification, aligned with the SIAX risk vocabulary (L0 = none). */
|
||||
export const PII_CLASSIFICATIONS = ["none", "pseudonymous", "personal", "sensitive"] as const;
|
||||
export type PiiClassification = (typeof PII_CLASSIFICATIONS)[number];
|
||||
|
||||
// ── 1. AnalyticsDataset ────────────────────────────────────────────────────
|
||||
|
||||
export const DATASET_STATUSES = ["draft", "active", "deprecated", "retired"] as const;
|
||||
export type AnalyticsDatasetStatus = (typeof DATASET_STATUSES)[number];
|
||||
|
||||
/**
|
||||
* BI-P003 DoD: "Every dataset declares tier, schema, owner, source, freshness,
|
||||
* quality, retention, classification." All eight are REQUIRED fields here —
|
||||
* an optional declaration is not a declaration.
|
||||
*/
|
||||
export interface AnalyticsDataset extends TenantScoped {
|
||||
dataset_id: string;
|
||||
name: string;
|
||||
/** BI-P003 tier. */
|
||||
tier: AnalyticsTier;
|
||||
/** Contract id + version this dataset's schema conforms to (BI-P004). */
|
||||
schema_contract_id: string;
|
||||
schema_contract_version: string;
|
||||
/** Accountable human/team, not the person who typed the create call. */
|
||||
owner_id: string;
|
||||
/** Upstream: a 0pt source_id, another dataset_id, or an external ref. */
|
||||
source_ref: string;
|
||||
/** Freshness SLO in seconds — how stale the data may be before it is late. */
|
||||
freshness_slo_seconds: number;
|
||||
/** DataQualityRule ids that gate this dataset. */
|
||||
quality_rule_ids: string[];
|
||||
/** Retention in days. 0 = keep indefinitely (must be justified in policy). */
|
||||
retention_days: number;
|
||||
classification: PiiClassification;
|
||||
status: AnalyticsDatasetStatus;
|
||||
/** BI-P003 escape hatch for RAW/NORMALIZED exposure to a BI surface. */
|
||||
raw_access_exception?: string;
|
||||
description?: string;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
created_by?: string;
|
||||
}
|
||||
|
||||
// ── 2. DatasetVersion (IMMUTABLE) ──────────────────────────────────────────
|
||||
|
||||
export interface DatasetVersion extends TenantScoped {
|
||||
readonly dataset_version_id: string;
|
||||
readonly dataset_id: string;
|
||||
/** Monotonic per dataset, starting at 1. */
|
||||
readonly version: number;
|
||||
/** The frozen DatasetContract JSON at this version (BI-P004). */
|
||||
readonly contract_hash: string;
|
||||
readonly schema_contract_version: string;
|
||||
readonly record_count?: number;
|
||||
readonly created_at: string;
|
||||
readonly created_by?: string;
|
||||
}
|
||||
|
||||
// ── 3. DatasetField ────────────────────────────────────────────────────────
|
||||
|
||||
export interface DatasetField extends TenantScoped {
|
||||
dataset_field_id: string;
|
||||
dataset_id: string;
|
||||
/** The dataset version this field description belongs to. */
|
||||
dataset_version: number;
|
||||
name: string;
|
||||
field_type: AnalyticsFieldType;
|
||||
nullable: boolean;
|
||||
role: FieldRole;
|
||||
/** True for the field(s) forming the dataset's primary identifier. */
|
||||
primary_identifier: boolean;
|
||||
classification: PiiClassification;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
// ── 4. DatasetGrant ────────────────────────────────────────────────────────
|
||||
|
||||
export const GRANT_LEVELS = ["read", "query", "export", "admin"] as const;
|
||||
export type GrantLevel = (typeof GRANT_LEVELS)[number];
|
||||
|
||||
/**
|
||||
* Who may use a dataset, and FOR WHAT. `allowed_purposes` is the GDPR purpose
|
||||
* limitation carried into analytics — a grant without a purpose is refused
|
||||
* by the repository layer.
|
||||
*/
|
||||
export interface DatasetGrant extends TenantScoped {
|
||||
grant_id: string;
|
||||
dataset_id: string;
|
||||
/** Subject: a CL0UD principal, role, or BI application binding id. */
|
||||
subject_id: string;
|
||||
subject_type: "user" | "role" | "service" | "bi_application";
|
||||
level: GrantLevel;
|
||||
allowed_purposes: string[];
|
||||
expires_at?: string;
|
||||
created_at: string;
|
||||
created_by?: string;
|
||||
}
|
||||
|
||||
// ── 5. MetricDefinition ────────────────────────────────────────────────────
|
||||
|
||||
export const METRIC_AGGREGATIONS = [
|
||||
"sum",
|
||||
"avg",
|
||||
"min",
|
||||
"max",
|
||||
"count",
|
||||
"count_distinct",
|
||||
"ratio",
|
||||
"derived",
|
||||
] as const;
|
||||
export type MetricAggregation = (typeof METRIC_AGGREGATIONS)[number];
|
||||
|
||||
export interface MetricDefinition extends TenantScoped {
|
||||
metric_id: string;
|
||||
/** Stable business name; unique per tenant. */
|
||||
name: string;
|
||||
dataset_id: string;
|
||||
aggregation: MetricAggregation;
|
||||
/** Measure field aggregated, or the numerator for ratio metrics. */
|
||||
measure_field: string;
|
||||
/** Denominator for ratio metrics. */
|
||||
denominator_field?: string;
|
||||
/** Dimensions this metric may legitimately be sliced by. */
|
||||
allowed_dimension_ids: string[];
|
||||
/** Current live version number (points at a MetricVersion). */
|
||||
current_version: number;
|
||||
owner_id: string;
|
||||
description?: string;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
// ── 6. MetricVersion (IMMUTABLE) ───────────────────────────────────────────
|
||||
|
||||
export interface MetricVersion extends TenantScoped {
|
||||
readonly metric_version_id: string;
|
||||
readonly metric_id: string;
|
||||
readonly version: number;
|
||||
/** Frozen definition JSON — what this metric MEANT at this version. */
|
||||
readonly definition_json: string;
|
||||
readonly definition_hash: string;
|
||||
/** Free-text reason the metric changed; required for version > 1. */
|
||||
readonly change_reason?: string;
|
||||
readonly created_at: string;
|
||||
readonly created_by?: string;
|
||||
}
|
||||
|
||||
// ── 7. DimensionDefinition ─────────────────────────────────────────────────
|
||||
|
||||
export interface DimensionDefinition extends TenantScoped {
|
||||
dimension_id: string;
|
||||
name: string;
|
||||
dataset_id: string;
|
||||
/**
|
||||
* Physical column/key this dimension resolves to. This is the ONLY place a
|
||||
* caller-supplied dimension name becomes a physical identifier — the query
|
||||
* compiler resolves through here and never splices caller input (BI-P011
|
||||
* "dimension identifier injection").
|
||||
*/
|
||||
field_name: string;
|
||||
field_type: AnalyticsFieldType;
|
||||
classification: PiiClassification;
|
||||
description?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ── 8. SemanticModel (versioned; versions IMMUTABLE) ───────────────────────
|
||||
|
||||
export interface SemanticModel extends TenantScoped {
|
||||
semantic_model_id: string;
|
||||
name: string;
|
||||
/** Immutable version number — a change mints a new row, never an UPDATE. */
|
||||
readonly version: number;
|
||||
/** MetricFlow/Cube-compatible model document (BI-P029/BI-P032 consume it). */
|
||||
readonly model_json: string;
|
||||
readonly model_hash: string;
|
||||
dataset_ids: string[];
|
||||
owner_id: string;
|
||||
readonly created_at: string;
|
||||
readonly created_by?: string;
|
||||
}
|
||||
|
||||
// ── 9. AnalyticsQuery ──────────────────────────────────────────────────────
|
||||
|
||||
export const QUERY_SURFACES = ["metric", "sql", "projection"] as const;
|
||||
export type QuerySurface = (typeof QUERY_SURFACES)[number];
|
||||
|
||||
/**
|
||||
* A SAVED, reusable query. The request that actually runs is
|
||||
* `src/analytics/engine/query-compiler.ts`'s `MetricQueryRequest`; this entity
|
||||
* is its durable, governed form.
|
||||
*/
|
||||
export interface AnalyticsQuery extends TenantScoped {
|
||||
query_id: string;
|
||||
name: string;
|
||||
surface: QuerySurface;
|
||||
dataset_id: string;
|
||||
metric_id?: string;
|
||||
/** Serialized closed-DSL request. Never raw SQL for surface="metric". */
|
||||
request_json: string;
|
||||
owner_id: string;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
// ── 10. QueryExecution ─────────────────────────────────────────────────────
|
||||
|
||||
export const EXECUTION_STATES = [
|
||||
"queued",
|
||||
"running",
|
||||
"succeeded",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"rejected",
|
||||
] as const;
|
||||
export type ExecutionState = (typeof EXECUTION_STATES)[number];
|
||||
|
||||
export interface QueryExecution extends TenantScoped {
|
||||
execution_id: string;
|
||||
query_id?: string;
|
||||
/** Engine-side identifier used to CANCEL this execution (BI-P009). */
|
||||
engine_query_id: string;
|
||||
state: ExecutionState;
|
||||
/** Which provider ran it: "clickhouse" | "duckdb" | "trino". */
|
||||
provider: string;
|
||||
submitted_at: string;
|
||||
started_at?: string;
|
||||
finished_at?: string;
|
||||
duration_ms?: number;
|
||||
rows_read?: number;
|
||||
bytes_read?: number;
|
||||
result_rows?: number;
|
||||
/** SiaxErrorCode when state="failed"/"rejected". Never a raw engine body. */
|
||||
error_code?: string;
|
||||
correlation_id?: string;
|
||||
}
|
||||
|
||||
// ── 11. QueryResult ────────────────────────────────────────────────────────
|
||||
|
||||
export const RESULT_ENCODINGS = ["json", "arrow_ipc"] as const;
|
||||
export type ResultEncoding = (typeof RESULT_ENCODINGS)[number];
|
||||
|
||||
export interface QueryResult extends TenantScoped {
|
||||
result_id: string;
|
||||
execution_id: string;
|
||||
encoding: ResultEncoding;
|
||||
row_count: number;
|
||||
/** Canonical ST0RE ref when materialised; inline results carry no bytes here. */
|
||||
artifact_ref?: string;
|
||||
/** True when the engine truncated at max_result_rows (BI-P012). */
|
||||
truncated: boolean;
|
||||
expires_at?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ── 12. DashboardDefinition ────────────────────────────────────────────────
|
||||
|
||||
export interface DashboardDefinition extends TenantScoped {
|
||||
dashboard_id: string;
|
||||
name: string;
|
||||
/** Live version pointer. */
|
||||
current_version: number;
|
||||
owner_id: string;
|
||||
/** Datasets the dashboard reads — checked against BI-P003 tier rules. */
|
||||
dataset_ids: string[];
|
||||
description?: string;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
// ── 13. DashboardVersion (IMMUTABLE) ───────────────────────────────────────
|
||||
|
||||
export interface DashboardVersion extends TenantScoped {
|
||||
readonly dashboard_version_id: string;
|
||||
readonly dashboard_id: string;
|
||||
readonly version: number;
|
||||
/** Frozen layout/panel document. */
|
||||
readonly layout_json: string;
|
||||
readonly layout_hash: string;
|
||||
readonly created_at: string;
|
||||
readonly created_by?: string;
|
||||
}
|
||||
|
||||
// ── 14. ReportDefinition ───────────────────────────────────────────────────
|
||||
|
||||
export const REPORT_FORMATS = ["pdf", "csv", "xlsx", "parquet", "arrow_ipc"] as const;
|
||||
export type ReportFormat = (typeof REPORT_FORMATS)[number];
|
||||
|
||||
export interface ReportDefinition extends TenantScoped {
|
||||
report_id: string;
|
||||
name: string;
|
||||
dashboard_id?: string;
|
||||
query_id?: string;
|
||||
format: ReportFormat;
|
||||
/** Cron expression; undefined = on-demand only. */
|
||||
schedule_cron?: string;
|
||||
owner_id: string;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
// ── 15. ReportRun ──────────────────────────────────────────────────────────
|
||||
|
||||
export interface ReportRun extends TenantScoped {
|
||||
report_run_id: string;
|
||||
report_id: string;
|
||||
state: ExecutionState;
|
||||
started_at: string;
|
||||
finished_at?: string;
|
||||
/** ST0RE artifact ref of the produced report. */
|
||||
artifact_ref?: string;
|
||||
error_code?: string;
|
||||
correlation_id?: string;
|
||||
}
|
||||
|
||||
// ── 16. DataQualityRule ────────────────────────────────────────────────────
|
||||
|
||||
export const QUALITY_RULE_KINDS = [
|
||||
"not_null",
|
||||
"unique",
|
||||
"accepted_values",
|
||||
"range",
|
||||
"freshness",
|
||||
"row_count",
|
||||
"referential",
|
||||
"custom",
|
||||
] as const;
|
||||
export type QualityRuleKind = (typeof QUALITY_RULE_KINDS)[number];
|
||||
|
||||
export const QUALITY_SEVERITIES = ["warn", "block"] as const;
|
||||
export type QualitySeverity = (typeof QUALITY_SEVERITIES)[number];
|
||||
|
||||
export interface DataQualityRule extends TenantScoped {
|
||||
rule_id: string;
|
||||
dataset_id: string;
|
||||
kind: QualityRuleKind;
|
||||
/** Field the rule applies to; omitted for dataset-level rules. */
|
||||
field_name?: string;
|
||||
/** Rule parameters (bounds, accepted values, max age). */
|
||||
params_json: string;
|
||||
severity: QualitySeverity;
|
||||
created_at: string;
|
||||
created_by?: string;
|
||||
}
|
||||
|
||||
// ── 17. DataQualityRun ─────────────────────────────────────────────────────
|
||||
|
||||
export interface DataQualityRun extends TenantScoped {
|
||||
quality_run_id: string;
|
||||
rule_id: string;
|
||||
dataset_id: string;
|
||||
dataset_version?: number;
|
||||
passed: boolean;
|
||||
/** Rows that violated the rule. */
|
||||
violation_count: number;
|
||||
evaluated_rows: number;
|
||||
started_at: string;
|
||||
finished_at?: string;
|
||||
correlation_id?: string;
|
||||
}
|
||||
|
||||
// ── 18. LineageReference ───────────────────────────────────────────────────
|
||||
|
||||
export const LINEAGE_DIRECTIONS = ["input", "output"] as const;
|
||||
export type LineageDirection = (typeof LINEAGE_DIRECTIONS)[number];
|
||||
|
||||
/**
|
||||
* The queryable projection of an OpenLineage edge (BI-P027). AUD0 stays the
|
||||
* system of record; this is 0pt's local index so "what fed this dashboard"
|
||||
* is answerable without leaving the analytics plane.
|
||||
*/
|
||||
export interface LineageReference extends TenantScoped {
|
||||
lineage_reference_id: string;
|
||||
/** OpenLineage run id this edge came from. */
|
||||
run_id: string;
|
||||
job_name: string;
|
||||
direction: LineageDirection;
|
||||
/** The analytics entity this edge touches. */
|
||||
entity_type: "dataset" | "metric" | "dashboard" | "report";
|
||||
entity_id: string;
|
||||
/** Namespaced dataset name on the other side of the edge. */
|
||||
counterpart_ref: string;
|
||||
observed_at: string;
|
||||
}
|
||||
|
||||
// ── 19. BIApplicationBinding ───────────────────────────────────────────────
|
||||
|
||||
export const BI_APPLICATION_KINDS = ["superset", "evidence", "des1gn", "notebook", "custom"] as const;
|
||||
export type BiApplicationKind = (typeof BI_APPLICATION_KINDS)[number];
|
||||
|
||||
/**
|
||||
* How an external BI surface is attached to the analytics plane.
|
||||
*
|
||||
* NORMATIVE (BI program §0 + the SIAX/0pt ownership boundary): this binding
|
||||
* carries NO engine credential. A bound application authenticates to the 0pt
|
||||
* Analytics API with a CL0UD identity and receives compiled, tenant-forced
|
||||
* results — it never learns a ClickHouse DSN, user, or password. The absence
|
||||
* of a credential field here is the enforcement, not a comment.
|
||||
*/
|
||||
export interface BIApplicationBinding extends TenantScoped {
|
||||
binding_id: string;
|
||||
kind: BiApplicationKind;
|
||||
name: string;
|
||||
/** CL0UD principal the application authenticates as. */
|
||||
principal_id: string;
|
||||
/** Datasets/metrics this application may reach at all. */
|
||||
dataset_ids: string[];
|
||||
metric_ids: string[];
|
||||
allowed_purposes: string[];
|
||||
enabled: boolean;
|
||||
created_at: string;
|
||||
created_by?: string;
|
||||
}
|
||||
|
||||
// ── registry of the canonical nineteen ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The canonical entity names, verbatim from BI-P002. Persisted-schema tests
|
||||
* assert sql/008 defines a table for every one of these, so a future rename
|
||||
* or omission is a test failure rather than drift.
|
||||
*/
|
||||
export const ANALYTICS_DOMAIN_ENTITIES = [
|
||||
"AnalyticsDataset",
|
||||
"DatasetVersion",
|
||||
"DatasetField",
|
||||
"DatasetGrant",
|
||||
"MetricDefinition",
|
||||
"MetricVersion",
|
||||
"DimensionDefinition",
|
||||
"SemanticModel",
|
||||
"AnalyticsQuery",
|
||||
"QueryExecution",
|
||||
"QueryResult",
|
||||
"DashboardDefinition",
|
||||
"DashboardVersion",
|
||||
"ReportDefinition",
|
||||
"ReportRun",
|
||||
"DataQualityRule",
|
||||
"DataQualityRun",
|
||||
"LineageReference",
|
||||
"BIApplicationBinding",
|
||||
] as const;
|
||||
export type AnalyticsDomainEntity = (typeof ANALYTICS_DOMAIN_ENTITIES)[number];
|
||||
|
||||
/** Entity -> physical table in sql/008_analytics_domain_model.sql. */
|
||||
export const ANALYTICS_ENTITY_TABLES: Record<AnalyticsDomainEntity, string> = {
|
||||
AnalyticsDataset: "opt_analytics_dataset",
|
||||
DatasetVersion: "opt_analytics_dataset_version",
|
||||
DatasetField: "opt_analytics_dataset_field",
|
||||
DatasetGrant: "opt_analytics_dataset_grant",
|
||||
MetricDefinition: "opt_analytics_metric_definition",
|
||||
MetricVersion: "opt_analytics_metric_version",
|
||||
DimensionDefinition: "opt_analytics_dimension_definition",
|
||||
SemanticModel: "opt_analytics_semantic_model",
|
||||
AnalyticsQuery: "opt_analytics_query",
|
||||
QueryExecution: "opt_analytics_query_execution",
|
||||
QueryResult: "opt_analytics_query_result",
|
||||
DashboardDefinition: "opt_analytics_dashboard_definition",
|
||||
DashboardVersion: "opt_analytics_dashboard_version",
|
||||
ReportDefinition: "opt_analytics_report_definition",
|
||||
ReportRun: "opt_analytics_report_run",
|
||||
DataQualityRule: "opt_analytics_data_quality_rule",
|
||||
DataQualityRun: "opt_analytics_data_quality_run",
|
||||
LineageReference: "opt_analytics_lineage_reference",
|
||||
BIApplicationBinding: "opt_analytics_bi_application_binding",
|
||||
};
|
||||
|
||||
/** The four entities BI-P002 requires to be immutable once written. */
|
||||
export const IMMUTABLE_VERSION_ENTITIES: readonly AnalyticsDomainEntity[] = [
|
||||
"DatasetVersion",
|
||||
"MetricVersion",
|
||||
"SemanticModel",
|
||||
"DashboardVersion",
|
||||
];
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* 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)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user