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:
@@ -1,212 +0,0 @@
|
||||
/**
|
||||
* src/adapters/document-intelligence-adapter.ts
|
||||
* ================================================
|
||||
* Tenant-agnostic Azure AI Document Intelligence client.
|
||||
*
|
||||
* Generalized from v0-datahub/lib/invoice-inbox/doc-intelligence.ts, which
|
||||
* hardcoded the `prebuilt-invoice` model and a fixed invoice-shaped return
|
||||
* type (amount_gross, vendor, vat, ...). Here `modelId` is a CALLER-SUPPLIED
|
||||
* parameter — "prebuilt-invoice", "prebuilt-receipt", "prebuilt-layout",
|
||||
* "prebuilt-read", or any custom-trained model id — and the adapter returns
|
||||
* a generic field map instead of assuming any particular document shape.
|
||||
*
|
||||
* Evidence discipline (correctness-critical, not a style choice): a field is
|
||||
* only ever populated with the value + confidence Document Intelligence
|
||||
* actually reported. If DI did not return a value, the field comes back as
|
||||
* { value: null, confidence: <DI's confidence if any, else null>, found: false }.
|
||||
* Nothing here ever defaults, guesses, or backfills a value.
|
||||
*/
|
||||
|
||||
export interface DocumentIntelligenceConfig {
|
||||
endpoint: string;
|
||||
apiKey: string;
|
||||
/** Default: "2024-11-30" — the API version the production invoice pipeline used. */
|
||||
apiVersion?: string;
|
||||
/** Delay between result-polling attempts, ms. Default 2000. (Tests override to run fast.) */
|
||||
pollIntervalMs?: number;
|
||||
/** Delay before retrying after a 429, ms. Default 6000. (Tests override to run fast.) */
|
||||
rateLimitRetryMs?: number;
|
||||
/** Max result-polling attempts before timing out. Default 40. */
|
||||
maxPollAttempts?: number;
|
||||
/** Max analyze-request attempts (each 429 counts as one). Default 4. */
|
||||
maxAnalyzeAttempts?: number;
|
||||
}
|
||||
|
||||
export interface ExtractedField {
|
||||
value: string | number | boolean | null;
|
||||
confidence: number | null;
|
||||
found: boolean;
|
||||
}
|
||||
|
||||
export interface DocumentIntelligenceResult {
|
||||
modelId: string;
|
||||
apiVersion: string;
|
||||
/** Full extracted text, when the API returns one (present across prebuilt models). */
|
||||
content: string | null;
|
||||
/** Top-level structured fields (documents[0].fields), normalized. Empty for pure layout/read. */
|
||||
fields: Record<string, ExtractedField>;
|
||||
/** Array-of-object fields (e.g. invoice/receipt line items), each item pre-normalized. */
|
||||
arrayFields: Record<string, Array<Record<string, ExtractedField>>>;
|
||||
/** documents[0].confidence, when the model reports a whole-document confidence. */
|
||||
documentConfidence: number | null;
|
||||
pageCount: number | null;
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/** Normalize one Document Intelligence field object into an evidence-based ExtractedField. */
|
||||
function normalizeField(raw: unknown): ExtractedField {
|
||||
const f = raw as Record<string, unknown> | null | undefined;
|
||||
if (!f) return { value: null, confidence: null, found: false };
|
||||
let value: string | number | boolean | null = null;
|
||||
switch (f.type) {
|
||||
case "string":
|
||||
value = (f.valueString as string | undefined) ?? (f.content as string | undefined) ?? null;
|
||||
break;
|
||||
case "number":
|
||||
value = (f.valueNumber as number | undefined) ?? null;
|
||||
break;
|
||||
case "integer":
|
||||
value = (f.valueInteger as number | undefined) ?? null;
|
||||
break;
|
||||
case "date":
|
||||
value = (f.valueDate as string | undefined) ?? null;
|
||||
break;
|
||||
case "time":
|
||||
value = (f.valueTime as string | undefined) ?? null;
|
||||
break;
|
||||
case "phoneNumber":
|
||||
value = (f.valuePhoneNumber as string | undefined) ?? null;
|
||||
break;
|
||||
case "countryRegion":
|
||||
value = (f.valueCountryRegion as string | undefined) ?? null;
|
||||
break;
|
||||
case "selectionMark":
|
||||
value = (f.valueSelectionMark as string | undefined) ?? null;
|
||||
break;
|
||||
case "currency": {
|
||||
const cur = f.valueCurrency as Record<string, unknown> | undefined;
|
||||
value = typeof cur?.amount === "number" ? (cur.amount as number) : null;
|
||||
break;
|
||||
}
|
||||
case "boolean":
|
||||
value = typeof f.valueBoolean === "boolean" ? (f.valueBoolean as boolean) : null;
|
||||
break;
|
||||
default:
|
||||
value = (f.valueString as string | undefined) ?? (f.content as string | undefined) ?? null;
|
||||
}
|
||||
const found = value !== null && value !== undefined && value !== "";
|
||||
const confidence = typeof f.confidence === "number" ? (f.confidence as number) : null;
|
||||
return { value: found ? value : null, confidence, found };
|
||||
}
|
||||
|
||||
function normalizeObjectFields(obj: Record<string, unknown> | null | undefined): Record<string, ExtractedField> {
|
||||
const out: Record<string, ExtractedField> = {};
|
||||
for (const [key, raw] of Object.entries(obj ?? {})) {
|
||||
out[key] = normalizeField(raw);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export class DocumentIntelligenceAdapter {
|
||||
constructor(private config: DocumentIntelligenceConfig) {}
|
||||
|
||||
static isConfigured(config: Partial<DocumentIntelligenceConfig>): boolean {
|
||||
return !!(config.endpoint && config.apiKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze a document buffer with the given model. Throws on any failure —
|
||||
* callers must never interpret a caught error as "no fields found". A
|
||||
* genuinely empty field is represented by { found: false } *inside a
|
||||
* successful result*; a failed call must propagate as an error, not a
|
||||
* fabricated empty success.
|
||||
*/
|
||||
async analyzeDocument(buf: Buffer, modelId: string): Promise<DocumentIntelligenceResult> {
|
||||
const apiVersion = this.config.apiVersion || "2024-11-30";
|
||||
const base = this.config.endpoint.replace(/\/$/, "");
|
||||
const analyzeUrl = `${base}/documentintelligence/documentModels/${encodeURIComponent(modelId)}:analyze?api-version=${apiVersion}`;
|
||||
|
||||
const maxAnalyzeAttempts = this.config.maxAnalyzeAttempts ?? 4;
|
||||
const rateLimitRetryMs = this.config.rateLimitRetryMs ?? 6000;
|
||||
const pollIntervalMs = this.config.pollIntervalMs ?? 2000;
|
||||
const maxPollAttempts = this.config.maxPollAttempts ?? 40;
|
||||
|
||||
let operationLocation = "";
|
||||
for (let attempt = 0; attempt < maxAnalyzeAttempts; attempt++) {
|
||||
const res = await fetch(analyzeUrl, {
|
||||
method: "POST",
|
||||
headers: { "Ocp-Apim-Subscription-Key": this.config.apiKey, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ base64Source: buf.toString("base64") }),
|
||||
});
|
||||
if (res.status === 429) {
|
||||
await sleep(rateLimitRetryMs);
|
||||
continue;
|
||||
}
|
||||
if (res.status !== 202) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(`Document Intelligence analyze request failed: ${res.status} ${text.slice(0, 300)}`);
|
||||
}
|
||||
operationLocation = res.headers.get("operation-location") || "";
|
||||
break;
|
||||
}
|
||||
if (!operationLocation) {
|
||||
throw new Error(
|
||||
"Document Intelligence analyze did not return an operation-location (rate-limited after retries, or misconfigured)",
|
||||
);
|
||||
}
|
||||
|
||||
let payload: Record<string, unknown> | null = null;
|
||||
for (let i = 0; i < maxPollAttempts; i++) {
|
||||
await sleep(pollIntervalMs);
|
||||
const pollRes = await fetch(operationLocation, { headers: { "Ocp-Apim-Subscription-Key": this.config.apiKey } });
|
||||
if (!pollRes.ok) {
|
||||
const text = await pollRes.text().catch(() => "");
|
||||
throw new Error(`Document Intelligence poll request failed: ${pollRes.status} ${text.slice(0, 300)}`);
|
||||
}
|
||||
const json = (await pollRes.json()) as Record<string, unknown>;
|
||||
if (json.status === "succeeded") {
|
||||
payload = json;
|
||||
break;
|
||||
}
|
||||
if (json.status === "failed") {
|
||||
throw new Error(`Document Intelligence analyze failed: ${JSON.stringify(json.error ?? json).slice(0, 500)}`);
|
||||
}
|
||||
}
|
||||
if (!payload) {
|
||||
throw new Error("Document Intelligence analyze timed out waiting for a result");
|
||||
}
|
||||
|
||||
const analyzeResult = (payload.analyzeResult as Record<string, unknown>) ?? {};
|
||||
const documents = analyzeResult.documents as Array<Record<string, unknown>> | undefined;
|
||||
const doc = documents?.[0];
|
||||
const rawFields = (doc?.fields as Record<string, unknown>) ?? {};
|
||||
|
||||
const fields: Record<string, ExtractedField> = {};
|
||||
const arrayFields: Record<string, Array<Record<string, ExtractedField>>> = {};
|
||||
for (const [key, raw] of Object.entries(rawFields)) {
|
||||
const f = raw as Record<string, unknown>;
|
||||
if (f?.type === "array" && Array.isArray(f.valueArray)) {
|
||||
arrayFields[key] = (f.valueArray as Array<Record<string, unknown>>).map((item) =>
|
||||
normalizeObjectFields(item?.valueObject as Record<string, unknown> | undefined),
|
||||
);
|
||||
} else {
|
||||
fields[key] = normalizeField(f);
|
||||
}
|
||||
}
|
||||
|
||||
const pages = analyzeResult.pages as unknown[] | undefined;
|
||||
|
||||
return {
|
||||
modelId,
|
||||
apiVersion,
|
||||
content: typeof analyzeResult.content === "string" ? (analyzeResult.content as string) : null,
|
||||
fields,
|
||||
arrayFields,
|
||||
documentConfidence: typeof doc?.confidence === "number" ? (doc.confidence as number) : null,
|
||||
pageCount: Array.isArray(pages) ? pages.length : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
/**
|
||||
* src/adapters/fabric-onelake-adapter.ts
|
||||
* ========================================
|
||||
* Tenant-agnostic Azure Fabric / OneLake SQL analytics endpoint adapter
|
||||
* (adapter_id = "fabric_onelake_sql" on a 0pt Source).
|
||||
*
|
||||
* Generalized from two proven patterns in v0-datahub:
|
||||
* - scripts/ops/cloud-bootstrap.mjs `aadToken()` — Entra service-principal
|
||||
* OAuth2 client-credentials flow (POST login.microsoftonline.com/{tenant}
|
||||
* /oauth2/v2.0/token, grant_type=client_credentials).
|
||||
* - lib/warehouse/fabric-sql.ts `buildConfig()` / `runFabricQuery()` — using
|
||||
* that token as an `azure-active-directory-access-token` credential on a
|
||||
* `mssql` TDS connection to the Fabric SQL analytics endpoint, and
|
||||
* returning `result.recordset` as plain rows.
|
||||
*
|
||||
* Both of those originals hardcode ONE customer's tenant/client/secret/
|
||||
* endpoint as module-level constants or env vars (AZ_SP_*, FABRIC_SQL_ENDPOINT,
|
||||
* kv-pts-datahub, ...). Nothing here is hardcoded: tenantId, clientId,
|
||||
* clientSecret, sqlEndpoint and database are always caller-supplied, because
|
||||
* this is a SIAX platform capability — any SIAX customer registers their own
|
||||
* Fabric/OneLake warehouse as a Source and queries it through this adapter.
|
||||
*
|
||||
* Dependency note: `mssql` (the TDS driver used by fabric-sql.ts) is NOT a
|
||||
* declared dependency of this repo yet, and package.json/pnpm-lock.yaml
|
||||
* already have unrelated uncommitted changes from a separate in-flight
|
||||
* session — so it is deliberately not added here to avoid colliding with
|
||||
* that work. The driver is loaded lazily via a non-literal dynamic import
|
||||
* (see `loadDriver`) so:
|
||||
* - this file has zero hard dependency at import/bundle time (Next.js/
|
||||
* webpack cannot statically resolve a non-literal specifier, so it does
|
||||
* not fail the build even though "mssql" isn't installed), and
|
||||
* - `tsc --noEmit` does not attempt to resolve module types for it either
|
||||
* (a widened `string`-typed specifier makes `import(...)` type as
|
||||
* `Promise<any>` instead of triggering module resolution).
|
||||
* Once `mssql` is added to package.json (`pnpm add mssql`), query() works
|
||||
* against a real endpoint with no code change here. Until then, `query()`
|
||||
* throws a clear, actionable error — see docs/P0_QUERY_SOURCE_FLOW.md.
|
||||
*
|
||||
* SSRF guard: `connection_config.sqlEndpoint` is caller-supplied per-request
|
||||
* (via POST /api/0pt/sources/{sourceId}/query -> source-query-service.ts)
|
||||
* and, until now, only had its scheme stripped before being handed to the
|
||||
* `mssql` driver as the outbound connection target — no hostname allowlist
|
||||
* or private/loopback/link-local/cloud-metadata check. `getPool()` now
|
||||
* resolves and validates the endpoint via
|
||||
* `src/lib/security/ssrf-guard.ts::assertConnectionHostIsSafe` *before*
|
||||
* constructing the pool, closing that gap defense-in-depth (this route
|
||||
* already requires a Zitadel bearer token + tenant match — see
|
||||
* src/http/tenant-guard.ts).
|
||||
*/
|
||||
|
||||
import { assertConnectionHostIsSafe, type DnsLookupFn } from "../lib/security/ssrf-guard";
|
||||
|
||||
const DEFAULT_SQL_SCOPE = "https://database.windows.net/.default";
|
||||
const TOKEN_REFRESH_SKEW_MS = 60_000;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
||||
|
||||
export interface FabricOneLakeCredentials {
|
||||
/** Entra (Azure AD) tenant id the service-principal app registration lives in. */
|
||||
tenantId: string;
|
||||
/** Entra app (client) id — app-only, client-credentials grant. */
|
||||
clientId: string;
|
||||
/** Entra app client secret. Never logged, never persisted by this adapter. */
|
||||
clientSecret: string;
|
||||
}
|
||||
|
||||
export interface FabricOneLakeConnectionConfig {
|
||||
credentials: FabricOneLakeCredentials;
|
||||
/** Fabric SQL analytics endpoint host, e.g. "xxxx.datawarehouse.fabric.microsoft.com" (scheme optional). */
|
||||
sqlEndpoint: string;
|
||||
/** Target database / lakehouse SQL endpoint name, e.g. "lh_customer_datahub". */
|
||||
database: string;
|
||||
/** AAD scope used for the SQL token. Defaults to the Azure SQL / Fabric warehouse resource scope. */
|
||||
scope?: string;
|
||||
/** Per-request timeout passed to the mssql pool config. Default 30s. */
|
||||
requestTimeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface FabricAccessToken {
|
||||
accessToken: string;
|
||||
expiresAtEpochMs: number;
|
||||
}
|
||||
|
||||
export interface AdapterQueryResult<T = Record<string, unknown>> {
|
||||
rows: T[];
|
||||
rowCount: number;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* OAuth2 client-credentials token acquisition for an Azure AD service
|
||||
* principal — generalized 1:1 from v0-datahub's `aadToken()`. Exported
|
||||
* standalone (not just as a private method) so it can be unit-tested and
|
||||
* reused by callers that only need a token (e.g. to probe connectivity)
|
||||
* without opening a SQL connection.
|
||||
*/
|
||||
export async function acquireFabricAccessToken(
|
||||
credentials: FabricOneLakeCredentials,
|
||||
scope: string = DEFAULT_SQL_SCOPE,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<FabricAccessToken> {
|
||||
const { tenantId, clientId, clientSecret } = credentials;
|
||||
if (!tenantId || !clientId || !clientSecret) {
|
||||
throw new Error("fabric_onelake_adapter: tenantId, clientId and clientSecret are all required");
|
||||
}
|
||||
const body = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
grant_type: "client_credentials",
|
||||
scope,
|
||||
});
|
||||
const res = await fetchImpl(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
const json: { access_token?: string; expires_in?: number; error?: string; error_description?: string } = await res.json();
|
||||
if (!res.ok || !json.access_token) {
|
||||
throw new Error(
|
||||
`fabric_onelake_adapter: AAD token request failed (scope=${scope}): ${json.error ?? res.status} ${json.error_description ?? ""}`.trim(),
|
||||
);
|
||||
}
|
||||
const expiresInMs = (typeof json.expires_in === "number" ? json.expires_in : 3600) * 1000;
|
||||
return { accessToken: json.access_token, expiresAtEpochMs: Date.now() + expiresInMs };
|
||||
}
|
||||
|
||||
function stripScheme(endpoint: string): string {
|
||||
return endpoint.replace(/^https?:\/\//, "").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/** Minimal shape of the pieces of the `mssql` module this adapter actually uses. Kept as a structural type, never imported from the real package (see file header). */
|
||||
interface MssqlLike {
|
||||
ConnectionPool: new (config: Record<string, unknown>) => {
|
||||
connect(): Promise<unknown>;
|
||||
request(): {
|
||||
input(name: string, value: unknown): unknown;
|
||||
query(text: string): Promise<{ recordset?: unknown[] }>;
|
||||
};
|
||||
close(): Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapter for Source.adapter_id === "fabric_onelake_sql". One instance holds
|
||||
* one registered Source's connection config; nothing is shared across
|
||||
* tenants/customers, and no config here ever falls back to an env var.
|
||||
*/
|
||||
export class FabricOneLakeAdapter {
|
||||
private token: FabricAccessToken | null = null;
|
||||
private pool: InstanceType<MssqlLike["ConnectionPool"]> | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly config: FabricOneLakeConnectionConfig,
|
||||
private readonly fetchImpl: typeof fetch = fetch,
|
||||
/**
|
||||
* Injectable DNS resolver for the SSRF guard (see `getPool()`).
|
||||
* Overridable for tests, same rationale as `fetchImpl`; defaults to the
|
||||
* real `node:dns` resolver in production (undefined -> ssrf-guard's own
|
||||
* default).
|
||||
*/
|
||||
private readonly dnsLookupImpl?: DnsLookupFn,
|
||||
) {}
|
||||
|
||||
private async getToken(): Promise<string> {
|
||||
if (this.token && this.token.expiresAtEpochMs - TOKEN_REFRESH_SKEW_MS > Date.now()) {
|
||||
return this.token.accessToken;
|
||||
}
|
||||
this.token = await acquireFabricAccessToken(this.config.credentials, this.config.scope, this.fetchImpl);
|
||||
return this.token.accessToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the `mssql` TDS driver at call time via a *non-literal* specifier.
|
||||
* `moduleName` is deliberately widened to `string` (not the literal
|
||||
* `"mssql"`) so TypeScript types the result as `Promise<any>` instead of
|
||||
* resolving module types, and so bundlers cannot statically inline the
|
||||
* specifier into a build-time-resolved chunk. Overridable for tests.
|
||||
*/
|
||||
private async loadDriver(): Promise<MssqlLike> {
|
||||
const moduleName: string = "mssql";
|
||||
try {
|
||||
const mod = await import(moduleName);
|
||||
return (mod.default ?? mod) as MssqlLike;
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`fabric_onelake_adapter: "mssql" package is not installed/resolvable. Add it to package.json ` +
|
||||
`(dependencies.mssql) to enable live Fabric SQL query execution. Original error: ` +
|
||||
`${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async getPool(): Promise<InstanceType<MssqlLike["ConnectionPool"]>> {
|
||||
if (this.pool) return this.pool;
|
||||
// SSRF guard: resolve + validate the caller-supplied sqlEndpoint before
|
||||
// doing anything else — in particular before loadDriver()/getToken(), so
|
||||
// a blocked target never gets as far as a real outbound connection
|
||||
// attempt (or spends an AAD token exchange on a request that will be
|
||||
// refused anyway). Throws SsrfBlockedHostError for a private/loopback/
|
||||
// link-local/cloud-metadata/unspecified address, or an unresolvable host.
|
||||
await assertConnectionHostIsSafe(this.config.sqlEndpoint, this.dnsLookupImpl);
|
||||
const sql = await this.loadDriver();
|
||||
const token = await this.getToken();
|
||||
const poolConfig = {
|
||||
server: stripScheme(this.config.sqlEndpoint),
|
||||
database: this.config.database,
|
||||
options: { encrypt: true, trustServerCertificate: false },
|
||||
authentication: {
|
||||
type: "azure-active-directory-access-token",
|
||||
options: { token },
|
||||
},
|
||||
pool: { max: 1, min: 0, idleTimeoutMillis: 30_000 },
|
||||
requestTimeout: this.config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
||||
};
|
||||
const pool = new sql.ConnectionPool(poolConfig);
|
||||
await pool.connect();
|
||||
this.pool = pool;
|
||||
return pool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a query and return rows + timing. This adapter does NOT enforce
|
||||
* row/time bounds itself — that is the job of the caller (see
|
||||
* src/services/source-query-service.ts), which wraps this in a timeout and
|
||||
* truncates the result for the synchronous path.
|
||||
*/
|
||||
async query<T = Record<string, unknown>>(queryText: string, params?: Record<string, unknown>): Promise<AdapterQueryResult<T>> {
|
||||
const start = Date.now();
|
||||
const pool = await this.getPool();
|
||||
const request = pool.request();
|
||||
if (params) {
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
request.input(key, value);
|
||||
}
|
||||
}
|
||||
const result = await request.query(queryText);
|
||||
const rows = (result.recordset ?? []) as T[];
|
||||
return { rows, rowCount: rows.length, durationMs: Date.now() - start };
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.pool) {
|
||||
await this.pool.close();
|
||||
this.pool = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createFabricOneLakeAdapter(
|
||||
config: FabricOneLakeConnectionConfig,
|
||||
fetchImpl?: typeof fetch,
|
||||
dnsLookupImpl?: DnsLookupFn,
|
||||
): FabricOneLakeAdapter {
|
||||
return new FabricOneLakeAdapter(config, fetchImpl, dnsLookupImpl);
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
/**
|
||||
* src/adapters/graph-mailbox-adapter.ts
|
||||
* ======================================
|
||||
* Tenant-agnostic Microsoft Graph mailbox poller (app-only client-credentials).
|
||||
*
|
||||
* Generalized from v0-datahub/lib/invoice-inbox/poll.ts: there the mailbox
|
||||
* ([email protected]), the Entra app, and the folder were all hardcoded
|
||||
* module constants. Here every one of those is a CALLER-SUPPLIED parameter —
|
||||
* any SIAX customer can register any mailbox (invoices, HR forms, contracts,
|
||||
* receipts, ...) and poll it through this adapter. Nothing about invoices,
|
||||
* vendors, or Protosell is baked in here — that logic (vendor-kb matching,
|
||||
* dup-hash, DQ scoring, invoice classification) was intentionally left
|
||||
* behind; it does not belong in a generic capture adapter.
|
||||
*/
|
||||
|
||||
const GRAPH_BASE = "https://graph.microsoft.com/v1.0";
|
||||
|
||||
export interface GraphMailboxConfig {
|
||||
/** Entra (Azure AD) tenant id the app registration lives in. */
|
||||
tenantId: string;
|
||||
/** Entra app (client) id — app-only, client-credentials grant. */
|
||||
clientId: string;
|
||||
/** Entra app client secret. Never logged, never persisted by this adapter. */
|
||||
clientSecret: string;
|
||||
/** Mailbox address to poll, e.g. "[email protected]". */
|
||||
mailboxAddress: string;
|
||||
/** Mail folder to poll. Default: "inbox". */
|
||||
folder?: string;
|
||||
}
|
||||
|
||||
export interface GraphMessage {
|
||||
id: string;
|
||||
internetMessageId: string | null;
|
||||
conversationId: string | null;
|
||||
receivedAt: string | null;
|
||||
senderName: string | null;
|
||||
senderEmail: string | null;
|
||||
toRecipients: string[];
|
||||
subject: string | null;
|
||||
bodyPreview: string | null;
|
||||
/** HTML body stripped to plain text. Falls back to bodyPreview when body is absent. */
|
||||
bodyText: string | null;
|
||||
hasAttachments: boolean;
|
||||
webLink: string | null;
|
||||
}
|
||||
|
||||
export interface GraphAttachment {
|
||||
id: string;
|
||||
name: string | null;
|
||||
contentType: string | null;
|
||||
sizeBytes: number | null;
|
||||
isPdf: boolean;
|
||||
contentBytes: Buffer;
|
||||
}
|
||||
|
||||
export interface PollMessagesOptions {
|
||||
/** Only return messages received at/after this ISO timestamp (incremental polling). */
|
||||
sinceISO?: string;
|
||||
/** Page size per Graph request. Default 50. */
|
||||
top?: number;
|
||||
/** Max number of pages to walk. Default 2 (raise for backfills). */
|
||||
maxPages?: number;
|
||||
}
|
||||
|
||||
/** Strip HTML to plain text. Generic — no document-type-specific parsing. */
|
||||
function stripHtml(html: string): string {
|
||||
return (html || "")
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, " ")
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, " ")
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/ /gi, " ")
|
||||
.replace(/&/gi, "&")
|
||||
.replace(/</gi, "<")
|
||||
.replace(/>/gi, ">")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export class GraphMailboxAdapter {
|
||||
private cachedToken: { token: string; expiresAt: number } | null = null;
|
||||
|
||||
constructor(private config: GraphMailboxConfig) {}
|
||||
|
||||
static isConfigured(config: Partial<GraphMailboxConfig>): boolean {
|
||||
return !!(config.tenantId && config.clientId && config.clientSecret && config.mailboxAddress);
|
||||
}
|
||||
|
||||
private async getToken(): Promise<string> {
|
||||
if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 30_000) {
|
||||
return this.cachedToken.token;
|
||||
}
|
||||
const { tenantId, clientId, clientSecret } = this.config;
|
||||
if (!tenantId || !clientId || !clientSecret) {
|
||||
throw new Error("GraphMailboxAdapter: missing tenantId/clientId/clientSecret");
|
||||
}
|
||||
const body = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
grant_type: "client_credentials",
|
||||
scope: "https://graph.microsoft.com/.default",
|
||||
});
|
||||
const res = await fetch(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
const json: Record<string, unknown> = await res.json();
|
||||
if (!res.ok) {
|
||||
throw new Error(`Graph token request failed: ${json.error || res.status} ${json.error_description || ""}`);
|
||||
}
|
||||
const expiresInMs = (typeof json.expires_in === "number" ? json.expires_in : 3600) * 1000;
|
||||
this.cachedToken = { token: json.access_token as string, expiresAt: Date.now() + expiresInMs };
|
||||
return this.cachedToken.token;
|
||||
}
|
||||
|
||||
// Graph-API:t är genuint ostrukturerat JSON (value-array med fri form);
|
||||
// full typning av hela Graph-ytan är egen insats — any här är medveten
|
||||
// och avgränsad till denna adapter (eslint-undantag med skäl, DoD §13).
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private async get(path: string): Promise<any> {
|
||||
const token = await this.getToken();
|
||||
const url = path.startsWith("http") ? path : `${GRAPH_BASE}${path}`;
|
||||
const res = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Graph-JSON är genuint ostrukturerat; full Graph-typning är egen insats
|
||||
const json: any = await res.json();
|
||||
if (!res.ok) {
|
||||
throw new Error(`Graph GET ${path} -> ${json.error?.code || res.status}: ${json.error?.message || ""}`);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
/** List messages in the configured mailbox/folder, newest first, optionally incremental. */
|
||||
async pollMessages(opts: PollMessagesOptions = {}): Promise<GraphMessage[]> {
|
||||
const folder = this.config.folder || "inbox";
|
||||
const top = opts.top ?? 50;
|
||||
const maxPages = opts.maxPages ?? 2;
|
||||
const select =
|
||||
"$select=id,internetMessageId,conversationId,receivedDateTime,from,toRecipients,subject,bodyPreview,hasAttachments,webLink,body";
|
||||
let sinceFilter = "";
|
||||
if (opts.sinceISO) {
|
||||
sinceFilter = `&$filter=receivedDateTime ge ${new Date(opts.sinceISO).toISOString()}`;
|
||||
}
|
||||
let url =
|
||||
`${GRAPH_BASE}/users/${encodeURIComponent(this.config.mailboxAddress)}/mailFolders/${encodeURIComponent(folder)}` +
|
||||
`/messages?$top=${top}&$orderby=receivedDateTime desc&${select}${sinceFilter}`;
|
||||
|
||||
const out: GraphMessage[] = [];
|
||||
for (let page = 0; page < maxPages && url; page++) {
|
||||
const data = await this.get(url);
|
||||
for (const m of data.value || []) {
|
||||
out.push({
|
||||
id: m.id,
|
||||
internetMessageId: m.internetMessageId || null,
|
||||
conversationId: m.conversationId || null,
|
||||
receivedAt: m.receivedDateTime || null,
|
||||
senderName: m.from?.emailAddress?.name || null,
|
||||
senderEmail: m.from?.emailAddress?.address || null,
|
||||
toRecipients: (m.toRecipients || []).map((r: { emailAddress?: { address?: string } }) => r.emailAddress?.address).filter(Boolean),
|
||||
subject: m.subject || null,
|
||||
bodyPreview: m.bodyPreview || null,
|
||||
bodyText: m.body?.content ? stripHtml(m.body.content) : m.bodyPreview || null,
|
||||
hasAttachments: !!m.hasAttachments,
|
||||
webLink: m.webLink || null,
|
||||
});
|
||||
}
|
||||
url = data["@odata.nextLink"] || "";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** List and download every file attachment on a message. */
|
||||
async listAttachments(messageId: string): Promise<GraphAttachment[]> {
|
||||
const data = await this.get(
|
||||
`/users/${encodeURIComponent(this.config.mailboxAddress)}/messages/${messageId}/attachments`,
|
||||
);
|
||||
const out: GraphAttachment[] = [];
|
||||
for (const a of data.value || []) {
|
||||
if (a["@odata.type"] !== "#microsoft.graph.fileAttachment" || !a.contentBytes) continue;
|
||||
const contentType: string | null = a.contentType || null;
|
||||
const name: string | null = a.name || null;
|
||||
const isPdf = (contentType || "").includes("pdf") || /\.pdf$/i.test(name || "");
|
||||
out.push({
|
||||
id: a.id,
|
||||
name,
|
||||
contentType,
|
||||
sizeBytes: typeof a.size === "number" ? a.size : null,
|
||||
isPdf,
|
||||
contentBytes: Buffer.from(a.contentBytes, "base64"),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* src/adapters/local-blob-store.ts
|
||||
* ==================================
|
||||
* INTERIM local-disk blob store — NOT the real ST0RE bytes backend.
|
||||
*
|
||||
* KNOWN GAP: src/clients/st0re-client.ts only registers artifact METADATA
|
||||
* (a pointer: provider/bucket/key/region). It has no endpoint that accepts
|
||||
* and persists raw bytes — ST0RE does not yet expose a real object-storage
|
||||
* write path for 0pt to call. Until it does, document-capture-service.ts
|
||||
* and document-extraction-service.ts write attachment/extraction bytes here
|
||||
* so the capability is functionally real end-to-end (download → persist →
|
||||
* read back for extraction) instead of silently discarding the PDF bytes
|
||||
* and only faking a metadata pointer.
|
||||
*
|
||||
* This is single-node, unencrypted-at-rest beyond the host filesystem, and
|
||||
* has no retention/lifecycle management — do not treat it as production
|
||||
* object storage. Swap it for a real ST0RE (or direct MinIO/Azure Blob)
|
||||
* client the day one exists; every call site that constructs this class is
|
||||
* marked "INTERIM" so the seam is easy to find.
|
||||
*/
|
||||
import { promises as fs } from "fs";
|
||||
import path from "path";
|
||||
import { isProductionRuntime } from "../platform/dependency-mode";
|
||||
import { SiaxError } from "../platform/errors";
|
||||
|
||||
export interface LocalBlobWriteResult {
|
||||
provider: "local_interim";
|
||||
bucket: string;
|
||||
key: string;
|
||||
absolutePath: string;
|
||||
sizeBytes: number;
|
||||
}
|
||||
|
||||
export class LocalBlobStore {
|
||||
constructor(private rootDir: string = process.env.OPT_LOCAL_BLOB_DIR || path.join(process.cwd(), ".data", "artifacts")) {}
|
||||
|
||||
/**
|
||||
* A fallback that silently swaps durable object storage for a container's
|
||||
* local filesystem is a double truth: `document-capture-service` registers
|
||||
* an artifact pointer claiming the bytes are stored, while the bytes sit on
|
||||
* an ephemeral single-node disk that is discarded on the next redeploy. In
|
||||
* production the honest answer is DEPENDENCY_UNAVAILABLE (the capability is
|
||||
* blocked because no ST0RE bytes path exists yet), never a fabricated
|
||||
* success. Dev/test keep the adapter so the capture -> persist -> read-back
|
||||
* flow stays exercisable end to end.
|
||||
*
|
||||
* Asserted per-operation rather than in the constructor so that merely
|
||||
* WIRING the service (both services construct one eagerly as a default) is
|
||||
* not itself fatal — only actually persisting or reading bytes is.
|
||||
*/
|
||||
private assertAllowed(operation: string): void {
|
||||
if (isProductionRuntime()) {
|
||||
throw new SiaxError(
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
"0pt.local_blob_store",
|
||||
`LocalBlobStore.${operation} is an interim dev/test adapter and may not persist document ` +
|
||||
`bytes in a production runtime; no canonical ST0RE bytes path is configured`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async write(bucket: string, key: string, bytes: Buffer): Promise<LocalBlobWriteResult> {
|
||||
this.assertAllowed("write");
|
||||
const safeKey = key.replace(/\.\./g, "_");
|
||||
const absolutePath = path.join(this.rootDir, bucket, safeKey);
|
||||
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
|
||||
await fs.writeFile(absolutePath, bytes);
|
||||
return { provider: "local_interim", bucket, key: safeKey, absolutePath, sizeBytes: bytes.length };
|
||||
}
|
||||
|
||||
async read(bucket: string, key: string): Promise<Buffer> {
|
||||
this.assertAllowed("read");
|
||||
const absolutePath = path.join(this.rootDir, bucket, key);
|
||||
return fs.readFile(absolutePath);
|
||||
}
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
/**
|
||||
* src/adapters/odoo-bills-adapter.ts
|
||||
* =====================================
|
||||
* `WritebackAdapter` (../adapters/writeback-adapter.ts) implementation for
|
||||
* Odoo Vendor Bills (`account.move`, `move_type: 'in_invoice'`) --
|
||||
* registered under `adapterId: "odoo_bills"` onto an
|
||||
* `ExternalWritebackService` (../services/external-writeback-service.ts).
|
||||
*
|
||||
* PORTED FROM v0-datahub's `lib/odoo/invoice-bridge.ts` (read in full before
|
||||
* writing this file), generalized as one WritebackAdapter implementation
|
||||
* rather than a standalone module with its own Supabase-coupled pipeline
|
||||
* function (`processInboxToOdoo`). What is a DIRECT PORT of proven logic,
|
||||
* vs. what is NEW/GENERALIZED, stated precisely:
|
||||
*
|
||||
* DIRECT PORT (same behavior, same guard order, same reasoning):
|
||||
* - `isReminder`/`duplicateFlag` guard -- invoice-bridge.ts's
|
||||
* `processInboxToOdoo`: "if (invoice.is_reminder || invoice.duplicate_flag)
|
||||
* return { ok:false, error: ... }" (a reminder or a detected duplicate is
|
||||
* NEVER posted to Odoo). Ported verbatim as this adapter's first guard in
|
||||
* `write()`.
|
||||
* - "already posted, skip" guard -- invoice-bridge.ts: "if
|
||||
* (invoice.odoo_move_id) { ...hoppar över...; return { ok:true, odoo_id:
|
||||
* invoice.odoo_move_id } }". Ported as the `existingExternalId` check --
|
||||
* this adapter's own idempotency defense-in-depth layer, complementing
|
||||
* (not replacing) `ExternalWritebackService`'s own in-memory claim -- see
|
||||
* that service's own module doc comment and writeback-adapter.ts's
|
||||
* `WritebackAdapter.write` doc comment for why BOTH layers exist.
|
||||
* - Partner matching by org-nr -- invoice-bridge.ts's
|
||||
* `matchInvoiceToOdooPartner`: digits-only comparison against
|
||||
* `odoo_export__res_partner.vat` so "556xxx-xxxx", "SE556xxxxxxxx01", and
|
||||
* "5561234567" all match the same partner. Ported as
|
||||
* `matchPartnerViaFabric` below, with ONE necessary substitution: the
|
||||
* original queried via v0-datahub's own `@/lib/warehouse/client`
|
||||
* (Next.js-app-local, not importable from this repo) -- this port uses
|
||||
* 0pt's own already-built, equally generic
|
||||
* `../adapters/fabric-onelake-adapter.ts` (built this same pass, for
|
||||
* 0pt.document_ocr's own needs) against the SAME table name
|
||||
* (`odoo_export__res_partner`) and the SAME digits-only `LIKE` query
|
||||
* shape, parameterized instead of string-interpolated.
|
||||
* - Vendor Bill request shape -- invoice-bridge.ts's `pushInvoiceToOdoo`:
|
||||
* POSTs `{ model: "account.move", invoice: { partner_id, ref,
|
||||
* invoice_date, invoice_date_due, invoice_line_ids: [...] } }` to
|
||||
* `/api/odoo/invoices/write`. Ported verbatim as this adapter's own POST
|
||||
* body -- same endpoint path convention, same field names, so an existing
|
||||
* `/api/odoo/invoices/write` deployment needs no change to accept calls
|
||||
* from this adapter.
|
||||
* - Line synthesis fallback -- invoice-bridge.ts's `processInboxToOdoo`
|
||||
* builds a single summary `invoice_line_ids` entry
|
||||
* (`description: subject||vendor||"Faktura {number}"`, `quantity: 1,
|
||||
* unit_price: amount_excl_vat`) when no itemized lines exist. Ported as
|
||||
* `synthesizeSummaryLine` below, used only when `payload.lines` is absent.
|
||||
*
|
||||
* GENERALIZED / NEW (did not exist in the original, or could not be ported
|
||||
* 1:1):
|
||||
* - The Supabase read/claim/update-status statements in
|
||||
* `processInboxToOdoo` (the `invoice_inbox` table CRUD, and its own
|
||||
* atomic `UPDATE ... WHERE odoo_move_id IS NULL` claim) are NOT ported
|
||||
* here -- that is `ExternalWritebackService`'s job now (its own
|
||||
* adapter-agnostic in-memory claim, see that service's module doc
|
||||
* comment), not this adapter's. This adapter is stateless per call.
|
||||
* - `baseUrl`/`apiKey`/the Fabric credentials are all constructor
|
||||
* parameters -- the original hardcoded `process.env.ODOO_BASE_URL`/
|
||||
* `process.env.NEXT_PUBLIC_APP_URL`/etc as module-level env reads (v0-
|
||||
* datahub is a single-tenant app; this repo is a SIAX platform capability
|
||||
* any customer's tenant can register their own Odoo instance against, the
|
||||
* same "nothing hardcoded, everything a caller-supplied credential"
|
||||
* doctrine ../adapters/fabric-onelake-adapter.ts's own header already
|
||||
* documents for the identical reason).
|
||||
* - `fetchImpl`/`matchPartner` are injectable (default to the real `fetch`
|
||||
* / `matchPartnerViaFabric`) purely so tests never make a real network
|
||||
* call -- the original had no test coverage for this path at all
|
||||
* (v0-datahub's invoice-bridge.ts has no accompanying test file); this
|
||||
* port is genuinely tested (see tests/p0/odoo-bills-adapter.test.ts).
|
||||
*/
|
||||
import type { WritebackAdapter, WritebackAdapterContext, WritebackRequest, WritebackResult } from "./writeback-adapter";
|
||||
import { FabricOneLakeAdapter, type FabricOneLakeConnectionConfig } from "./fabric-onelake-adapter";
|
||||
|
||||
/** One itemized Vendor Bill line -- same shape as invoice-bridge.ts's `InvoiceForOdoo.lines`. */
|
||||
export interface OdooBillLine {
|
||||
description: string;
|
||||
quantity: number;
|
||||
unit_price: number;
|
||||
vat_rate?: number;
|
||||
account_bas?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The structured record this adapter expects as `WritebackRequest.payload`
|
||||
* -- same field set as invoice-bridge.ts's `InvoiceForOdoo`, plus the guard
|
||||
* fields (`is_reminder`/`duplicate_flag`/`existing_external_id`) that
|
||||
* `processInboxToOdoo` read directly off its own `invoice_inbox` row (this
|
||||
* adapter has no row of its own to read them from, so the caller supplies
|
||||
* them on the payload instead).
|
||||
*/
|
||||
export interface OdooBillPayload {
|
||||
vendor_name: string;
|
||||
vendor_org_nr?: string;
|
||||
/** Pre-resolved Odoo res.partner id -- when absent and `vendor_org_nr` is set, this adapter
|
||||
* attempts to resolve one via partner matching (see this file's module doc comment). */
|
||||
partner_id?: number;
|
||||
invoice_number: string;
|
||||
ocr?: string;
|
||||
amount_gross: number;
|
||||
amount_excl_vat?: number;
|
||||
vat?: number;
|
||||
currency: string;
|
||||
invoice_date: string;
|
||||
due_date?: string;
|
||||
description?: string;
|
||||
lines?: readonly OdooBillLine[];
|
||||
/** Mirrors invoice_inbox.is_reminder -- a payment reminder must never be posted as a new Bill. */
|
||||
is_reminder?: boolean;
|
||||
/** Mirrors invoice_inbox.duplicate_flag -- a detected duplicate must never be posted. */
|
||||
duplicate_flag?: boolean;
|
||||
/** When the caller already knows this record was posted (e.g. re-delivering a webhook), pass
|
||||
* the known Odoo id here -- this adapter treats it as already-done and returns it unchanged,
|
||||
* exactly mirroring invoice-bridge.ts's own `invoice.odoo_move_id` early-return. */
|
||||
existing_external_id?: string;
|
||||
}
|
||||
|
||||
export type OdooPartnerMatcher = (
|
||||
orgNr: string,
|
||||
ctx: WritebackAdapterContext,
|
||||
) => Promise<{ partner_id?: number; partner_name?: string }>;
|
||||
|
||||
export interface OdooBillsAdapterConfig {
|
||||
/** Base URL of the deployment exposing `/api/odoo/invoices/write` (same route shape as
|
||||
* v0-datahub's own `/api/odoo/invoices/write` this was ported from). */
|
||||
baseUrl: string;
|
||||
/** Bearer credential for that route. Optional ONLY when `allowUnauthenticated` is explicitly
|
||||
* set (e.g. a route that authenticates by network policy instead) -- see `isConfigured`. */
|
||||
apiKey?: string;
|
||||
allowUnauthenticated?: boolean;
|
||||
/** Fabric/OneLake connection used for org-nr -> Odoo partner matching (this file's own
|
||||
* `matchPartnerViaFabric`), when `matchPartner` is not explicitly supplied. Optional --
|
||||
* without it (and without an explicit `matchPartner`), partner matching is skipped entirely
|
||||
* and the Bill is posted without a partner link, mirroring invoice-bridge.ts's own
|
||||
* `matchInvoiceToOdooPartner` catch-all ("Ingen partner match — skickar utan
|
||||
* partner-koppling"). */
|
||||
fabric?: FabricOneLakeConnectionConfig;
|
||||
/** Table name for the partner lookup query -- defaults to `odoo_export__res_partner`, the
|
||||
* exact table invoice-bridge.ts's own `matchInvoiceToOdooPartner` queried. */
|
||||
partnerTable?: string;
|
||||
/** Injectable partner matcher, for tests or a caller with its own partner-resolution source.
|
||||
* When supplied, this takes priority over `fabric`. */
|
||||
matchPartner?: OdooPartnerMatcher;
|
||||
/** Injectable `fetch`, so tests never make a real network call. */
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Digits-only org-nr -> Odoo partner match, ported 1:1 from invoice-bridge.ts's
|
||||
* `matchInvoiceToOdooPartner` (see this file's module doc comment). The only
|
||||
* substitution is the query transport: `FabricOneLakeAdapter.query` instead
|
||||
* of v0-datahub's `@/lib/warehouse/client` -- same table, same digits-only
|
||||
* `LIKE` comparison so "556xxx-xxxx"/"SE556xxxxxxxx01"/"5561234567" all
|
||||
* resolve to the same partner, now parameterized instead of string-interpolated.
|
||||
*/
|
||||
export async function matchPartnerViaFabric(
|
||||
fabric: FabricOneLakeAdapter,
|
||||
orgNr: string,
|
||||
partnerTable: string = "odoo_export__res_partner",
|
||||
): Promise<{ partner_id?: number; partner_name?: string }> {
|
||||
const digits = orgNr.replace(/[^0-9]/g, "");
|
||||
if (!digits) return {};
|
||||
try {
|
||||
const result = await fabric.query<{ id: number; name: string; vat: string }>(
|
||||
`SELECT TOP 1 id, name, vat FROM ${partnerTable} WHERE REPLACE(REPLACE(vat,'-',''),' ','') LIKE '%' + @digits + '%'`,
|
||||
{ digits },
|
||||
);
|
||||
if (result.rows.length > 0) {
|
||||
return { partner_id: result.rows[0]!.id, partner_name: result.rows[0]!.name };
|
||||
}
|
||||
return {};
|
||||
} catch {
|
||||
// Same catch-all as invoice-bridge.ts's own matchInvoiceToOdooPartner: an unreachable/
|
||||
// misconfigured warehouse must never fail the whole write -- it degrades to "post without
|
||||
// a partner link", not a thrown error.
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds the single synthesized `invoice_line_ids` entry used when `payload.lines` is absent
|
||||
* -- ported verbatim from invoice-bridge.ts's `processInboxToOdoo` line-synthesis block. */
|
||||
function synthesizeSummaryLine(payload: OdooBillPayload): OdooBillLine {
|
||||
const exclVat = payload.amount_excl_vat ?? payload.amount_gross;
|
||||
const description = (payload.description || payload.vendor_name || `Faktura ${payload.invoice_number}`).trim();
|
||||
return { description, quantity: 1, unit_price: exclVat };
|
||||
}
|
||||
|
||||
function isOdooBillPayload(payload: Readonly<Record<string, unknown>>): payload is OdooBillPayload & Record<string, unknown> {
|
||||
return (
|
||||
typeof payload.vendor_name === "string" &&
|
||||
typeof payload.invoice_number === "string" &&
|
||||
typeof payload.amount_gross === "number" &&
|
||||
typeof payload.currency === "string" &&
|
||||
typeof payload.invoice_date === "string"
|
||||
);
|
||||
}
|
||||
|
||||
export class OdooBillsAdapter implements WritebackAdapter {
|
||||
readonly adapterId = "odoo_bills";
|
||||
private fabricAdapter: FabricOneLakeAdapter | null;
|
||||
|
||||
constructor(private config: OdooBillsAdapterConfig) {
|
||||
this.fabricAdapter = config.fabric ? new FabricOneLakeAdapter(config.fabric, config.fetchImpl) : null;
|
||||
}
|
||||
|
||||
isConfigured(): boolean {
|
||||
return !!this.config.baseUrl && (!!this.config.apiKey || this.config.allowUnauthenticated === true);
|
||||
}
|
||||
|
||||
async write(request: WritebackRequest, ctx: WritebackAdapterContext): Promise<WritebackResult> {
|
||||
if (!this.isConfigured()) {
|
||||
return { ok: false, error: "odoo_not_configured" };
|
||||
}
|
||||
if (!isOdooBillPayload(request.payload)) {
|
||||
return { ok: false, error: "invalid_payload_missing_required_fields" };
|
||||
}
|
||||
const payload = request.payload as unknown as OdooBillPayload;
|
||||
|
||||
// Guard 1: reminders/duplicates are never posted -- ported verbatim from
|
||||
// invoice-bridge.ts's processInboxToOdoo (see this file's module doc comment).
|
||||
if (payload.is_reminder) return { ok: false, error: "is_reminder" };
|
||||
if (payload.duplicate_flag) return { ok: false, error: "duplicate" };
|
||||
|
||||
// Guard 2: already posted -- idempotent no-op, ported verbatim.
|
||||
if (payload.existing_external_id) {
|
||||
return { ok: true, externalId: payload.existing_external_id };
|
||||
}
|
||||
|
||||
// Partner match (best-effort, never fails the write) -- ported verbatim in spirit.
|
||||
let partnerId = payload.partner_id;
|
||||
if (!partnerId && payload.vendor_org_nr) {
|
||||
if (this.config.matchPartner) {
|
||||
const matched = await this.config.matchPartner(payload.vendor_org_nr, ctx);
|
||||
partnerId = matched.partner_id;
|
||||
} else if (this.fabricAdapter) {
|
||||
const matched = await matchPartnerViaFabric(this.fabricAdapter, payload.vendor_org_nr, this.config.partnerTable);
|
||||
partnerId = matched.partner_id;
|
||||
}
|
||||
}
|
||||
|
||||
const lines = payload.lines && payload.lines.length > 0 ? payload.lines : [synthesizeSummaryLine(payload)];
|
||||
|
||||
const fetchImpl = this.config.fetchImpl ?? fetch;
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchImpl(`${this.config.baseUrl}/api/odoo/invoices/write`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(this.config.apiKey ? { Authorization: `Bearer ${this.config.apiKey}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "account.move",
|
||||
invoice: {
|
||||
partner_id: partnerId,
|
||||
ref: payload.invoice_number,
|
||||
invoice_date: payload.invoice_date,
|
||||
invoice_date_due: payload.due_date,
|
||||
invoice_line_ids: lines.map((l) => ({ name: l.description, quantity: l.quantity, price_unit: l.unit_price })),
|
||||
},
|
||||
}),
|
||||
});
|
||||
} catch (e) {
|
||||
return { ok: false, error: `odoo_network_error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: `odoo_http_${res.status}` };
|
||||
}
|
||||
const result: { ok?: boolean; odoo_id?: number; error?: string } = await res.json();
|
||||
if (!result.ok || !result.odoo_id) {
|
||||
return { ok: false, error: result.error ?? "odoo_write_failed" };
|
||||
}
|
||||
return { ok: true, externalId: String(result.odoo_id) };
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/**
|
||||
* src/adapters/writeback-adapter.ts
|
||||
* ===================================
|
||||
* The adapter interface `ExternalWritebackService` (../services/
|
||||
* external-writeback-service.ts) writes through. One implementation per
|
||||
* external system (e.g. odoo-bills-adapter.ts's OdooBillsAdapter for Odoo
|
||||
* Vendor Bills) -- the service itself has zero knowledge of Odoo, Salesforce,
|
||||
* or any other concrete external system; it only knows "an adapter with this
|
||||
* adapterId exists, is configured, and can write a record."
|
||||
*/
|
||||
|
||||
export interface WritebackAdapterContext {
|
||||
tenant_id: string;
|
||||
project_id: string;
|
||||
actor_id: string;
|
||||
correlation_id: string;
|
||||
}
|
||||
|
||||
export interface WritebackRequest {
|
||||
recordType: string;
|
||||
payload: Readonly<Record<string, unknown>>;
|
||||
/** Same idempotency key the caller gave ExternalWritebackService -- forwarded so an adapter
|
||||
* with its own persistent storage (unlike the generic service's in-memory claim) can ALSO
|
||||
* claim defensively at its own layer. See WritebackAdapter.write's own doc comment. */
|
||||
idempotencyKey: string;
|
||||
}
|
||||
|
||||
export interface WritebackResult {
|
||||
ok: boolean;
|
||||
/** The external system's own id for the record that was created (or already existed --
|
||||
* see WritebackAdapter.write's own doc comment on idempotent re-calls), when ok is true. */
|
||||
externalId?: string;
|
||||
/** A short, stable, machine-readable reason code when ok is false (e.g. "is_reminder",
|
||||
* "duplicate", "odoo_http_500") -- NOT a free-form human sentence, so callers/tests can
|
||||
* assert on it reliably. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One external-system write adapter. Registered onto an
|
||||
* `ExternalWritebackService` via `registerAdapter` under a stable `adapterId`
|
||||
* (e.g. "odoo_bills") that `ExternalWriteRequest.adapter_id` references.
|
||||
*/
|
||||
export interface WritebackAdapter {
|
||||
readonly adapterId: string;
|
||||
|
||||
/** Whether this adapter has everything it needs (base URL, credentials, etc) to actually
|
||||
* write -- mirrors DocumentIntelligenceAdapter.isConfigured's "refuse to fabricate a result"
|
||||
* convention (../adapters/document-intelligence-adapter.ts): an unconfigured adapter must
|
||||
* never be silently treated as a no-op success. */
|
||||
isConfigured(): boolean;
|
||||
|
||||
/**
|
||||
* Writes one record to the external system.
|
||||
*
|
||||
* IDEMPOTENCY, TWO LAYERS (per this task's own instruction not to regress the proven
|
||||
* idempotent-claim logic ported from v0-datahub's invoice-bridge.ts):
|
||||
* 1. `ExternalWritebackService` (the caller) already claims `idempotencyKey` in its own
|
||||
* in-memory map BEFORE ever calling this method, so under normal operation `write` is
|
||||
* only ever called once per logical record, from one service instance.
|
||||
* 2. That in-memory claim is process-local and does not survive a restart, nor protect a
|
||||
* multi-instance deployment. An adapter backed by its own persistent storage (like
|
||||
* OdooBillsAdapter, when a caller supplies an already-posted record's
|
||||
* `existing_external_id` in the payload) MUST ALSO refuse to re-post a record that
|
||||
* already carries an external id -- exactly the "Redan bokförd i Odoo... hoppar över"
|
||||
* early-return invoice-bridge.ts's own `processInboxToOdoo` performs. This is the
|
||||
* genuine defense-in-depth the original proven code had; a `WritebackAdapter`
|
||||
* implementation with real persistent storage should follow the same doctrine.
|
||||
*/
|
||||
write(request: WritebackRequest, ctx: WritebackAdapterContext): Promise<WritebackResult>;
|
||||
}
|
||||
@@ -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
@@ -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' };
|
||||
}),
|
||||
};
|
||||
}
|
||||
Vendored
-329
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user