On this page
- Status: Accepted. Batches D1a/D1b (2026-09-03), commits
b393b097,69bca3da. - Owners: Platform (site programme).
- Extends: ADR 0038, ADR 0039.
- Related: the numeric Rule DSL (
packages/metrics/src/playbook-rules.ts) and the closed transform enum (packages/connectors/core/src/mapping/apply.ts) — the two precedents this design follows rather than a free-text formula parser.
Context#
A tenant's derived measures (Total Employment Cost, TOR, ROI/Employee, variance ACTUAL - PLAN) need a formula language an org admin can define without shipping code, that a machine can validate for correctness (cycles, unit mismatch, an illegal stock reduction — ADR 0039 D2) before it ever runs, and that computes server-side only — nothing renders a number the browser derived.
Decisions#
D1 — A closed discriminated union, not a formula parser
datasetFieldExprSchema (packages/metrics/src/dataset-expr.ts), a Zod discriminated union on
kind. Twelve nodes, each serving one class of derived measure from the HR digest and the AI Data
Dictionary contract:
| node | shape | serves |
|---|---|---|
stored |
{agg, field, where?} |
Hires, OT Hours, Staff Cost |
sum_ |
{measures[]} |
Total Employment Cost |
delta |
{a, b} |
Variance ACTUAL - PLAN |
ratio |
{numerator, denominator, unit, minBase} |
TOR, ROI/Employee |
period_ |
{measure, over} |
Average Active HC = 159.71 |
endpoint_ |
{measure, from, to} |
contractual YTD average headcount (ADR 0039 D3) |
period_ |
{measure} |
Active HC at the snapshot month = 163 |
period_ |
{measure, offset} |
MoM / YoY |
axis_ |
{measure, axis, value} |
the PLAN leg of a variance |
classify |
{input, rules[], else} |
Salary Range Status (8 states) |
pending_ |
{owner, note} |
a measure the customer has not defined yet |
pending_ |
{owner, note} |
a measure blocked on a source that does not exist |
Every node compiles to SQL over the rollup and evaluates server-side — the existing rule, guarded by
kpi-headline-vs-rows-reconciliation.py and fabricated-multiplier-kpis.py, extended to this
family.
D2 — Save-time validator: references, cycles, reduction rule, filter/grain propagation
validateDatasetFieldExpr runs at save (never at read) and checks:
- References resolve to a real field in the same dataset (or a linked one via
org_dataset_links). - No cycles in the dependency graph a
sum_of/delta/rationode forms over other derived fields. - The stock/flow reduction rule (ADR 0039 D2):
sum/sum_ofnever reaches astock-temporality field, direct or indirect. applicable_filtersintersection: a derived field's applicable filters are the intersection of its inputs' — a ratio of a company-grain measure and a department-grain measure is company-grain, never silently the wider set.grain_scopeunion propagation and unit inference (VND stays VND, a ratio of two VND measures is dimensionless) so a schema author cannot declare an internally inconsistent field.
D3 — The rollup evaluator: a pure planner, integer-scale arithmetic
packages/metrics/src/dataset-rollup.ts — a pure planner from org_dataset_records to
agg_org_dataset_period, one pass per expression node, honouring all seven availability states (ADR
0039 D6) and integer-scale arithmetic throughout (no floats reach the database — money is bigint VND,
every non-money fraction is a scaled integer with a declared scale, per §2). Cross-dataset link
rollup (ROI = revenue / headcount over two datasets) goes through org_dataset_links. Tested against
a synthetic HR scenario distinguishing period_end vs period_average vs endpoint_average
headcount, hires, TOR, and OT.
D4 — Materialisation at ingest/rollup, never at read; backfill on redefinition
An expression is evaluated into org_dataset_record_measures/agg_org_dataset_period at
ingest/rollup time — never recomputed in the browser or in a read-time query. Redefining a field
(D4 of ADR 0038: confirm/rename/reject through orgDatasets.decideFields) writes schema_version
N+1, archives the old definition in the same transaction, and enqueues a per-brand backfill job
(dataset.backfill, worker queue dataset) that recomputes the rollup under the new definition — one
dataset at a time, idempotent, RLS-pinned, dead-lettered on permanent failure. The binding cache folds
the dataset's schema_version into its key (ADR 0044) so a shape change invalidates every cached read
durably, not just after a TTL.
D5 — Worker queue: dataset.rollup.refresh and dataset.backfill
Both jobs go through the transactional outbox, are idempotent, and classify permanent vs transient
failure (dead-letter on permanent). dataset.rollup.refresh runs after an ordinary ingest; dataset.backfill
runs only after a confirmed redefinition (D4).
Consequences#
- A client's derived measure is reviewable as data: the expression, its validated references, and its declared grain/filters/temporality are all in one row, never a formula buried in a per-client branch.
- A schema author cannot ship an internally inconsistent field — the validator refuses it at save, before it ever reaches a rollup.
- Redefining a measure is safe: the old definition's history is preserved (archived, not deleted) and every dependent number is recomputed by an auditable, idempotent job, not silently stale.
Implementation status (declared 2026-09-03)#
| Decision | Status | Evidence |
|---|---|---|
| D1 twelve-node closed union | Landed | dataset, packages/ (dataset-, HR fixture) |
| D2 save-time validator | Landed | validate; refs/cycles/reduction/filter/grain/unit checks all tested |
| D3 rollup evaluator | Landed | packages/, dataset- (synthetic HR scenario) |
| D4 materialise at ingest + backfill | Landed | org_/agg_ writes at promote time; dataset. job |
| D5 worker queue | Landed | apps/; queue dataset registered in job- |
Amendment — 2026-09-10: axis_pick pins an axis and composes with the caller's slice#
D3 shipped axis_pick as a pass-through: the evaluator returned
resolve(expr.measure, period, dimKey, valueKey) and never read expr.axis or expr.value. The
finance pack's opex_plan_axis therefore resolved opex_by_scenario at the CALLER's slice, which at
the dataset total row is the sum of all three unpivot legs, so
budget_variance = delta(opex, opex_plan_axis) was actual - (actual + plan + forecast) carrying
state: 'ok'. No org had the pack installed, so the defect was latent, not live.
- Decision (evaluation).
axis_pick(measure, axis, value)PINS the axis coordinate and resolvesmeasureat the CALLER's own slice, carrying the pin down to the record leaves. A pin on arecord_agg.unpivotdimension selects the leg; any other pin is a second filter on the same records, alongside the caller's own breakdown. Soopex_plan_axisread at(dim_key: 'cost_center', value_key: 'sales')is the plan leg RESTRICTED TO Sales — budget variance by cost centre is a real number, and the breakdown sums back to the headline (§51). This is possible because the evaluator resolves every slice from the raw records rather than by reading a cell back; the axis is consumed inside the expression, so the cell the field produces still carries one(dim_key, value_key)pair and the no-axis sentinel inscenario/version.valueis folded through the samenormalizeAliasFormthe promoter applies to every storedvalue_key, so a pack writingPlanselects theplanleg instead of nothing. - Decision (what is still refused). Two CONTRADICTIONS resolve
not_applicable_at_grain— one of ADR 0039 D6's named states, not a new one: a caller breaking down BY the picked axis at a different value (scenario=forecastasked of a field defined as the plan leg), and two picks on the same axis disagreeing (plan inside forecast). Neither is a capability gap; no records answer either. - Decision (propagation).
axis_pickderives the source'sapplicable_filtersMINUS the axis. The axis is consumed — a field that has already fixedscenario=planmay never offer ascenariofilter, or the card is offering to re-pick an axis that is gone — while every other dimension the source honours survives the pick, because the pin composes with it. A new validator issue,axis_not_on_measure, refuses at save time a pick whose axis is not among the source measure'sapplicable_filters: that pick would filter records on a dimension they do not carry, and asumover the empty result prints as a budget of zero. - Consequence for the finance pack.
finance-pnl.jsongoes to v2.opex_by_scenarioandopex_plan_axisnow declarecost_centeralongsideentity— the plan rows carry it, so the budget and cost-centre pages the pack already ships compute real per-cost-centre budgets and variances instead of resolving nothing.budget_variance/budget_variance_pctwere already declared correctly and are unchanged..dataset-pack-baseline.jsonis re-armed to v2 in the same change. - Gates.
packages/metrics/src/dataset-axis-pick.test.tsdrivesplanDatasetRollupwith the SHIPPED pack's own field definitions over a hand-summed record fixture whose entity and cost-centre partitions deliberately differ (plan 515m, forecast 280m, variance 25m = 485 bp; by cost centre -10m and +35m; by entity +5m and +20m; both breakdowns sum to the headline), and pins both axes, a two-level pick, and both refusals.packages/metrics/src/dataset-expr-evaluator-coverage.test.tsis the class-of-bug guard: every property of every node in the closed union that carries a CHOICE must be read by that node's evaluator branch (or by a helper it calls), with a written-reason ledger for the few that are deliberately not evaluated. Both run inpnpm test, hence in pre-push andci.yml.