feat(analytics): BI-P014/016..022/025..026/028..031 — query contract, analyst SQL, execution, cache, cost, dbt, quality, metrics #35

Merged
admin merged 14 commits from feat/bi-p014-p031-query-metric-quality into main 2026-09-07 01:25:38 +00:00
66 changed files with 13889 additions and 637 deletions
+51
View File
@@ -0,0 +1,51 @@
# `analytics/dbt/` — BI-P022
The canonical SIAX transformation project. **Nothing in this repository runs
it.** Execution lives in N0D (`n0d#38`), against the contract in
`src/analytics/transform/dbt-contract.ts`.
## Layers, and why they map onto BI-P003
| directory | tier (BI-P003) | may read | must not contain |
| ---------------------- | -------------- | --------------------- | --------------------- |
| `models/sources/` | `RAW` | — (declarations only) | any SQL |
| `models/staging/` | `NORMALIZED` | sources | joins, business logic |
| `models/intermediate/` | `CURATED` | staging | presentation shaping |
| `models/marts/` | `SERVING` | intermediate | direct source reads |
`assertLayerDependenciesLegal` enforces the "may read" column against the
dependency graph in `manifest.json`. A mart reading a source directly is
refused — that is raw data reaching a dashboard, which is precisely what
BI-P003's tier rule exists to prevent, and a convention nobody checks would not
prevent it.
## What a run must produce
`manifest.json` and `run_results.json`, both registered as ST0RE artifacts.
`assertValidDbtJobResult` refuses a result missing either: without them the run
cannot be audited and its tests cannot be ingested by BI-P025's
`DbtQualityProvider`.
It also refuses:
- a result whose revision differs from the request — the run is not reproducible;
- a result whose observed dbt version differs from the pin — a runtime that is
not the pinned one silently changes what the models mean;
- `status: success` with **zero nodes executed** — a dbt selector that matches
nothing exits 0, which is the dbt-shaped false green.
## Version posture
`DBT_RUNTIME_PIN` records dbt Core 1.10.13 (stable line) with
`dbt-clickhouse` 1.9.2. **Both review flags are `false`.** No licence or
supply-chain review has been performed in this repo, and none is claimed.
`assertDbtRuntimeCertified` refuses a `production` run until they are true, so
BI-P022's "after current license/security verification" is a gate rather than a
sentence in a document.
## Credentials
A dbt run never receives a tenant's warehouse credential from this repo. N0D
resolves a credential whose write scope matches `target_layer` and
`expected_target_schema`, and the contract refuses a request whose expected
schema is not scoped to the job's tenant.
+43
View File
@@ -0,0 +1,43 @@
# BI-P022 — the canonical SIAX analytics transformation project.
#
# Execution happens in N0D (n0d#38), never here. This project is the MODELS and
# the CONVENTIONS; src/analytics/transform/dbt-contract.ts is the job contract
# N0D consumes, and it is what refuses a run that is not reproducible.
name: siax_analytics
version: 1.0.0
config-version: 2
profile: siax_analytics
model-paths: ['models']
test-paths: ['tests']
snapshot-paths: ['snapshots']
macro-paths: ['macros']
# The four layers map onto BI-P003's tiers rather than inventing a fifth
# vocabulary. `+tags` carries the tier so a manifest reader can assign one
# without parsing paths, and dbt-contract.ts asserts the mapping.
models:
siax_analytics:
+materialized: view
staging:
+schema: staging
+materialized: view
+tags: ['tier:NORMALIZED']
intermediate:
+schema: intermediate
+materialized: table
+tags: ['tier:CURATED']
marts:
+schema: marts
+materialized: table
+tags: ['tier:SERVING']
snapshots:
siax_analytics:
+target_schema: snapshots
# `on_schema_change: fail` rather than `sync_all_columns`: a silently widened
# table is how a downstream metric starts averaging a column that did not exist
# yesterday. BI-P004's contract gate is the same rule one layer up.
vars:
siax_tenant_id: '__set_by_n0d__'
@@ -0,0 +1,16 @@
-- CURATED (BI-P003). Joins and conformed entities. Reads STAGING only.
{{ config(materialized='table', tags=['tier:CURATED']) }}
select
e.event_id,
e.tenant_id,
e.customer_id,
e.amount_sek,
e.channel,
coalesce(c.country_code, e.country_code) as country_code,
c.segment,
e.invoiced_at
from {{ ref('stg_sales_events') }} e
left join {{ ref('stg_customers') }} c
on e.customer_id = c.customer_id
and e.tenant_id = c.tenant_id -- the join itself stays tenant-scoped
@@ -0,0 +1,17 @@
-- SERVING (BI-P003). What a dashboard or a BI-P028 metric reads.
--
-- Reads INTERMEDIATE only. Reading a source here would skip two layers, and
-- assertLayerDependenciesLegal refuses that against the manifest graph.
{{ config(materialized='table', tags=['tier:SERVING']) }}
select
tenant_id,
date_trunc('day', invoiced_at) as day,
country_code,
channel,
segment,
count(*) as order_count,
sum(amount_sek) as net_revenue_sek
from {{ ref('int_sales_enriched') }}
where channel != 'internal' -- matches the net_revenue metric's baked filter
group by 1, 2, 3, 4, 5
+19
View File
@@ -0,0 +1,19 @@
version: 2
models:
- name: mart_sales_daily
description: >
SERVING projection behind the `net_revenue` and `orders` metrics.
A blocking test failure here quarantines the serving projection
(BI-P025); the quarantine is enforced on the READ side.
columns:
- name: tenant_id
tests: [not_null]
- name: day
tests: [not_null]
- name: net_revenue_sek
tests: [not_null]
- name: order_count
tests:
- not_null
- dbt_utils.accepted_range: { min_value: 1, inclusive: true }
+34
View File
@@ -0,0 +1,34 @@
version: 2
# RAW. Declared, never modelled. A source has no SQL of its own — anything that
# transforms belongs in staging, where BI-P003 assigns it NORMALIZED.
sources:
- name: opt_raw
description: >
Landed, untransformed data as delivered by the 0pt sourcing engine.
RAW tier: no BI surface may read this directly without a recorded
BI-P003 exception.
schema: "{{ var('siax_tenant_id') }}_raw"
loaded_at_field: ingested_at
freshness:
# BI-P026's DELAYED/STALE thresholds, expressed where dbt can act on them.
warn_after: { count: 90, period: minute }
error_after: { count: 180, period: minute }
tables:
- name: sales_events
description: One row per invoiced sales line, as landed.
columns:
- name: event_id
tests: [not_null, unique]
- name: tenant_id
description: Present on every raw row; the tier boundary depends on it.
tests: [not_null]
- name: ingested_at
tests: [not_null]
- name: customers
description: Customer master as landed.
columns:
- name: customer_id
tests: [not_null, unique]
- name: tenant_id
tests: [not_null]
+26
View File
@@ -0,0 +1,26 @@
version: 2
models:
- name: stg_sales_events
description: Normalized sales events — one row per event_id, latest landing wins.
columns:
- name: event_id
tests: [not_null, unique]
- name: tenant_id
tests: [not_null]
- name: amount_sek
tests:
- not_null
- dbt_utils.accepted_range:
min_value: 0
inclusive: true
- name: channel
tests:
- accepted_values:
values: ['web', 'retail', 'partner', 'internal']
- name: stg_customers
columns:
- name: customer_id
tests: [not_null, unique]
- name: tenant_id
tests: [not_null]
@@ -0,0 +1,11 @@
-- NORMALIZED (BI-P003).
{{ config(materialized='view', tags=['tier:NORMALIZED']) }}
select
cast(customer_id as varchar) as customer_id,
cast(tenant_id as varchar) as tenant_id,
cast(name as varchar) as customer_name,
cast(segment as varchar) as segment,
cast(country as varchar) as country_code
from {{ source('opt_raw', 'customers') }}
where tenant_id = '{{ var("siax_tenant_id") }}'
@@ -0,0 +1,30 @@
-- NORMALIZED (BI-P003). Rename, cast, deduplicate. No joins, no business logic.
--
-- The tenant predicate is applied HERE, at the first modelled layer, so every
-- downstream model inherits it and no later model has to remember. It is the
-- same forced-predicate rule as the query compiler's, one layer up.
{{ config(materialized='view', tags=['tier:NORMALIZED']) }}
with source as (
select * from {{ source('opt_raw', 'sales_events') }}
where tenant_id = '{{ var("siax_tenant_id") }}'
),
deduplicated as (
select
*,
row_number() over (partition by event_id order by ingested_at desc) as _rn
from source
)
select
cast(event_id as varchar) as event_id,
cast(tenant_id as varchar) as tenant_id,
cast(customer_id as varchar) as customer_id,
cast(amount as double) as amount_sek,
cast(channel as varchar) as channel,
cast(country as varchar) as country_code,
cast(invoiced_at as timestamp) as invoiced_at,
cast(ingested_at as timestamp) as ingested_at
from deduplicated
where _rn = 1
@@ -0,0 +1,15 @@
-- Slowly-changing customer attributes, so a historical metric can be
-- recomputed against what a customer's segment WAS, not what it is now.
{% snapshot snap_customers %}
{{
config(
target_schema='snapshots',
unique_key='customer_id',
strategy='check',
check_cols=['segment', 'country_code'],
invalidate_hard_deletes=True
)
}}
select customer_id, tenant_id, customer_name, segment, country_code
from {{ ref('stg_customers') }}
{% endsnapshot %}
@@ -0,0 +1,7 @@
-- Fails when the serving mart is EMPTY.
--
-- Without this, every column test passes trivially over zero rows and the
-- whole suite reports green while the pipeline is dead — the same false green
-- BI-P025's NativeQualityProvider refuses.
select 1 as empty_mart
having (select count(*) from {{ ref('mart_sales_daily') }}) = 0
@@ -0,0 +1,11 @@
-- A singular test that FAILS if the serving mart ever contains a row belonging
-- to a tenant other than the one the run was scoped to.
--
-- The tenant predicate is applied in staging and inherited downstream, so this
-- test should be impossible to fail. That is precisely why it exists: an
-- isolation guarantee nobody tests is the one that turns out to have four
-- holes rather than the one reported.
select tenant_id, count(*) as rows_from_another_tenant
from {{ ref('mart_sales_daily') }}
where tenant_id != '{{ var("siax_tenant_id") }}'
group by tenant_id
+160
View File
@@ -0,0 +1,160 @@
# BI-P014, P016–P022, P025–P026, P028–P031 — query, metric, quality
Extends the analytics core merged in `0pt#34` (BI-P002..P012). Nothing there is
rebuilt.
This document is organised around what is **proven** and what is **not**,
because the second list is the one that gets dropped.
---
## Where things live
| prompt | module | live proof |
| -------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| BI-P014 DuckDB provider | `src/analytics/providers/duckdb-provider.ts` | `tests/duckdb/duckdb-provider.live.test.ts` |
| BI-P016 query request contract | `src/analytics/contract/query-request.ts`, `compile-clickhouse.ts`, `compile-semantic.ts` | unit only (pure compilation) |
| BI-P017 analyst SQL contract | `src/analytics/sql/` | `tests/integration/analyst-sql-clickhouse.integration.test.ts` |
| BI-P018 execution model | `src/analytics/execution/query-execution-record.ts` | `sql/009` + Postgres realinfra |
| BI-P019 cancellation | `src/analytics/execution/cancellation.ts` | `tests/integration/query-cancellation-budget.integration.test.ts` |
| BI-P020 query cache | `src/analytics/cache/query-cache.ts` | unit only (no engine involved) |
| BI-P021 cost / budget | `src/analytics/cost/query-budget.ts` | same live suite as BI-P019 |
| BI-P022 dbt contract | `src/analytics/transform/dbt-contract.ts`, `analytics/dbt/` | contract only — execution is `n0d#38` |
| BI-P025 quality provider | `src/analytics/quality/` | `tests/integration/data-quality-clickhouse.integration.test.ts` |
| BI-P026 freshness | `src/analytics/quality/freshness.ts` | unit + `sql/009` defaults |
| BI-P028/P031 metric model + governance | `src/analytics/metrics/metric-model.ts` | Postgres trigger, realinfra |
| BI-P029 semantic provider | `src/analytics/metrics/semantic-provider.ts` | **partially — see below** |
| BI-P030 semantic registry | `src/analytics/metrics/semantic-registry.ts` | unit + Postgres constraints |
---
## Five findings that changed the implementation
Each was found by writing a test that could fail, and each is pinned so it
cannot quietly stop being true.
### 1. ClickHouse `readonly = 1` on a user profile forbids **every** request setting
Measured on 24.8.14.39. A user whose profile carries `readonly = 1` answers
`Code: 164. Cannot modify 'max_rows_to_read' setting in readonly mode` to any
setting sent with the statement. So BI-P012's ceilings **cannot travel with an
analyst statement** — they are baked into the user's `SETTINGS PROFILE` at
provisioning. Proven both ways: an over-budget scan fails with code 158 from
the profile with no setting sent, and an attempt to raise it from the request
fails with 164.
### 2. `CREATE ROW POLICY IF NOT EXISTS` is a silent no-op on re-provisioning
Dropping a user empties the policy's apply-to list. The next provisioning run
sees the policy exists and does nothing, so it survives with
`apply_to_list = []` — applying to **nobody** — while `system.row_policies`
still shows the correct `select_filter`. The restricted user read 100 of 100
rows, **both tenants**, from the base table.
Fixed with `OR REPLACE`, plus `rowPolicyVerificationSql()` which turns "the
policy is applied" from an assumption into a query, and a test asserting
`applied_to_user = 1` per object. `CREATE SETTINGS PROFILE IF NOT EXISTS` has
the identical shape and is fixed the same way.
### 3. DuckDB's `allowed_directories` **alone** is a no-op
Measured on 1.5.5. With `allowed_directories` set to one mount directory and
nothing else, `read_csv('/etc/passwd')` **returned the file** and an `https://`
URL was fetched over the network. Only `enable_external_access = false`
alongside it makes the allow-list bind.
The obvious spelling of this control appears in `duckdb_settings()`, looks like
a sandbox, and permits everything. The measurement is pinned by a test that
never skips, so simplifying the bootstrap breaks the build rather than the
guarantee.
### 4. `pg_constraint.conname` is not schema-scoped
`SELECT 1 FROM pg_constraint WHERE conname = '...'` matches a same-named
constraint in **any** schema, so `sql/009` applied into a second schema
silently skipped every guarded `CHECK`. Every guard now scopes via
`conrelid = '<table>'::regclass`.
### 5. `describe.skipIf(flagSetInBeforeAll)` skips **always**
Vitest evaluates `skipIf` at collection time. Ten tests reported green while
skipping against a live, reachable ClickHouse. Replaced with the repo's
env-var gate, which **fails** when the variable is set and the server is down.
---
## What is NOT proven
- **BI-P029 / MetricFlow was never executed.** No Python runtime is
provisioned for this repo's CI, and BI-P029's "pin a currently verified
version" needs a licence and supply-chain review that has not happened.
`MetricFlowProvider.providerReadiness()` returns `verified: false` and names
all four open items. What _is_ proven is that the engine-neutral spec
compiles to a MetricFlow-shaped query and that canonical SIAX metric ids
survive a provider swap — tested against a second, deliberately
different-named provider so the equality is not trivially true.
- **The Superset integration path and the AI Analyst comparison** (BI-P029's
other two DoD surfaces) are not implemented.
- **dbt is not run here.** `DBT_RUNTIME_PIN` has both review flags `false`, and
`assertDbtRuntimeCertified` refuses a production run until they are true.
- **DuckDB Arrow IPC** is unproven: the `arrow` extension is a network install
the offline environment could not download. `readiness()` says so.
- **BI-P021's budget is a bound, not a hard cap.** In-flight enforcement is
granular to the poll interval, so the query overshoots between polls — and on
a columnar engine the overshoot is large. In the committed run
(`evidence/bi-p019-p021/`) a 1,000,000-row window cancelled the query at
**153,318,696 rows**, 55 ms in: a **153×** overshoot. The figure is
machine-dependent and moves between runs (an earlier run on the same box
recorded 131 M / 130×), which is itself the point — the bound is "roughly one
poll interval of engine throughput", not a number. It is still a bound: the
same query, unwatched, read **4,227,318,261 rows** before cancellation in the
BI-P019 case. Anyone quoting it as a hard cap is wrong.
- **The per-process window store does not bind across replicas.**
`describeEnforcement()` reports `"with N replicas a tenant can spend up to N
times this budget"`. A shared store (Valkey, or the CL0UD quota service)
behind `SharedWindowStore` is required for it to bind.
---
## Running the live suites
```bash
docker run -d --name ch -p 28123:8123 -e CLICKHOUSE_SKIP_USER_SETUP=1 \
clickhouse/clickhouse-server:24.8
docker run -d --name pg -p 25433:5432 -e POSTGRES_PASSWORD=test \
-e POSTGRES_DB=opt postgres:16-alpine
CLICKHOUSE_URL=http://127.0.0.1:28123 pnpm vitest run tests/integration
ANALYTICS_TEST_DATABASE_URL=postgres://postgres:[email protected]:25433/opt \
pnpm vitest run tests/analytics/analytics-governance-postgres.realinfra.test.ts
python -m venv .venv && .venv/bin/pip install duckdb pyarrow 'pyiceberg[sql-sqlite]'
DUCKDB_PYTHON=.venv/bin/python pnpm vitest run tests/duckdb
```
Every one of these **fails** rather than skipping when its variable is set and
the backend is unreachable.
---
## One note for whoever maintains `.gitea/workflows/ci.yml`
Not changed here — it is a protected file, and this branch touched none.
The integration job's guard is:
```sh
if grep -qE "skipped" /tmp/itest.log && ! grep -qE "Tests [0-9]+ passed" /tmp/itest.log
```
Vitest writes that summary with ANSI colour codes, so the literal text is
`Tests [22m [1m[32m81 passed[39m…`. The second pattern therefore **never
matches**, and the guard is effectively "any skip fails the job" rather than
the "skipped _and_ nothing passed" it reads as. That is stricter than intended,
not looser, so nothing is currently unguarded — but the escape hatch does not
work, and someone will eventually be puzzled by it. Piping through
`sed 's/\x1b\[[0-9;]*m//g'` before the grep would restore the intended
behaviour.
This is how the DuckDB suite's placement was caught, so the guard earned its
keep either way.
@@ -30,26 +30,10 @@
],
"num_rows": 3,
"pyarrow_values": {
"tenant_id": [
"t_alpha",
"t_beta",
"t_gamma"
],
"n": [
1,
2,
3
],
"v": [
1.5,
2.5,
3.25
],
"flag": [
true,
false,
true
],
"tenant_id": ["t_alpha", "t_beta", "t_gamma"],
"n": [1, 2, 3],
"v": [1.5, 2.5, 3.25],
"flag": [true, false, true],
"ts": [
"2026-01-01 00:00:00+00:00",
"2026-06-15 08:09:10.123000+00:00",
@@ -57,49 +41,16 @@
]
},
"duckdb_types": [
[
"tenant_id",
"VARCHAR"
],
[
"n",
"BIGINT"
],
[
"v",
"DOUBLE"
],
[
"flag",
"BOOLEAN"
],
[
"ts",
"TIMESTAMP WITH TIME ZONE"
]
["tenant_id", "VARCHAR"],
["n", "BIGINT"],
["v", "DOUBLE"],
["flag", "BOOLEAN"],
["ts", "TIMESTAMP WITH TIME ZONE"]
],
"duckdb_rows": [
[
"t_alpha",
"1",
"1.5",
"True",
"2026-01-01 00:00:00+00:00"
],
[
"t_beta",
"2",
"2.5",
"False",
"2026-06-15 08:09:10.123000+00:00"
],
[
"t_gamma",
"3",
"3.25",
"True",
"2026-09-06 12:34:56.789000+00:00"
]
["t_alpha", "1", "1.5", "True", "2026-01-01 00:00:00+00:00"],
["t_beta", "2", "2.5", "False", "2026-06-15 08:09:10.123000+00:00"],
["t_gamma", "3", "3.25", "True", "2026-09-06 12:34:56.789000+00:00"]
]
},
"0pt encoder -> arrow -> pyarrow/duckdb": {
@@ -129,26 +80,10 @@
],
"num_rows": 3,
"pyarrow_values": {
"tenant_id": [
"t_alpha",
"t_beta",
"t_gamma"
],
"n": [
1,
2,
3
],
"v": [
1.5,
2.5,
3.25
],
"flag": [
true,
false,
true
],
"tenant_id": ["t_alpha", "t_beta", "t_gamma"],
"n": [1, 2, 3],
"v": [1.5, 2.5, 3.25],
"flag": [true, false, true],
"ts": [
"2026-01-01 00:00:00+00:00",
"2026-06-15 08:09:10.123000+00:00",
@@ -156,49 +91,16 @@
]
},
"duckdb_types": [
[
"tenant_id",
"VARCHAR"
],
[
"n",
"BIGINT"
],
[
"v",
"DOUBLE"
],
[
"flag",
"BOOLEAN"
],
[
"ts",
"TIMESTAMP WITH TIME ZONE"
]
["tenant_id", "VARCHAR"],
["n", "BIGINT"],
["v", "DOUBLE"],
["flag", "BOOLEAN"],
["ts", "TIMESTAMP WITH TIME ZONE"]
],
"duckdb_rows": [
[
"t_alpha",
"1",
"1.5",
"True",
"2026-01-01 00:00:00+00:00"
],
[
"t_beta",
"2",
"2.5",
"False",
"2026-06-15 08:09:10.123000+00:00"
],
[
"t_gamma",
"3",
"3.25",
"True",
"2026-09-06 12:34:56.789000+00:00"
]
["t_alpha", "1", "1.5", "True", "2026-01-01 00:00:00+00:00"],
["t_beta", "2", "2.5", "False", "2026-06-15 08:09:10.123000+00:00"],
["t_gamma", "3", "3.25", "True", "2026-09-06 12:34:56.789000+00:00"]
]
}
},
+107
View File
@@ -0,0 +1,107 @@
{
"duckdb_version": "1.5.5",
"recorded_at": "2026-09-07T01:15:40.775Z",
"parquet": {
"SE": 394.5,
"NO": 105.5
},
"csv": {
"rows": 3,
"includes_quoted_value": true
},
"injection_attempt": {
"matched_rows": 0,
"note": "escaped as data; 0 rows, not 3"
},
"iceberg": {
"read_by": "iceberg_scan on the exact metadata JSON",
"note": "an exact metadata file is a SNAPSHOT reference; DuckDB refuses to glob for the latest version by default, and that refusal is correct — globbing can read uncommitted data",
"totals": {
"NO": 20,
"SE": 40
}
},
"symlink_escape_refused": true,
"sandbox_bypass_attempts": [
{
"id": "read-etc-passwd",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/etc/passwd\\\" - file system operations are disabled by configuration\\n\\nLINE 1: SELECT * FROM read_c"
},
{
"id": "read-etc-shadow",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/etc/shadow\\\" - file system operations are disabled by configuration\\n\\nLINE 1: SELECT * FROM read_c"
},
{
"id": "traversal-from-mount",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/tmp/claude-1000/-/987b696c-9462-4fac-b1c0-4e07bad73920/scratchpad/w-0pt-bi/tests/fixtures/duckdb/.."
},
{
"id": "glob-root",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/etc/*\\\" - file system operations are disabled by configuration\\n\\nLINE 1: SELECT * FROM read_csv('/"
},
{
"id": "http-exfiltration",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"https://example.com/a.csv\\\" - file system operations are disabled by configuration\\n\\nLINE 1: SELECT"
},
{
"id": "s3-read",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"s3://bucket/a.parquet\\\" - file system operations are disabled by configuration\\n\\nLINE 1: SELECT * F"
},
{
"id": "attach-external-db",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/tmp/duckdb_escape.db\\\" - file system operations are disabled by configuration\""
},
{
"id": "attach-etc",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/etc/passwd\\\" - file system operations are disabled by configuration\""
},
{
"id": "copy-out-of-mount",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/tmp/duckdb_escape.csv\\\" - file system operations are disabled by configuration\""
},
{
"id": "read-parquet-outside",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/root/x.parquet\\\" - file system operations are disabled by configuration\\n\\nLINE 1: SELECT * FROM re"
},
{
"id": "json-outside",
"succeeded": false,
"engine_message": "\"Permission Error: Cannot access file \\\"/etc/hosts\\\" - file system operations are disabled by configuration\\n\\nLINE 1: SELECT * FROM read_js"
}
],
"counterfactual_mounted_file_readable": true,
"naive_allowed_directories_is_a_noop": {
"statements": [
"SET allowed_directories=['/tmp/claude-1000/-/987b696c-9462-4fac-b1c0-4e07bad73920/scratchpad/w-0pt-bi/tests/fixtures/duckdb']"
],
"read_etc_passwd_succeeded": true,
"note": "allowed_directories alone appears in duckdb_settings() and looks like a sandbox. It permits /etc/passwd and outbound HTTP. Only enable_external_access=false binds it."
},
"reconfiguration_refused": [
{
"statement": "SET allowed_directories=['/etc']",
"refused": true,
"engine_message": "\"Invalid Input Error: Cannot change configuration option \\\"allowed_directories\\\" - the configuration has been locked\""
},
{
"statement": "SET enable_external_access=true",
"refused": true,
"engine_message": "\"Invalid Input Error: Cannot change configuration option \\\"enable_external_access\\\" - the configuration has been locked\""
},
{
"statement": "SET lock_configuration=false",
"refused": true,
"engine_message": "\"Invalid Input Error: Cannot change configuration option \\\"lock_configuration\\\" - the configuration has been locked\""
}
]
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
{
"clickhouse_version": "24.8.14.39",
"recorded_at": "2026-09-07T01:15:40.234Z",
"counterfactual_still_running_after_2s": true,
"cancellation": {
"rows_read_before_cancel": 4227318261,
"elapsed_ms_to_verified_stop": 162,
"verified_stopped": true,
"clickhouse_query_log_type": "ExceptionWhileProcessing",
"clickhouse_exception_code": 394
},
"budget_in_flight": {
"budget_max_rows_scanned": 1000000,
"observed_rows_read_at_cancel": 153318696,
"observed_elapsed_ms_at_cancel": 55,
"polls_before_breach": 1,
"overshoot_factor": 153,
"overshoot_note": "in-flight enforcement is granular to the poll interval; the query overshot the window by this factor before the poll that caught it. A bound, not a hard cap.",
"cancellation_verified": true,
"clickhouse_exception_code": 394,
"charged_for_work_done_before_cancel": true
},
"advisory_posture_is_declared": {
"admission": "estimate is compared to the remaining window before the query starts",
"in_flight": "NOT ENFORCED — this budget is advisory. A query that exceeds its estimate runs to completion.",
"across_replicas": "window spend is per-process — with N replicas a tenant can spend up to N times this budget",
"binding": false
}
}
+33
View File
@@ -0,0 +1,33 @@
{
"clickhouse_version": "24.8.14.39",
"recorded_at": "2026-09-07T01:15:45.657Z",
"not_null": {
"evaluated": 118,
"violations": 5
},
"range": {
"violations": 3
},
"distribution": {
"violations": 4
},
"unique": {
"violations": 11,
"breakdown": "6 rows on dup_0/dup_1, plus 5 rows sharing the empty-string key"
},
"empty_dataset": {
"raw_counts_from_clickhouse": {
"violations": 0,
"evaluated": 0
},
"verdict_passed": false,
"note": "a real engine returns zero violations over zero rows; the provider refuses to call that a pass"
},
"tenant_isolation": {
"base_table_rows": 618,
"alpha_evaluated": 118,
"alpha_violations": 5,
"beta_evaluated": 500,
"beta_violations": 500
}
}
@@ -0,0 +1,346 @@
-- 0pt analytics: execution metadata, metric governance, semantic registry,
-- quarantine (BI-P018, BI-P021, BI-P025, BI-P028, BI-P030, BI-P031).
--
-- Extends sql/008. Every statement is ADDITIVE and idempotent: ALTER TABLE ...
-- ADD COLUMN IF NOT EXISTS, CREATE TABLE IF NOT EXISTS, CREATE OR REPLACE
-- FUNCTION, DROP TRIGGER IF EXISTS before CREATE TRIGGER. It can be replayed
-- onto an already-migrated database, which is what the restore drill needs.
--
-- Ordering: requires sql/008 (it alters two of its tables).
--
-- WHY COLUMNS RATHER THAN NEW TABLES for the metric fields: BI-P028 names
-- fifteen fields and BI-P002 already persists nine of them. A second metric
-- table would be exactly the failure BI-P028's DoD is about ("no production
-- metric exists only inside a dashboard tool" generalises to "one metric, one
-- home"), so the six missing fields are added where the metric already lives.
-- ═══════════════════════════════════════════════════════════════════════════
-- BI-P018 — QUERY EXECUTION MODEL
-- ═══════════════════════════════════════════════════════════════════════════
-- The fields BI-P018 lists that sql/008's QueryExecution did not carry.
--
-- `compiled_query_hash` and NOT the statement: BI-P018 says "without
-- unnecessarily storing sensitive raw SQL". There is deliberately no
-- `query_text` column, and the CHECK below makes adding one by accident
-- visible — a hash is 64 hex characters and nothing else.
ALTER TABLE opt_analytics_query_execution
ADD COLUMN IF NOT EXISTS principal_id TEXT,
ADD COLUMN IF NOT EXISTS workload TEXT,
ADD COLUMN IF NOT EXISTS compiled_query_hash TEXT,
ADD COLUMN IF NOT EXISTS datasets TEXT[] NOT NULL DEFAULT '{}',
ADD COLUMN IF NOT EXISTS metrics TEXT[] NOT NULL DEFAULT '{}',
ADD COLUMN IF NOT EXISTS cache_status TEXT NOT NULL DEFAULT 'miss',
ADD COLUMN IF NOT EXISTS cost_units NUMERIC(20, 6);
-- NOTE ON THE GUARD SHAPE. `pg_constraint.conname` is NOT unique across
-- schemas: a bare `WHERE conname = '...'` matches a same-named constraint in
-- ANY schema and silently skips the ADD here. Found by running this file into
-- a second schema on a database that already had it in `public` — every CHECK
-- below was quietly absent, and the tests that should have proven them passed
-- because the INSERTs they expected to fail succeeded. Every guard therefore
-- scopes to the table via `conrelid = '<table>'::regclass`, which resolves
-- through search_path.
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'opt_analytics_query_execution_hash_shape'
AND conrelid = 'opt_analytics_query_execution'::regclass
) THEN
ALTER TABLE opt_analytics_query_execution
ADD CONSTRAINT opt_analytics_query_execution_hash_shape
CHECK (compiled_query_hash IS NULL OR compiled_query_hash ~ '^[0-9a-f]{64}$');
END IF;
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'opt_analytics_query_execution_cache_status'
AND conrelid = 'opt_analytics_query_execution'::regclass
) THEN
ALTER TABLE opt_analytics_query_execution
ADD CONSTRAINT opt_analytics_query_execution_cache_status
CHECK (cache_status IN ('hit','miss','bypass','stale_refused','not_cacheable'));
END IF;
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'opt_analytics_query_execution_workload'
AND conrelid = 'opt_analytics_query_execution'::regclass
) THEN
ALTER TABLE opt_analytics_query_execution
ADD CONSTRAINT opt_analytics_query_execution_workload
CHECK (workload IS NULL OR workload IN
('dashboard','report','api','analyst_sql','ai_analyst','scheduled','internal'));
END IF;
END $$;
-- Cost reporting is per tenant per window; index for it rather than making
-- every billing query a sequential scan of every tenant's executions.
CREATE INDEX IF NOT EXISTS opt_analytics_query_execution_cost_idx
ON opt_analytics_query_execution (tenant_id, submitted_at DESC)
WHERE cost_units IS NOT NULL;
-- ═══════════════════════════════════════════════════════════════════════════
-- BI-P017 — ANALYST SQL STATEMENT HISTORY
-- ═══════════════════════════════════════════════════════════════════════════
-- The ONE place raw SQL is retained, and it is a separate table with a
-- separate retention posture precisely so that decision is visible.
--
-- `statement_normalized` (literals masked) is NOT NULL: it is always present
-- and is the searchable, non-PII form. `statement_raw` is nullable, so a
-- deployment that chooses not to retain it simply leaves it NULL rather than
-- losing the history entirely.
CREATE TABLE IF NOT EXISTS opt_analytics_sql_statement (
statement_id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
project_id TEXT,
principal_id TEXT NOT NULL,
statement_normalized TEXT NOT NULL,
statement_raw TEXT,
statement_hash TEXT NOT NULL CHECK (statement_hash ~ '^[0-9a-f]{64}$'),
referenced_objects TEXT[] NOT NULL DEFAULT '{}',
outcome TEXT NOT NULL CHECK (outcome IN ('admitted','refused','succeeded','failed','cancelled')),
error_code TEXT,
refusal_reason TEXT,
submitted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
finished_at TIMESTAMPTZ,
duration_ms INTEGER,
rows_returned BIGINT,
rows_read BIGINT,
bytes_read BIGINT,
correlation_id TEXT,
-- A refusal must say why. An unreviewable refusal log is not an audit trail,
-- and an analyst probing the boundary is exactly what an operator needs to see.
CHECK (outcome <> 'refused' OR (refusal_reason IS NOT NULL AND length(btrim(refusal_reason)) > 0))
);
CREATE INDEX IF NOT EXISTS opt_analytics_sql_statement_tenant_idx
ON opt_analytics_sql_statement (tenant_id, submitted_at DESC);
CREATE INDEX IF NOT EXISTS opt_analytics_sql_statement_refused_idx
ON opt_analytics_sql_statement (tenant_id, submitted_at DESC)
WHERE outcome = 'refused';
-- ═══════════════════════════════════════════════════════════════════════════
-- BI-P028 / BI-P031 — METRIC DOMAIN MODEL AND GOVERNANCE
-- ═══════════════════════════════════════════════════════════════════════════
ALTER TABLE opt_analytics_metric_definition
ADD COLUMN IF NOT EXISTS metric_type TEXT NOT NULL DEFAULT 'simple',
ADD COLUMN IF NOT EXISTS time_dimension TEXT,
ADD COLUMN IF NOT EXISTS unit TEXT,
ADD COLUMN IF NOT EXISTS currency TEXT,
ADD COLUMN IF NOT EXISTS display_format TEXT NOT NULL DEFAULT 'decimal',
ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'DRAFT',
ADD COLUMN IF NOT EXISTS filters_json TEXT NOT NULL DEFAULT '[]',
ADD COLUMN IF NOT EXISTS certification TEXT NOT NULL DEFAULT 'experimental',
ADD COLUMN IF NOT EXISTS business_definition TEXT,
ADD COLUMN IF NOT EXISTS technical_definition TEXT,
ADD COLUMN IF NOT EXISTS meaning_hash TEXT,
ADD COLUMN IF NOT EXISTS certified_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS certified_by TEXT;
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'opt_analytics_metric_status'
AND conrelid = 'opt_analytics_metric_definition'::regclass) THEN
ALTER TABLE opt_analytics_metric_definition ADD CONSTRAINT opt_analytics_metric_status
CHECK (status IN ('DRAFT','REVIEW','ACTIVE','DEPRECATED','RETIRED'));
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'opt_analytics_metric_type'
AND conrelid = 'opt_analytics_metric_definition'::regclass) THEN
ALTER TABLE opt_analytics_metric_definition ADD CONSTRAINT opt_analytics_metric_type
CHECK (metric_type IN ('simple','ratio','derived','cumulative','conversion'));
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'opt_analytics_metric_format'
AND conrelid = 'opt_analytics_metric_definition'::regclass) THEN
ALTER TABLE opt_analytics_metric_definition ADD CONSTRAINT opt_analytics_metric_format
CHECK (display_format IN ('integer','decimal','percent','currency','duration_ms','bytes'));
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'opt_analytics_metric_certification'
AND conrelid = 'opt_analytics_metric_definition'::regclass) THEN
ALTER TABLE opt_analytics_metric_definition ADD CONSTRAINT opt_analytics_metric_certification
CHECK (certification IN ('experimental','certified','deprecated'));
END IF;
-- A currency-formatted metric with no currency is how SEK gets rendered as
-- USD on a dashboard nobody double-checks.
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'opt_analytics_metric_currency_pairing'
AND conrelid = 'opt_analytics_metric_definition'::regclass) THEN
ALTER TABLE opt_analytics_metric_definition ADD CONSTRAINT opt_analytics_metric_currency_pairing
CHECK (
(display_format = 'currency' AND currency IS NOT NULL AND currency ~ '^[A-Z]{3}$')
OR (display_format <> 'currency' AND currency IS NULL)
);
END IF;
-- Certification is an ACT: it has an actor and a time, or it has not happened.
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'opt_analytics_metric_certification_act'
AND conrelid = 'opt_analytics_metric_definition'::regclass) THEN
ALTER TABLE opt_analytics_metric_definition ADD CONSTRAINT opt_analytics_metric_certification_act
CHECK (
certification <> 'certified'
OR (certified_by IS NOT NULL AND certified_at IS NOT NULL
AND business_definition IS NOT NULL AND technical_definition IS NOT NULL)
);
END IF;
END $$;
-- ── BI-P031's DoD, in the DATABASE ────────────────────────────────────────
-- "Certified metric cannot be modified in-place; new version required."
--
-- The TypeScript check (assertMetricEditAllowed) is layer 1. This trigger is
-- layer 2, and it is the one that holds when something writes to the table
-- without going through the application — a migration script, a psql session,
-- an admin tool. A compiler opinion does not survive `psql`; a trigger does.
--
-- The rule is on the MEANING HASH, so a change this trigger has never heard of
-- still counts as a change: new fields default to "changes the meaning" rather
-- than to "allowed", which is the fail-closed direction.
CREATE OR REPLACE FUNCTION opt_analytics_metric_certified_immutable() RETURNS trigger AS $$
BEGIN
IF OLD.certification = 'certified'
AND NEW.current_version = OLD.current_version
AND NEW.meaning_hash IS DISTINCT FROM OLD.meaning_hash THEN
RAISE EXCEPTION
'BI-P031: metric % is CERTIFIED; its definition cannot be modified in place - mint version %',
OLD.name, OLD.current_version + 1
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS opt_analytics_metric_certified_guard ON opt_analytics_metric_definition;
CREATE TRIGGER opt_analytics_metric_certified_guard
BEFORE UPDATE ON opt_analytics_metric_definition
FOR EACH ROW EXECUTE FUNCTION opt_analytics_metric_certified_immutable();
-- ═══════════════════════════════════════════════════════════════════════════
-- BI-P030 — SEMANTIC MODEL REGISTRY
-- ═══════════════════════════════════════════════════════════════════════════
-- Persisted SEPARATELY from any implementation engine, which is the whole
-- point of the prompt. There is no column here for a provider manifest, and
-- `assertOnlySemanticModelFields` refuses one in the application; the schema
-- refuses it by simply not having anywhere to put it.
--
-- sql/008's opt_analytics_semantic_model holds the current model; this table
-- holds the VERSION HISTORY BI-P030 enumerates, and its rows are immutable for
-- the same reason a MetricVersion's are: a dashboard pinned to version 7 must
-- mean the same thing tomorrow.
CREATE TABLE IF NOT EXISTS opt_analytics_semantic_model_version (
semantic_model_version_id TEXT PRIMARY KEY,
model_id TEXT NOT NULL,
tenant_id TEXT NOT NULL,
project_id TEXT NOT NULL,
version INTEGER NOT NULL CHECK (version >= 1),
datasets TEXT[] NOT NULL DEFAULT '{}',
relationships_json TEXT NOT NULL DEFAULT '[]',
metrics_json TEXT NOT NULL DEFAULT '[]',
dimensions_json TEXT NOT NULL DEFAULT '[]',
valid_from TIMESTAMPTZ NOT NULL DEFAULT now(),
status TEXT NOT NULL CHECK (status IN ('draft','active','superseded','retired')),
hash TEXT NOT NULL CHECK (hash ~ '^[0-9a-f]{64}$'),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_by TEXT,
UNIQUE (tenant_id, model_id, version)
);
CREATE INDEX IF NOT EXISTS opt_analytics_semantic_model_version_tenant_idx
ON opt_analytics_semantic_model_version (tenant_id, project_id, model_id, version DESC);
-- At most ONE active version per model per tenant. A partial unique index
-- rather than application discipline: two active versions is a silent
-- correctness failure in which half the dashboards read a different model.
CREATE UNIQUE INDEX IF NOT EXISTS opt_analytics_semantic_model_one_active
ON opt_analytics_semantic_model_version (tenant_id, model_id)
WHERE status = 'active';
-- A published version's CONTENT is immutable; only its status and valid_from
-- may move (draft -> active -> superseded -> retired).
CREATE OR REPLACE FUNCTION opt_analytics_semantic_version_content_immutable() RETURNS trigger AS $$
BEGIN
IF NEW.hash IS DISTINCT FROM OLD.hash
OR NEW.metrics_json IS DISTINCT FROM OLD.metrics_json
OR NEW.dimensions_json IS DISTINCT FROM OLD.dimensions_json
OR NEW.relationships_json IS DISTINCT FROM OLD.relationships_json
OR NEW.datasets IS DISTINCT FROM OLD.datasets
OR NEW.version IS DISTINCT FROM OLD.version THEN
RAISE EXCEPTION
'BI-P030: semantic model % v% is immutable; publish a new version instead',
OLD.model_id, OLD.version
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS opt_analytics_semantic_version_guard ON opt_analytics_semantic_model_version;
CREATE TRIGGER opt_analytics_semantic_version_guard
BEFORE UPDATE ON opt_analytics_semantic_model_version
FOR EACH ROW EXECUTE FUNCTION opt_analytics_semantic_version_content_immutable();
-- ═══════════════════════════════════════════════════════════════════════════
-- BI-P025 / BI-P026 — QUARANTINE AND FRESHNESS
-- ═══════════════════════════════════════════════════════════════════════════
-- The quarantine record BI-P025's DoD acts on. The READ-side gate lives in the
-- application (`assertProjectionReadable`); this is its durable state, so a
-- process restart does not release a quarantine.
CREATE TABLE IF NOT EXISTS opt_analytics_projection_quarantine (
tenant_id TEXT NOT NULL,
dataset_id TEXT NOT NULL REFERENCES opt_analytics_dataset (dataset_id),
quarantined BOOLEAN NOT NULL,
caused_by TEXT[] NOT NULL DEFAULT '{}',
reason TEXT,
since TIMESTAMPTZ,
released_at TIMESTAMPTZ,
released_by TEXT,
PRIMARY KEY (tenant_id, dataset_id),
-- Release is an ACT with an operator behind it, never an automatic
-- consequence of a later passing run: a flapping rule would otherwise
-- quarantine and un-quarantine a dataset between two reads of one dashboard.
CHECK (quarantined OR released_at IS NULL OR (released_by IS NOT NULL AND reason IS NOT NULL))
);
-- BI-P026 freshness state, per dataset. `UNKNOWN` is the DEFAULT, deliberately:
-- a dataset nobody has computed freshness for must not read as FRESH.
CREATE TABLE IF NOT EXISTS opt_analytics_dataset_freshness (
tenant_id TEXT NOT NULL,
dataset_id TEXT NOT NULL REFERENCES opt_analytics_dataset (dataset_id),
state TEXT NOT NULL DEFAULT 'UNKNOWN'
CHECK (state IN ('FRESH','DELAYED','STALE','FAILED','UNKNOWN')),
age_ms BIGINT,
last_successful_load_at TIMESTAMPTZ,
last_run_at TIMESTAMPTZ,
last_run_status TEXT CHECK (last_run_status IN ('succeeded','failed','running','never_run')),
expected_interval_ms BIGINT NOT NULL,
disclosure TEXT NOT NULL,
computed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, dataset_id),
-- Every state must carry a disclosure a UI can render verbatim. A state with
-- no words attached is a state a dashboard will render as a silent green dot.
CHECK (length(btrim(disclosure)) > 0)
);
-- ═══════════════════════════════════════════════════════════════════════════
-- BI-P021 — USAGE LEDGER
-- ═══════════════════════════════════════════════════════════════════════════
-- What CL0UD quotas, AUD0 usage and B00K accounting read. Append-only.
--
-- `terminated_by_budget` is recorded because a query the budget killed still
-- COST what it burned before it died; not charging for it is how a tenant
-- learns that the cheapest query is one that gets cancelled.
CREATE TABLE IF NOT EXISTS opt_analytics_usage_ledger (
usage_id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
project_id TEXT,
principal_id TEXT NOT NULL,
query_id TEXT NOT NULL,
engine TEXT NOT NULL,
rows_scanned BIGINT NOT NULL DEFAULT 0,
bytes_scanned BIGINT NOT NULL DEFAULT 0,
storage_read_bytes BIGINT NOT NULL DEFAULT 0,
execution_ms BIGINT NOT NULL DEFAULT 0,
cost_units NUMERIC(20, 6) NOT NULL,
terminated_by_budget BOOLEAN NOT NULL DEFAULT false,
recorded_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS opt_analytics_usage_ledger_window_idx
ON opt_analytics_usage_ledger (tenant_id, recorded_at DESC);
DROP TRIGGER IF EXISTS opt_analytics_usage_ledger_immutable ON opt_analytics_usage_ledger;
CREATE TRIGGER opt_analytics_usage_ledger_immutable
BEFORE UPDATE OR DELETE ON opt_analytics_usage_ledger
FOR EACH ROW EXECUTE FUNCTION opt_analytics_forbid_mutation();
+329
View File
@@ -0,0 +1,329 @@
/**
* 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);
}
}
@@ -0,0 +1,252 @@
/**
* 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.
*/
const AGG_IF: Record<string, (mParam: string) => string> = {
sum: (p) => `sumIf(value, metric = {${p}:String})`,
avg: (p) => `avgIf(value, metric = {${p}:String})`,
min: (p) => `minIf(value, metric = {${p}:String})`,
max: (p) => `maxIf(value, metric = {${p}:String})`,
count: (p) => `countIf(metric = {${p}:String})`,
count_distinct: (p) => `uniqExactIf(event_id, metric = {${p}:String})`,
};
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}"`);
}
selectParts.push(`${template(key)} 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 ?? [], 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[],
index: number,
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)}`,
);
}
}
}
+145
View File
@@ -0,0 +1,145 @@
/**
* 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;
}
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 })),
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,
};
}
+489
View File
@@ -0,0 +1,489 @@
/**
* src/analytics/contract/query-request.ts
* ========================================
* BI-P016 — QUERY REQUEST CONTRACT.
*
* The canonical shape every SIAX product/application API speaks when it wants
* analytics:
*
* AnalyticsQueryRequest { dataset metrics[] dimensions[] filters[]
* timeRange orderBy limit format }
*
* BI-P016's hard rule: "The default product/application API must NOT accept
* arbitrary SQL." That is enforced structurally, not by a review convention —
* there is no field in this type that can carry SQL, and
* `parseAnalyticsQueryRequest` REJECTS unknown keys rather than ignoring them.
* A caller who adds `sql`, `where`, `having` or `expression` gets
* INVALID_REQUEST, not silent truncation; silent truncation is how an
* "unsupported" field becomes a supported one after the next refactor.
*
* Everything in this request is a NAME, resolved through a declared catalog
* (`QueryResolution`) before it can reach a compiler. Caller text therefore
* never becomes a SQL identifier and never becomes a SQL literal — the two
* ways injection happens.
*
* WHY THIS IS SEPARATE FROM `MetricQueryRequest` (engine/query-compiler.ts):
* that type is the ENGINE's internal, already-resolved, single-metric input,
* and it carries `tenant_id` because the engine sets it. This one is the
* CONSUMER-facing contract: it has no tenant field at all, because a consumer
* must never be able to name a tenant. INF0's Wave-2 hole was exactly a tenant
* read out of a request body; the fix that sticks is a request type in which
* the field does not exist.
*/
import { SiaxError } from '../../platform/errors';
// ── vocabulary ─────────────────────────────────────────────────────────────
/**
* Filter operators. A CLOSED list: every one compiles to a fixed SQL shape
* with bound parameters. There is no "raw" or "expression" operator, and
* adding one would have to survive `filter-operators-are-closed` in
* tests/analytics/query-request-contract.test.ts.
*/
export const FILTER_OPERATORS = [
'eq',
'ne',
'in',
'not_in',
'lt',
'lte',
'gt',
'gte',
'contains',
'is_null',
'is_not_null',
] as const;
export type FilterOperator = (typeof FILTER_OPERATORS)[number];
/** Operators that take exactly one value. */
const SINGLE_VALUE_OPERATORS: readonly FilterOperator[] = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'contains'];
/** Operators that take one-or-more values. */
const MULTI_VALUE_OPERATORS: readonly FilterOperator[] = ['in', 'not_in'];
/** Operators that take NO value. Supplying one is a rejection, not a shrug. */
const NO_VALUE_OPERATORS: readonly FilterOperator[] = ['is_null', 'is_not_null'];
export const TIME_GRAINS = ['hour', 'day', 'week', 'month', 'quarter', 'year'] as const;
export type TimeGrain = (typeof TIME_GRAINS)[number];
export const ORDER_DIRECTIONS = ['asc', 'desc'] as const;
export type OrderDirection = (typeof ORDER_DIRECTIONS)[number];
/** Result encodings, matching `QueryResult.encoding` (BI-P002/BI-P005). */
export const REQUEST_FORMATS = ['json', 'arrow_ipc'] as const;
export type RequestFormat = (typeof REQUEST_FORMATS)[number];
// ── the request ────────────────────────────────────────────────────────────
export interface AnalyticsFilter {
/** Caller-facing dimension NAME. Resolved through the catalog, never spliced. */
dimension: string;
operator: FilterOperator;
/** Literal values. They travel as bound parameters; never as SQL text. */
values?: string[];
}
export interface AnalyticsTimeRange {
/**
* Caller-facing time dimension name. Omitted means "the dataset's declared
* primary time dimension", which the resolution supplies — a consumer never
* has to know the physical column.
*/
dimension?: string;
/** ISO-8601 inclusive lower bound. */
from?: string;
/** ISO-8601 EXCLUSIVE upper bound (half-open, so adjacent ranges never double count). */
to?: string;
grain?: TimeGrain;
}
export interface AnalyticsOrderBy {
/**
* A metric name or a dimension name that ALREADY APPEARS in this request.
* Ordering by something not selected is refused: it is both a correctness
* trap and the obvious place to smuggle an expression.
*/
ref: string;
direction: OrderDirection;
}
/** BI-P016's canonical request, field-for-field. */
export interface AnalyticsQueryRequest {
dataset: string;
metrics: string[];
dimensions: string[];
filters: AnalyticsFilter[];
timeRange?: AnalyticsTimeRange;
orderBy?: AnalyticsOrderBy[];
limit?: number;
format?: RequestFormat;
}
/** The exact keys the contract accepts at the top level. */
export const ANALYTICS_QUERY_REQUEST_KEYS = [
'dataset',
'metrics',
'dimensions',
'filters',
'timeRange',
'orderBy',
'limit',
'format',
] as const;
/**
* Keys a caller might reach for when they want to smuggle SQL. Listed
* explicitly so the rejection MESSAGE names the rule rather than saying
* "unknown key" — an integrator who tries `sql` should learn why, not guess.
* The unknown-key rejection below covers everything, listed or not.
*/
const SQL_SMELLING_KEYS = new Set([
'sql',
'query',
'rawSql',
'raw_sql',
'raw',
'where',
'having',
'expression',
'expr',
'select',
'from',
'groupBy',
'group_by',
'sqlFragment',
'unsafe',
'tenant',
'tenant_id',
'tenantId',
'project_id',
'database',
'catalog',
'table',
]);
const MAX_METRICS = 16;
const MAX_DIMENSIONS = 8;
const MAX_FILTERS = 32;
const MAX_FILTER_VALUES = 500;
const MAX_ORDER_BY = 8;
/** A name is a catalog key, not free text; keep it short and boring. */
const MAX_NAME_LENGTH = 128;
/** A filter VALUE is data (it is bound, never spliced) but still bounded. */
const MAX_VALUE_LENGTH = 4096;
export const DEFAULT_REQUEST_LIMIT = 1000;
function invalid(detail: string): never {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', detail);
}
function asObject(raw: unknown, what: string): Record<string, unknown> {
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) invalid(`${what} must be an object`);
return raw as Record<string, unknown>;
}
function asName(raw: unknown, what: string): string {
if (typeof raw !== 'string') invalid(`${what} must be a string`);
const v = raw.trim();
if (!v) invalid(`${what} must not be empty`);
if (v.length > MAX_NAME_LENGTH) invalid(`${what} exceeds ${MAX_NAME_LENGTH} characters`);
return v;
}
function rejectUnknownKeys(obj: Record<string, unknown>, allowed: readonly string[], what: string): void {
for (const key of Object.keys(obj)) {
if (allowed.includes(key)) continue;
if (SQL_SMELLING_KEYS.has(key)) {
invalid(
`"${key}" is not part of the analytics query contract — the product API does not accept SQL, ` +
`catalogs, or tenant selection (BI-P016)`,
);
}
invalid(`unknown field "${key}" in ${what}`);
}
}
/**
* Parse and VALIDATE an untrusted request body into the canonical contract.
*
* Fail-closed at every branch: an unparseable field is a rejection, never a
* default. The only defaulting this function does is `filters: []`,
* `dimensions: []` and `limit`, and each of those defaults is strictly
* narrower than any value a caller could have supplied.
*/
export function parseAnalyticsQueryRequest(raw: unknown): AnalyticsQueryRequest {
const obj = asObject(raw, 'analytics query request');
rejectUnknownKeys(obj, ANALYTICS_QUERY_REQUEST_KEYS, 'analytics query request');
const dataset = asName(obj.dataset, 'dataset');
if (!Array.isArray(obj.metrics)) invalid('metrics must be an array');
if (obj.metrics.length === 0) invalid('at least one metric is required');
if (obj.metrics.length > MAX_METRICS) invalid(`at most ${MAX_METRICS} metrics per request`);
const metrics = obj.metrics.map((m, i) => asName(m, `metrics[${i}]`));
if (new Set(metrics).size !== metrics.length) invalid('metrics contains duplicates');
const rawDimensions = obj.dimensions ?? [];
if (!Array.isArray(rawDimensions)) invalid('dimensions must be an array');
if (rawDimensions.length > MAX_DIMENSIONS) invalid(`at most ${MAX_DIMENSIONS} dimensions per request`);
const dimensions = rawDimensions.map((d, i) => asName(d, `dimensions[${i}]`));
if (new Set(dimensions).size !== dimensions.length) invalid('dimensions contains duplicates');
const rawFilters = obj.filters ?? [];
if (!Array.isArray(rawFilters)) invalid('filters must be an array');
if (rawFilters.length > MAX_FILTERS) invalid(`at most ${MAX_FILTERS} filters per request`);
const filters = rawFilters.map((f, i) => parseFilter(f, i));
const timeRange = obj.timeRange === undefined ? undefined : parseTimeRange(obj.timeRange);
const rawOrderBy = obj.orderBy ?? [];
if (!Array.isArray(rawOrderBy)) invalid('orderBy must be an array');
if (rawOrderBy.length > MAX_ORDER_BY) invalid(`at most ${MAX_ORDER_BY} orderBy entries`);
const orderBy = rawOrderBy.map((o, i) => parseOrderBy(o, i));
const selectable = new Set<string>([...metrics, ...dimensions]);
for (const o of orderBy) {
if (!selectable.has(o.ref)) {
invalid(`orderBy "${o.ref}" is neither a requested metric nor a requested dimension`);
}
}
let limit = DEFAULT_REQUEST_LIMIT;
if (obj.limit !== undefined) {
if (typeof obj.limit !== 'number' || !Number.isFinite(obj.limit))
invalid('limit must be a finite number');
if (!Number.isInteger(obj.limit)) invalid('limit must be an integer');
if (obj.limit < 1) invalid('limit must be >= 1');
limit = obj.limit;
}
let format: RequestFormat = 'json';
if (obj.format !== undefined) {
if (typeof obj.format !== 'string' || !(REQUEST_FORMATS as readonly string[]).includes(obj.format)) {
invalid(`format must be one of ${REQUEST_FORMATS.join(', ')}`);
}
format = obj.format as RequestFormat;
}
return { dataset, metrics, dimensions, filters, timeRange, orderBy, limit, format };
}
function parseFilter(raw: unknown, index: number): AnalyticsFilter {
const obj = asObject(raw, `filters[${index}]`);
rejectUnknownKeys(obj, ['dimension', 'operator', 'values'], `filters[${index}]`);
const dimension = asName(obj.dimension, `filters[${index}].dimension`);
if (typeof obj.operator !== 'string' || !(FILTER_OPERATORS as readonly string[]).includes(obj.operator)) {
invalid(`filters[${index}].operator must be one of ${FILTER_OPERATORS.join(', ')}`);
}
const operator = obj.operator as FilterOperator;
if (NO_VALUE_OPERATORS.includes(operator)) {
if (obj.values !== undefined) invalid(`filters[${index}].operator "${operator}" takes no values`);
return { dimension, operator };
}
if (!Array.isArray(obj.values)) invalid(`filters[${index}].values must be an array`);
if (obj.values.length === 0) invalid(`filters[${index}].values must not be empty`);
if (obj.values.length > MAX_FILTER_VALUES) {
invalid(`filters[${index}].values exceeds ${MAX_FILTER_VALUES} entries`);
}
if (SINGLE_VALUE_OPERATORS.includes(operator) && obj.values.length !== 1) {
invalid(`filters[${index}].operator "${operator}" takes exactly one value`);
}
if (!MULTI_VALUE_OPERATORS.includes(operator) && !SINGLE_VALUE_OPERATORS.includes(operator)) {
invalid(`filters[${index}].operator "${operator}" is not a value operator`);
}
const values = obj.values.map((v, i) => {
if (typeof v !== 'string') invalid(`filters[${index}].values[${i}] must be a string`);
if (v.length > MAX_VALUE_LENGTH)
invalid(`filters[${index}].values[${i}] exceeds ${MAX_VALUE_LENGTH} characters`);
return v;
});
return { dimension, operator, values };
}
function parseTimeRange(raw: unknown): AnalyticsTimeRange {
const obj = asObject(raw, 'timeRange');
rejectUnknownKeys(obj, ['dimension', 'from', 'to', 'grain'], 'timeRange');
const out: AnalyticsTimeRange = {};
if (obj.dimension !== undefined) out.dimension = asName(obj.dimension, 'timeRange.dimension');
if (obj.from !== undefined) out.from = asIsoInstant(obj.from, 'timeRange.from');
if (obj.to !== undefined) out.to = asIsoInstant(obj.to, 'timeRange.to');
if (obj.grain !== undefined) {
if (typeof obj.grain !== 'string' || !(TIME_GRAINS as readonly string[]).includes(obj.grain)) {
invalid(`timeRange.grain must be one of ${TIME_GRAINS.join(', ')}`);
}
out.grain = obj.grain as TimeGrain;
}
if (out.from && out.to && Date.parse(out.from) >= Date.parse(out.to)) {
invalid('timeRange.from must be strictly before timeRange.to');
}
return out;
}
/**
* A timestamp is validated as a real instant, not merely as "a string that
* gets bound". It is bound as a parameter either way, so this is not the
* injection defence — it is the defence against a nonsense range silently
* producing an empty answer that a dashboard renders as "zero sales".
*/
function asIsoInstant(raw: unknown, what: string): string {
if (typeof raw !== 'string') invalid(`${what} must be an ISO-8601 string`);
const v = raw.trim();
if (!/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:?\d{2})?)?$/.test(v)) {
invalid(`${what} is not an ISO-8601 timestamp`);
}
if (Number.isNaN(Date.parse(v))) invalid(`${what} is not a valid timestamp`);
return v;
}
function parseOrderBy(raw: unknown, index: number): AnalyticsOrderBy {
const obj = asObject(raw, `orderBy[${index}]`);
rejectUnknownKeys(obj, ['ref', 'direction'], `orderBy[${index}]`);
const ref = asName(obj.ref, `orderBy[${index}].ref`);
if (typeof obj.direction !== 'string' || !(ORDER_DIRECTIONS as readonly string[]).includes(obj.direction)) {
invalid(`orderBy[${index}].direction must be one of ${ORDER_DIRECTIONS.join(', ')}`);
}
return { ref, direction: obj.direction as OrderDirection };
}
// ── resolution: names -> declared catalog entries ──────────────────────────
/**
* What a metric NAME resolves to. Supplied from `MetricDefinition` rows
* (BI-P002/BI-P028); the compilers never invent one.
*/
export interface ResolvedMetric {
name: string;
metric_id: string;
/** The `metric` key stored in the analytics event table. */
event_metric_key: string;
aggregation: 'sum' | 'avg' | 'min' | 'max' | 'count' | 'count_distinct';
/** Dimension names this metric may legitimately be sliced by. */
allowed_dimensions: readonly string[];
unit?: string;
}
/** What a dimension NAME resolves to. Supplied from `DimensionDefinition` rows. */
export interface ResolvedDimension {
name: string;
dimension_id: string;
/** Physical key inside `dim_names`. Validated as an identifier downstream. */
field_name: string;
}
/**
* The declared surface for ONE dataset, for ONE tenant. A compiler is handed
* this; it cannot reach past it. An unresolvable name is a rejection.
*/
export interface QueryResolution {
dataset_id: string;
/** Semantic model version this resolution came from — part of the cache key (BI-P020). */
semantic_model_version?: number;
metric(name: string): ResolvedMetric | undefined;
dimension(name: string): ResolvedDimension | undefined;
/** Physical time dimension used when `timeRange.dimension` is omitted. */
defaultTimeDimension?: string;
}
export function queryResolutionFrom(args: {
dataset_id: string;
metrics: readonly ResolvedMetric[];
dimensions: readonly ResolvedDimension[];
semantic_model_version?: number;
defaultTimeDimension?: string;
}): QueryResolution {
const metricMap = new Map(args.metrics.map((m) => [m.name, m]));
const dimMap = new Map(args.dimensions.map((d) => [d.name, d]));
return {
dataset_id: args.dataset_id,
semantic_model_version: args.semantic_model_version,
defaultTimeDimension: args.defaultTimeDimension,
// Map lookups: "__proto__" / "constructor" resolve to undefined, as they must.
metric: (name) => metricMap.get(name),
dimension: (name) => dimMap.get(name),
};
}
/**
* Resolve every name in a request, or refuse the request.
*
* This is the single place where "a caller said X" becomes "the catalog
* declares Y". Both compile targets (ClickHouse and semantic) consume the
* RESOLVED form, which is why BI-P016's DoD holds: the consumer writes one
* request and neither target sees consumer text.
*/
export interface ResolvedQuery {
request: AnalyticsQueryRequest;
dataset_id: string;
metrics: ResolvedMetric[];
dimensions: ResolvedDimension[];
filters: Array<{ filter: AnalyticsFilter; dimension: ResolvedDimension }>;
timeDimension?: string;
semantic_model_version?: number;
}
export function resolveAnalyticsQuery(
request: AnalyticsQueryRequest,
resolution: QueryResolution,
): ResolvedQuery {
if (request.dataset !== resolution.dataset_id) {
// The resolution is built FOR a dataset the caller was authorised to read
// (BI-P006 grants). A mismatch means the caller is asking about something
// else entirely, and answering from this resolution would be a leak.
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics',
'requested dataset does not match the authorised resolution',
);
}
const metrics = request.metrics.map((name) => {
const m = resolution.metric(name);
if (!m) invalid(`unknown metric "${name}" for this dataset`);
return m;
});
const dimensions = request.dimensions.map((name) => {
const d = resolution.dimension(name);
if (!d) invalid(`unknown dimension "${name}" for this dataset`);
return d;
});
// Every requested dimension must be legitimate for EVERY requested metric.
// Slicing a metric by a dimension its definition does not allow is how a
// "harmless" grouping turns into an unintended disclosure.
for (const m of metrics) {
for (const d of dimensions) {
if (!m.allowed_dimensions.includes(d.name)) {
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics',
`metric "${m.name}" may not be sliced by dimension "${d.name}"`,
);
}
}
}
const filters = request.filters.map((f) => {
const d = resolution.dimension(f.dimension);
if (!d) invalid(`unknown filter dimension "${f.dimension}"`);
return { filter: f, dimension: d };
});
let timeDimension: string | undefined;
if (request.timeRange) {
if (request.timeRange.dimension) {
const d = resolution.dimension(request.timeRange.dimension);
if (!d) invalid(`unknown time dimension "${request.timeRange.dimension}"`);
timeDimension = d.field_name;
} else {
timeDimension = resolution.defaultTimeDimension;
if ((request.timeRange.from || request.timeRange.to) && !timeDimension) {
invalid('dataset declares no default time dimension; timeRange.dimension is required');
}
}
}
return {
request,
dataset_id: resolution.dataset_id,
metrics,
dimensions,
filters,
timeDimension,
semantic_model_version: resolution.semantic_model_version,
};
}
+415
View File
@@ -0,0 +1,415 @@
/**
* 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 };
}
}
+183
View File
@@ -0,0 +1,183 @@
/**
* 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;
}
@@ -0,0 +1,138 @@
/**
* 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;
}
}
@@ -0,0 +1,274 @@
/**
* 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`,
);
}
}
}
+419
View File
@@ -0,0 +1,419 @@
/**
* src/analytics/metrics/metric-model.ts
* ======================================
* BI-P028 — METRIC DOMAIN MODEL, and BI-P031 — METRIC GOVERNANCE.
*
* BI-P028 names a canonical metric with fifteen fields. BI-P002 (merged in
* 0pt#34) already persists a `MetricDefinition` row with nine of them. This
* module does NOT define a second, parallel metric: `MetricSpec` is the
* BI-P028 shape, `metricSpecFromDefinition`/`metricDefinitionFromSpec` bridge
* it to the persisted entity, and sql/009 adds the six columns BI-P028 needs
* that BI-P002 did not have. A second metric type would be the exact failure
* BI-P028's DoD is about.
*
* ── BI-P028's DoD, made enforceable ───────────────────────────────────────
* "No production metric exists only inside a dashboard tool."
*
* A statement of intent unless something refuses. `assertPanelUsesRegisteredMetric`
* is that something: a dashboard panel must reference a `metric_id` that the
* registry knows and that is ACTIVE. A panel carrying an inline aggregation, a
* SQL expression, or a metric id nobody registered is refused — so a metric
* cannot come into existence inside Superset and quietly become production.
*
* ── BI-P031's DoD, made enforceable ───────────────────────────────────────
* "Certified metric cannot be modified in-place; new version required."
*
* `assertMetricEditAllowed` refuses any change to a CERTIFIED metric's MEANING
* — measure, aggregation, filters, time dimension, unit, currency — and points
* the caller at `nextMetricVersion`. Editorial fields (description, owner,
* business definition) stay editable, because forcing a version bump to fix a
* typo is how teams learn to route around governance.
*
* The TypeScript check is layer 1. sql/009 carries the same rule as a Postgres
* trigger, which is layer 2 and the one that holds when something writes to
* the table without going through this code.
*/
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import type { MetricAggregation, MetricDefinition } from '../domain/entities';
// ── BI-P028 vocabulary ─────────────────────────────────────────────────────
/**
* `type` in BI-P028's field list. What KIND of metric this is, which is
* separate from how it aggregates: a `ratio` is two measures, a `cumulative`
* is a window over one, a `derived` is an expression over other metrics.
*/
export const METRIC_TYPES = ['simple', 'ratio', 'derived', 'cumulative', 'conversion'] as const;
export type MetricType = (typeof METRIC_TYPES)[number];
/** BI-P028's lifecycle, verbatim. */
export const METRIC_STATUSES = ['DRAFT', 'REVIEW', 'ACTIVE', 'DEPRECATED', 'RETIRED'] as const;
export type MetricStatus = (typeof METRIC_STATUSES)[number];
/** BI-P031's certification axis. Orthogonal to lifecycle status, on purpose. */
export const METRIC_CERTIFICATIONS = ['experimental', 'certified', 'deprecated'] as const;
export type MetricCertification = (typeof METRIC_CERTIFICATIONS)[number];
/** Display format. A number without one is a number a dashboard guesses at. */
export const METRIC_FORMATS = ['integer', 'decimal', 'percent', 'currency', 'duration_ms', 'bytes'] as const;
export type MetricFormat = (typeof METRIC_FORMATS)[number];
/**
* A metric-level filter. STRUCTURED, never a SQL string — same rule as
* BI-P016's request filters, and for the same reason: a metric definition that
* carries SQL is a raw-SQL surface with a governance label on it.
*/
export interface MetricFilter {
dimension: string;
operator: 'eq' | 'ne' | 'in' | 'not_in' | 'lt' | 'lte' | 'gt' | 'gte' | 'is_null' | 'is_not_null';
values?: string[];
}
/** BI-P028's canonical metric, field for field. */
export interface MetricSpec {
id: string;
name: string;
description: string;
type: MetricType;
/** The measure field aggregated (numerator, for a ratio). */
measure: string;
aggregation: MetricAggregation;
/** Denominator for a ratio metric. */
denominator?: string;
/** Dimension names this metric may legitimately be sliced by. */
dimensions: string[];
/** Filters baked into the metric's definition. */
filters: MetricFilter[];
/** The dimension time ranges and grains apply to. */
timeDimension: string;
unit?: string;
/** ISO-4217, required when `format` is "currency". */
currency?: string;
format: MetricFormat;
owner: string;
version: number;
status: MetricStatus;
}
/** BI-P031's governance envelope around a spec. */
export interface MetricGovernance {
certification: MetricCertification;
/** What the business means by this number, in prose, for a non-engineer. */
business_definition: string;
/** How it is actually computed, for an engineer. */
technical_definition: string;
owner: string;
/** Upstream datasets/models, from BI-P027 lineage. */
lineage_refs: string[];
/** Latest quality verdict for the metric's dataset (BI-P025). */
quality_status?: 'passing' | 'warning' | 'failing' | 'unknown';
/** Usage, from AUD0's BI-P076 events. Drives deprecation decisions. */
usage_30d?: { queries: number; distinct_principals: number; dashboards: number };
certified_at?: string;
certified_by?: string;
}
export interface GovernedMetric {
spec: MetricSpec;
governance: MetricGovernance;
}
// ── validation ─────────────────────────────────────────────────────────────
const NAME_RE = /^[a-z][a-z0-9_]{1,62}$/;
function invalid(detail: string): never {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.metrics', detail);
}
/**
* Validate a spec. Every rule here is one that, unenforced, produces a metric
* that renders as a plausible number and means nothing.
*/
export function assertValidMetricSpec(spec: MetricSpec): void {
if (!NAME_RE.test(spec.name)) {
invalid(`metric name "${spec.name}" must be a lowercase snake_case identifier`);
}
if (!spec.description?.trim()) {
// Not pedantry: an undescribed metric is the one two teams compute
// differently and argue about in a board meeting.
invalid(`metric "${spec.name}" has no description`);
}
if (!spec.owner?.trim()) invalid(`metric "${spec.name}" has no owner`);
if (!spec.timeDimension?.trim()) {
invalid(
`metric "${spec.name}" has no time dimension; a metric without one cannot be trended or compared`,
);
}
if (!(METRIC_TYPES as readonly string[]).includes(spec.type)) invalid(`unknown metric type "${spec.type}"`);
if (!(METRIC_STATUSES as readonly string[]).includes(spec.status))
invalid(`unknown metric status "${spec.status}"`);
if (!(METRIC_FORMATS as readonly string[]).includes(spec.format))
invalid(`unknown metric format "${spec.format}"`);
if (spec.version < 1 || !Number.isInteger(spec.version))
invalid('metric version must be a positive integer');
if (spec.type === 'ratio' && !spec.denominator) {
invalid(`ratio metric "${spec.name}" has no denominator`);
}
if (spec.type !== 'ratio' && spec.denominator) {
invalid(`metric "${spec.name}" is not a ratio but carries a denominator`);
}
if (spec.format === 'currency' && !spec.currency) {
// A currency-formatted number with no currency is how SEK gets rendered
// as USD on a dashboard nobody double-checks.
invalid(`metric "${spec.name}" is currency-formatted but names no currency`);
}
if (spec.currency && !/^[A-Z]{3}$/.test(spec.currency)) {
invalid(`metric "${spec.name}" currency must be an ISO-4217 code`);
}
if (spec.format !== 'currency' && spec.currency) {
invalid(`metric "${spec.name}" names a currency but is not currency-formatted`);
}
if (new Set(spec.dimensions).size !== spec.dimensions.length) {
invalid(`metric "${spec.name}" lists a dimension twice`);
}
for (const f of spec.filters) {
if (!spec.dimensions.includes(f.dimension) && f.dimension !== spec.timeDimension) {
invalid(`metric "${spec.name}" filters on "${f.dimension}", which is not one of its dimensions`);
}
const needsValues = !['is_null', 'is_not_null'].includes(f.operator);
if (needsValues && (!f.values || f.values.length === 0)) {
invalid(`metric "${spec.name}" filter on "${f.dimension}" has no values`);
}
if (!needsValues && f.values?.length) {
invalid(`metric "${spec.name}" filter operator "${f.operator}" takes no values`);
}
}
}
/**
* The hash that makes "did the meaning change?" answerable.
*
* Deliberately covers ONLY the semantic fields. Description, owner and version
* are excluded: a metric whose hash changed when someone fixed a typo would
* make every governance check cry wolf, and a check that cries wolf gets
* disabled.
*/
export function metricMeaningHash(spec: MetricSpec): string {
const meaning = JSON.stringify([
spec.type,
spec.measure,
spec.aggregation,
spec.denominator ?? '',
[...spec.dimensions].sort(),
[...spec.filters]
.map((f) => [f.dimension, f.operator, [...(f.values ?? [])].sort()])
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
spec.timeDimension,
spec.unit ?? '',
spec.currency ?? '',
]);
return crypto.createHash('sha256').update(meaning).digest('hex');
}
/** Fields whose change is EDITORIAL — allowed in place, even when certified. */
export const EDITORIAL_FIELDS: readonly (keyof MetricSpec)[] = [
'description',
'owner',
'status',
'format',
'name',
];
/**
* BI-P031's DoD. Refuses an in-place change to a CERTIFIED metric's meaning.
*
* The check is on the MEANING HASH, not on a field-by-field diff, so a change
* this code has never heard of is still caught — new fields default to
* "changes the meaning" rather than to "allowed", which is the fail-closed
* direction.
*/
export function assertMetricEditAllowed(current: GovernedMetric, proposed: MetricSpec): void {
if (current.spec.id !== proposed.id) {
invalid('a metric edit must not change the metric id');
}
if (current.governance.certification !== 'certified') return;
if (proposed.version !== current.spec.version) {
// A version bump is the sanctioned path; it is not an "edit".
return;
}
if (metricMeaningHash(current.spec) !== metricMeaningHash(proposed)) {
throw new SiaxError(
'CONFLICT',
'0pt.analytics.metrics',
`metric "${current.spec.name}" is CERTIFIED; its definition cannot be modified in place — ` +
`mint version ${current.spec.version + 1} instead`,
);
}
}
/**
* Mint the next version. The new version starts as DRAFT and EXPERIMENTAL:
* inheriting `certified` would let a certified metric's meaning change while
* still wearing the badge, which is the thing BI-P031 forbids.
*/
export function nextMetricVersion(
current: GovernedMetric,
changes: Partial<MetricSpec>,
reason: string,
): { spec: MetricSpec; governance: MetricGovernance; change_reason: string } {
if (!reason?.trim()) {
invalid('a new metric version requires a change reason');
}
const spec: MetricSpec = {
...current.spec,
...changes,
id: current.spec.id,
version: current.spec.version + 1,
status: 'DRAFT',
};
assertValidMetricSpec(spec);
return {
spec,
governance: {
...current.governance,
certification: 'experimental',
certified_at: undefined,
certified_by: undefined,
},
change_reason: reason,
};
}
/** Certification is an act with an actor and a time, not a boolean someone set. */
export function certifyMetric(metric: GovernedMetric, by: string, at: string): GovernedMetric {
if (metric.spec.status !== 'ACTIVE') {
invalid(`only an ACTIVE metric can be certified; "${metric.spec.name}" is ${metric.spec.status}`);
}
if (!metric.governance.business_definition?.trim() || !metric.governance.technical_definition?.trim()) {
invalid(
`metric "${metric.spec.name}" cannot be certified without both a business and a technical definition`,
);
}
if (!by?.trim()) invalid('certification requires the certifying principal');
return {
...metric,
governance: { ...metric.governance, certification: 'certified', certified_by: by, certified_at: at },
};
}
// ── BI-P028 DoD: no metric lives only in a dashboard ───────────────────────
/**
* A dashboard panel, as far as governance is concerned. It may name a metric.
* It may not BE one.
*/
export interface DashboardPanelRef {
panel_id: string;
metric_id?: string;
/** Anything a BI tool would let a user type instead of picking a metric. */
inline_expression?: string;
inline_aggregation?: string;
inline_sql?: string;
}
export interface MetricLookup {
(metricId: string): GovernedMetric | undefined;
}
export function assertPanelUsesRegisteredMetric(
panel: DashboardPanelRef,
lookup: MetricLookup,
): GovernedMetric {
for (const field of ['inline_expression', 'inline_aggregation', 'inline_sql'] as const) {
if (panel[field]) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" defines a metric inline via "${field}" — BI-P028: no production metric ` +
`may exist only inside a dashboard tool. Register it and reference its metric_id.`,
);
}
}
if (!panel.metric_id) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" references no metric_id`,
);
}
const metric = lookup(panel.metric_id);
if (!metric) {
throw new SiaxError(
'NOT_FOUND',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" references unregistered metric "${panel.metric_id}"`,
);
}
if (metric.spec.status === 'RETIRED') {
throw new SiaxError(
'CONFLICT',
'0pt.analytics.metrics',
`panel "${panel.panel_id}" references RETIRED metric "${metric.spec.name}"`,
);
}
return metric;
}
// ── bridge to the BI-P002 persisted entity ─────────────────────────────────
/**
* The BI-P028 spec, read out of the BI-P002 row plus sql/009's added columns.
* Kept as an explicit pair of functions rather than merging the types, so it
* is obvious which fields are new and where they are stored.
*/
export interface MetricDefinitionExtension {
metric_type: MetricType;
time_dimension: string;
unit?: string;
currency?: string;
display_format: MetricFormat;
status: MetricStatus;
filters_json: string;
certification: MetricCertification;
business_definition: string;
technical_definition: string;
meaning_hash: string;
}
export function metricSpecFromDefinition(def: MetricDefinition, ext: MetricDefinitionExtension): MetricSpec {
return {
id: def.metric_id,
name: def.name,
description: def.description ?? '',
type: ext.metric_type,
measure: def.measure_field,
aggregation: def.aggregation,
denominator: def.denominator_field,
dimensions: [...def.allowed_dimension_ids],
filters: JSON.parse(ext.filters_json) as MetricFilter[],
timeDimension: ext.time_dimension,
unit: ext.unit,
currency: ext.currency,
format: ext.display_format,
owner: def.owner_id,
version: def.current_version,
status: ext.status,
};
}
export function metricDefinitionExtensionFromSpec(
spec: MetricSpec,
governance: MetricGovernance,
): MetricDefinitionExtension {
return {
metric_type: spec.type,
time_dimension: spec.timeDimension,
unit: spec.unit,
currency: spec.currency,
display_format: spec.format,
status: spec.status,
filters_json: JSON.stringify(spec.filters),
certification: governance.certification,
business_definition: governance.business_definition,
technical_definition: governance.technical_definition,
meaning_hash: metricMeaningHash(spec),
};
}
+249
View File
@@ -0,0 +1,249 @@
/**
* src/analytics/metrics/semantic-provider.ts
* ===========================================
* BI-P029 — METRICFLOW PROVIDER.
*
* ── WHAT IS AND IS NOT PROVEN HERE. READ THIS BEFORE CITING BI-P029. ──────
*
* BI-P029's DoD asks that a golden metric return the same result via the 0pt
* Metric API, the MetricFlow CLI/provider, a Superset integration path, and
* the AI Analyst, within a numerical tolerance.
*
* MetricFlow is a Python package. It was NOT executed for this commit: there
* is no Python environment provisioned for this repo's CI, and adding one is a
* separate decision with its own supply-chain review (BI-P029 says "pin a
* currently verified OSI-compatible version", which requires that review to
* happen first — `METRICFLOW_PINNED_VERSION` below records the intended pin
* and is explicitly marked unverified).
*
* So what IS proven, in tests/integration/semantic-parity.integration.test.ts,
* is the part that does not need MetricFlow: the SAME golden metric, taken
* from the SAME registry version, executed against the SAME live ClickHouse
* data by TWO INDEPENDENT compilers — 0pt's metric compiler, and a renderer
* driven only by the engine-neutral `SemanticQuerySpec` — returns the same
* number. That is a real parity test between two code paths that share no
* SQL-generation code. It is NOT a test of MetricFlow, and this file does not
* claim to be one.
*
* The remaining three DoD surfaces (MetricFlow CLI, Superset, AI Analyst) are
* therefore OPEN. Saying so is the point; a green suite that quietly covered
* one of four surfaces would be the estate's recurring failure.
*/
import { SiaxError } from '../../platform/errors';
import type { SemanticQuerySpec } from '../contract/compile-semantic';
import type { MetricSpec } from './metric-model';
import type { SemanticModelVersion } from './semantic-registry';
/**
* The version this provider is written against.
*
* UNVERIFIED: no supply-chain or licence review has been run for it in this
* repo, and it has not been executed. It is a declared intent, not a
* certification, and `providerReadiness()` reports it as such so nothing
* downstream can mistake the constant for a green light.
*/
export const METRICFLOW_PINNED_VERSION = '0.208.1';
/** The provider-neutral port. BI-P029's `SiaxSemanticProvider`. */
export interface SiaxSemanticProvider {
readonly provider: string;
/**
* Emit this provider's own model document from the canonical registry
* version. The registry never stores it (BI-P030); it is derived.
*/
buildManifest(model: SemanticModelVersion): unknown;
/** Compile the engine-neutral spec into whatever this provider executes. */
compile(spec: SemanticQuerySpec, model: SemanticModelVersion): CompiledSemanticQuery;
/** Canonical SIAX metric id -> this provider's own name for it. */
providerBindings(model: SemanticModelVersion): Record<string, string>;
}
export interface CompiledSemanticQuery {
provider: string;
/** The provider's own query representation. Never SQL text from a caller. */
query: unknown;
/** Canonical metric ids, unchanged — the BI-P030 contract. */
canonical_metric_ids: string[];
}
export interface ProviderReadiness {
provider: string;
pinned_version: string;
/** True only when the pin has been reviewed AND the provider executed. */
verified: boolean;
/** What has actually been demonstrated. Plain words for an operator. */
proven: string[];
/** What has NOT. */
open: string[];
}
/**
* MetricFlow-shaped provider.
*
* The manifest it emits follows MetricFlow's semantic-manifest structure
* (semantic_models with entities/dimensions/measures, and metrics referencing
* them), so a future run of the real MetricFlow has something to consume. It
* is derived from the registry on demand and never persisted — persisting it
* would be exactly the BI-P030 violation the registry's `assertEngineNeutral`
* exists to prevent.
*/
export class MetricFlowProvider implements SiaxSemanticProvider {
readonly provider = 'metricflow';
providerReadiness(): ProviderReadiness {
return {
provider: this.provider,
pinned_version: METRICFLOW_PINNED_VERSION,
verified: false,
proven: [
'the engine-neutral SemanticQuerySpec compiles to a MetricFlow-shaped query',
'a MetricFlow semantic manifest is derived from the canonical registry without persisting it',
'canonical SIAX metric ids survive the compilation unchanged',
"0pt's metric compiler and an independent spec-driven renderer return the same number " +
'for the golden metric against live ClickHouse data',
],
open: [
`MetricFlow ${METRICFLOW_PINNED_VERSION} has NOT been executed — no Python runtime is provisioned`,
'the pinned version has NOT had a licence or supply-chain review',
'the Superset integration path is not implemented',
'the AI Analyst path (inf0#29) has not been compared against this provider',
],
};
}
buildManifest(model: SemanticModelVersion): {
/** Stamped so a document that leaked into a registry row is detectable. */
_generated_by: string;
_generated_from: { model_id: string; version: number; hash: string };
semantic_models: Array<Record<string, unknown>>;
metrics: Array<Record<string, unknown>>;
} {
const semantic_models = model.datasets.map((dataset) => {
const dims = model.dimensions.filter((d) => d.dataset_id === dataset);
const measures = model.metrics
.filter((m) => m.dimensions.some((dim) => dims.some((d) => d.name === dim)))
.map((m) => ({ name: m.measure, agg: mapAggregation(m.aggregation), expr: m.measure }));
return {
name: dataset,
node_relation: { alias: dataset, schema_name: '__resolved_at_execution__' },
entities: model.relationships
.filter((r) => r.from_dataset === dataset)
.map((r) => ({ name: r.from_field, type: r.kind === 'many_to_one' ? 'foreign' : 'primary' })),
dimensions: dims.map((d) => ({
name: d.name,
type: d.kind === 'time' ? 'time' : 'categorical',
...(d.kind === 'time' ? { type_params: { time_granularity: 'day' } } : {}),
})),
measures: dedupeBy(measures, (m) => m.name),
};
});
const metrics = model.metrics.map((m) => ({
// The CANONICAL id is what a consumer holds. The provider's own name is
// derived from it, never the other way round.
name: m.id,
description: m.description,
type: mapMetricType(m.type),
type_params: metricTypeParams(m),
filter: m.filters.length ? { where_filters: m.filters.map(structuredFilter) } : undefined,
meta: { siax_metric_id: m.id, siax_metric_version: m.version, unit: m.unit, currency: m.currency },
}));
return {
_generated_by: `${this.provider}@${METRICFLOW_PINNED_VERSION}`,
_generated_from: { model_id: model.model_id, version: model.version, hash: model.hash },
semantic_models,
metrics,
};
}
compile(spec: SemanticQuerySpec, model: SemanticModelVersion): CompiledSemanticQuery {
const known = new Map(model.metrics.map((m) => [m.id, m]));
for (const ref of spec.metrics) {
if (!known.has(ref.metric_id)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`metric "${ref.metric_id}" is not in semantic model ${model.model_id} v${model.version}`,
);
}
}
const timeBucket = spec.groupBy.find((g) => g.grain);
return {
provider: this.provider,
query: {
metrics: spec.metrics.map((m) => m.metric_id),
group_by: spec.groupBy.filter((g) => !g.grain).map((g) => g.name),
...(timeBucket ? { time_granularity: timeBucket.grain } : {}),
// STRUCTURED, not a `--where` SQL string. MetricFlow accepts predicate
// text; handing it caller-derived text would put a raw-SQL surface
// behind the closed DSL.
where: spec.where.map((w) => ({ dimension: w.name, operator: w.operator, values: w.values })),
order_by: spec.orderBy.map((o) => ({ name: o.ref, descending: o.direction === 'desc' })),
limit: spec.limit,
...(spec.timeConstraint
? { start_time: spec.timeConstraint.start, end_time: spec.timeConstraint.end }
: {}),
},
canonical_metric_ids: spec.metrics.map((m) => m.metric_id).sort(),
};
}
providerBindings(model: SemanticModelVersion): Record<string, string> {
// Identity for MetricFlow, because its metric names can be the canonical
// ids. A provider whose naming rules differ (Cube's cube.measure form)
// populates this differently — and THAT is the whole replaceability story:
// the bindings change, the canonical ids do not.
return Object.fromEntries(model.metrics.map((m) => [m.id, m.id]));
}
}
function mapAggregation(agg: MetricSpec['aggregation']): string {
switch (agg) {
case 'count_distinct':
return 'count_distinct';
case 'ratio':
case 'derived':
// Not a measure aggregation at all — these are metric-level types, and
// the manifest expresses them through type_params instead.
return 'sum';
default:
return agg;
}
}
function mapMetricType(type: MetricSpec['type']): string {
switch (type) {
case 'ratio':
return 'ratio';
case 'derived':
return 'derived';
case 'cumulative':
return 'cumulative';
case 'conversion':
return 'conversion';
default:
return 'simple';
}
}
function metricTypeParams(m: MetricSpec): Record<string, unknown> {
if (m.type === 'ratio') {
return { numerator: m.measure, denominator: m.denominator };
}
return { measure: { name: m.measure } };
}
function structuredFilter(f: MetricSpec['filters'][number]): Record<string, unknown> {
return { dimension: f.dimension, operator: f.operator, values: f.values ?? [] };
}
function dedupeBy<T>(items: T[], key: (t: T) => string): T[] {
const seen = new Set<string>();
return items.filter((i) => {
const k = key(i);
if (seen.has(k)) return false;
seen.add(k);
return true;
});
}
+316
View File
@@ -0,0 +1,316 @@
/**
* src/analytics/metrics/semantic-registry.ts
* ===========================================
* BI-P030 — SEMANTIC MODEL REGISTRY.
*
* "Persist semantic model version SEPARATELY FROM IMPLEMENTATION ENGINE.
* DoD: MetricFlow can be replaced without breaking canonical SIAX metric IDs."
*
* Which means exactly one thing in code, and it is a negative: NOTHING in this
* file may name MetricFlow, Cube, dbt, ClickHouse, Trino or DuckDB. A registry
* that stores a MetricFlow manifest is a MetricFlow registry with a neutral
* name on it. `assertEngineNeutral` enforces the negative at runtime by
* scanning a serialized version for engine vocabulary, and the test asserts it
* catches a manifest that smuggles one in — because the rule is exactly the
* kind that decays silently.
*
* The canonical SIAX metric id is the contract. A provider maps it to whatever
* its own model calls that metric (BI-P029's `providerBindings`), and swapping
* providers changes the BINDINGS, never the ids — so a dashboard, an API
* consumer or a saved query keeps working.
*/
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import type { MetricSpec } from './metric-model';
export const SEMANTIC_MODEL_STATUSES = ['draft', 'active', 'superseded', 'retired'] as const;
export type SemanticModelStatus = (typeof SEMANTIC_MODEL_STATUSES)[number];
export const RELATIONSHIP_KINDS = ['one_to_many', 'many_to_one', 'one_to_one'] as const;
export type RelationshipKind = (typeof RELATIONSHIP_KINDS)[number];
export interface SemanticRelationship {
from_dataset: string;
from_field: string;
to_dataset: string;
to_field: string;
kind: RelationshipKind;
}
export interface SemanticDimension {
id: string;
name: string;
dataset_id: string;
/** "categorical" | "time". A time dimension is what grains apply to. */
kind: 'categorical' | 'time';
}
/** BI-P030's fields, verbatim. */
export interface SemanticModelVersion {
model_id: string;
version: number;
tenant_id: string;
datasets: string[];
relationships: SemanticRelationship[];
/** Canonical SIAX metric ids and their specs at this version. */
metrics: MetricSpec[];
dimensions: SemanticDimension[];
valid_from: string;
status: SemanticModelStatus;
hash: string;
}
/**
* Engine vocabulary that must never appear in a persisted semantic model.
*
* Checked against the SERIALIZED version, so it catches an engine name hiding
* in a nested field somebody added later — the failure mode a type cannot
* prevent.
*/
const ENGINE_VOCABULARY = [
'metricflow',
'clickhouse',
'trino',
'duckdb',
'cube.js',
'cubejs',
'dbt_metric',
'superset',
'presto',
'bigquery',
'snowflake',
];
/** The only top-level keys a persisted semantic model may carry. */
export const SEMANTIC_MODEL_KEYS = [
'model_id',
'version',
'tenant_id',
'datasets',
'relationships',
'metrics',
'dimensions',
'valid_from',
'status',
'hash',
] as const;
/**
* The STRUCTURAL half of engine neutrality, and the load-bearing one.
*
* `assertEngineNeutral` below is a VOCABULARY scan: it catches a model that
* says "metricflow" or "clickhouse". It cannot catch a document that is
* structurally MetricFlow-shaped while avoiding the word — a limitation found
* by a test that expected it to and did not. So publishing also rejects any
* key outside the BI-P030 field list, which means a provider manifest cannot
* be stored in a registry row at all, whatever it calls itself.
*/
export function assertOnlySemanticModelFields(model: object): void {
for (const key of Object.keys(model)) {
if (!(SEMANTIC_MODEL_KEYS as readonly string[]).includes(key)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`semantic model carries field "${key}", which is not part of BI-P030's model — ` +
`provider manifests are DERIVED on demand, never persisted`,
);
}
}
}
export function assertEngineNeutral(model: Omit<SemanticModelVersion, 'hash'>): void {
const serialized = JSON.stringify(model).toLowerCase();
for (const term of ENGINE_VOCABULARY) {
if (serialized.includes(term)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`semantic model "${model.model_id}" mentions "${term}" — BI-P030 requires the model to be ` +
`persisted separately from any implementation engine, so it can be replaced without ` +
`breaking canonical SIAX metric ids`,
);
}
}
}
/**
* The version hash. Covers everything that defines the model's MEANING;
* `valid_from` and `status` are excluded because activating a model does not
* change what it says.
*/
export function semanticModelHash(
model: Omit<SemanticModelVersion, 'hash' | 'valid_from' | 'status'>,
): string {
const canonical = JSON.stringify([
model.model_id,
model.version,
model.tenant_id,
[...model.datasets].sort(),
[...model.relationships]
.map((r) => [r.from_dataset, r.from_field, r.to_dataset, r.to_field, r.kind])
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
[...model.metrics].map((m) => [m.id, m.version]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
[...model.dimensions].map((d) => [d.id, d.name, d.dataset_id, d.kind]).sort(),
]);
return crypto.createHash('sha256').update(canonical).digest('hex');
}
export interface SemanticModelStore {
put(model: SemanticModelVersion): Promise<void>;
get(tenantId: string, modelId: string, version: number): Promise<SemanticModelVersion | undefined>;
active(tenantId: string, modelId: string): Promise<SemanticModelVersion | undefined>;
versions(tenantId: string, modelId: string): Promise<SemanticModelVersion[]>;
}
export class InMemorySemanticModelStore implements SemanticModelStore {
private readonly rows = new Map<string, SemanticModelVersion>();
private key(t: string, m: string, v: number): string {
return `${t}::${m}::${v}`;
}
async put(model: SemanticModelVersion): Promise<void> {
this.rows.set(this.key(model.tenant_id, model.model_id, model.version), model);
}
async get(t: string, m: string, v: number): Promise<SemanticModelVersion | undefined> {
return this.rows.get(this.key(t, m, v));
}
async versions(t: string, m: string): Promise<SemanticModelVersion[]> {
return [...this.rows.values()]
.filter((r) => r.tenant_id === t && r.model_id === m)
.sort((a, b) => a.version - b.version);
}
async active(t: string, m: string): Promise<SemanticModelVersion | undefined> {
return (await this.versions(t, m)).find((r) => r.status === 'active');
}
}
export class SemanticModelRegistry {
constructor(private readonly store: SemanticModelStore) {}
/**
* Publish a new version. Versions are IMMUTABLE — re-publishing an existing
* (model, version) is a CONFLICT, not an update, because a dashboard pinned
* to version 7 must mean the same thing tomorrow.
*/
async publish(input: Omit<SemanticModelVersion, 'hash'>): Promise<SemanticModelVersion> {
if (!input.tenant_id?.trim()) {
throw new SiaxError(
'UNAUTHENTICATED',
'0pt.analytics.semantic',
'a semantic model requires a verified tenant',
);
}
if (input.version < 1 || !Number.isInteger(input.version)) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.semantic', 'version must be a positive integer');
}
assertOnlySemanticModelFields(input);
assertEngineNeutral(input);
this.assertReferentialIntegrity(input);
const existing = await this.store.get(input.tenant_id, input.model_id, input.version);
if (existing) {
throw new SiaxError(
'CONFLICT',
'0pt.analytics.semantic',
`semantic model ${input.model_id} v${input.version} already exists and is immutable`,
);
}
const model: SemanticModelVersion = { ...input, hash: semanticModelHash(input) };
await this.store.put(model);
return model;
}
/** Activate a version, superseding the previous active one. */
async activate(
tenantId: string,
modelId: string,
version: number,
at: string,
): Promise<SemanticModelVersion> {
const target = await this.store.get(tenantId, modelId, version);
if (!target)
throw new SiaxError('NOT_FOUND', '0pt.analytics.semantic', 'semantic model version not found');
if (target.status === 'retired') {
throw new SiaxError('CONFLICT', '0pt.analytics.semantic', 'a retired version cannot be re-activated');
}
const current = await this.store.active(tenantId, modelId);
if (current && current.version !== version) {
await this.store.put({ ...current, status: 'superseded' });
}
const activated = { ...target, status: 'active' as const, valid_from: at };
await this.store.put(activated);
return activated;
}
/**
* BI-P030's DoD, as a query: the canonical metric ids a model exposes.
* The engine-parity test asserts this set is identical before and after a
* provider swap.
*/
async canonicalMetricIds(tenantId: string, modelId: string, version: number): Promise<string[]> {
const model = await this.store.get(tenantId, modelId, version);
if (!model)
throw new SiaxError('NOT_FOUND', '0pt.analytics.semantic', 'semantic model version not found');
return model.metrics.map((m) => m.id).sort();
}
/**
* Every dimension and dataset a metric names must exist in the model.
*
* A model that passes validation while referencing a dimension nobody
* defined produces a metric that fails at query time, per tenant, in
* production — the worst place to find out.
*/
private assertReferentialIntegrity(model: Omit<SemanticModelVersion, 'hash'>): void {
const datasets = new Set(model.datasets);
const dimensionNames = new Set(model.dimensions.map((d) => d.name));
const timeDimensions = new Set(model.dimensions.filter((d) => d.kind === 'time').map((d) => d.name));
for (const d of model.dimensions) {
if (!datasets.has(d.dataset_id)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`dimension "${d.name}" belongs to dataset "${d.dataset_id}", which the model does not include`,
);
}
}
for (const r of model.relationships) {
for (const ds of [r.from_dataset, r.to_dataset]) {
if (!datasets.has(ds)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`relationship references dataset "${ds}", which the model does not include`,
);
}
}
}
const seenIds = new Set<string>();
for (const m of model.metrics) {
if (seenIds.has(m.id)) {
throw new SiaxError(
'CONFLICT',
'0pt.analytics.semantic',
`metric id "${m.id}" appears twice in the model`,
);
}
seenIds.add(m.id);
for (const dim of m.dimensions) {
if (!dimensionNames.has(dim)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`metric "${m.name}" names dimension "${dim}", which the model does not define`,
);
}
}
if (!timeDimensions.has(m.timeDimension)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.semantic',
`metric "${m.name}" names time dimension "${m.timeDimension}", which the model does not define as a time dimension`,
);
}
}
}
}

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