From cbb062a68c73f4f7d2210260e6a67f64e01a95d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:30:59 +0000 Subject: [PATCH 1/6] Carry what each build declares in the timeline, for the page's step card and marks The page (PR 2 of #224) opens a card on a step with the facts of its two builds, and marks a change of build engine on the time axis. Those facts are in the points, and `timeline.json` copied none of them, so the page would have read every point on each request. - `buildTimeline` adds a `declared` block to each build: the build its point was fetched through, its built-at time, the model and core it was built with, the range of models it declares, its Microcosm repository and commit, its target set's digest and size, the target registry version and the household weight year. It is null where the panel holds no point. Two builds that publish one file carry the same facts. - The key is optional in `timeline.schema.json`, as the schema's rule for a key added later says: a timeline written before this commit stays valid, and the next finalize rewrites it. No id and no stored point changes. - The Python `TimelineBuild` type, the generated TypeScript types and both countries' timeline fixtures follow. Co-Authored-By: Claude Opus 5.5 --- docs/release-history.md | 9 +- .../microcosm/release-history-documents.ts | 34 ++++++++ .../microcosm/release-history-store.test.ts | 66 +++++++++++++++ .../lib/microcosm/release-history-store.ts | 30 ++++++- release_history/schemas/timeline.schema.json | 77 +++++++++++++++++ .../src/release_history/documents.py | 19 +++++ .../tests/fixtures/uk/timeline.json | 83 +++++++++++++++++-- .../tests/fixtures/us/timeline.json | 66 +++++++++++++-- 8 files changed, 371 insertions(+), 13 deletions(-) diff --git a/docs/release-history.md b/docs/release-history.md index ceba157e..b7d0d823 100644 --- a/docs/release-history.md +++ b/docs/release-history.md @@ -263,8 +263,13 @@ served page. `timeline.json` holds, for each build of the series record in publish order, its file, state and point, whether the reference model is inside the range the -build declares, and the file's columns the model does not define (it drops -them); and for each output and period, one value per +build declares, the file's columns the model does not define (it drops +them), and what the build its point was fetched through declares (`declared`: +its built-at time, the model and core it was built with, the range of models +it declares, its Microcosm repository and commit, its target set's digest and +size, the target registry version and the household weight year; null where +the panel holds no point, and absent from a timeline written before the page +needed it); and for each output and period, one value per build, the change from the previous build on the series when both hold the cell (relative for money and counts, in percentage points for rates), and the output's official reference. A withdrawn build is listed but is never a diff --git a/frontend/lib/microcosm/release-history-documents.ts b/frontend/lib/microcosm/release-history-documents.ts index f7eec2fc..6f228f3c 100644 --- a/frontend/lib/microcosm/release-history-documents.ts +++ b/frontend/lib/microcosm/release-history-documents.ts @@ -397,6 +397,40 @@ export interface Timeline { * Columns of the file the reference model does not define; null where the panel holds no point or the point is a gap. */ unknownColumns: null | string[]; + /** + * Added after the first timelines were written, so not required: what the build the panel's point was fetched through declares about its file, copied from the point (`fetched_from.declared`). Null where the panel holds no point. + */ + declared?: null | { + /** + * The build the point was fetched through: another build than this one where two builds publish the same file. + */ + fetchedThrough: string; + builtAt: string | null; + /** + * Copied as the upstream document holds it; its shape is that document's. + */ + builtWithModel: unknown; + /** + * Copied as the upstream document holds it; its shape is that document's. + */ + builtWithCore: unknown; + /** + * Copied as the upstream document holds it; its shape is that document's. + */ + compatibleModels: unknown; + codeRepository: string | null; + codeCommit: string | null; + targetSurfaceSha256: string | null; + nTargets: number | null; + /** + * Copied as the upstream document holds it; its shape is that document's. + */ + targetRegistryVersion: unknown; + /** + * Copied as the upstream document holds it; its shape is that document's. + */ + householdWeightYear: unknown; + }; }[]; outputs: { output: string; diff --git a/frontend/lib/microcosm/release-history-store.test.ts b/frontend/lib/microcosm/release-history-store.test.ts index 6c636fd6..01b84613 100644 --- a/frontend/lib/microcosm/release-history-store.test.ts +++ b/frontend/lib/microcosm/release-history-store.test.ts @@ -626,3 +626,69 @@ test("the timeline carries each point's model compatibility and the columns the [null, null], ]); }); + +test("the timeline carries what each build's point declares, for the page's step card and marks", () => { + // b1 and b2 publish one file: both carry the facts of the build its point was fetched through. + const listed = series([build("b1", file(1)), build("b2", file(1)), build("b3", file(3)), build("b4", file(4))]); + const withFacts: MeasurementDocument = { + ...point(file(1), [cell(1)]), + fetched_from: { + ...point(file(1)).fetched_from, + build_id: `${LINE}/b1`, + declared: { + ...point(file(1)).fetched_from.declared, + built_at: "2026-11-01T03:00:00+00:00", + built_with_model: { name: "policyengine-zz", version: "1.2.0" }, + built_with_core: { name: "policyengine-core", version: "3.33.3" }, + compatible_models: [{ name: "policyengine-zz", specifier: "==1.2.0" }], + build_provenance: { + code_repository: "PolicyEngine/microcosm", + code_commit: "e".repeat(40), + attempt_id: "b1", + target_surface_sha256: "7".repeat(64), + n_targets: 1214, + target_registry_version: "2026.11", + household_weight_year: 2024, + runtime: { seconds: 1 }, + }, + }, + }, + }; + // A build with no build manifest declares no provenance: its facts are null, never absent. + const withoutProvenance = point(file(3), [cell(2)]); + const timeline = timelineOf(listed, [withFacts, withoutProvenance]); + const facts = { + fetchedThrough: `${LINE}/b1`, + builtAt: "2026-11-01T03:00:00+00:00", + builtWithModel: { name: "policyengine-zz", version: "1.2.0" }, + builtWithCore: { name: "policyengine-core", version: "3.33.3" }, + compatibleModels: [{ name: "policyengine-zz", specifier: "==1.2.0" }], + codeRepository: "PolicyEngine/microcosm", + codeCommit: "e".repeat(40), + targetSurfaceSha256: "7".repeat(64), + nTargets: 1214, + targetRegistryVersion: "2026.11", + householdWeightYear: 2024, + }; + expect(timeline.builds.map((timelineBuild) => timelineBuild.declared)).toEqual([ + facts, + facts, + { + fetchedThrough: "test-release/test-build", + builtAt: null, + builtWithModel: null, + builtWithCore: null, + compatibleModels: null, + codeRepository: null, + codeCommit: null, + targetSurfaceSha256: null, + nTargets: null, + targetRegistryVersion: null, + householdWeightYear: null, + }, + // No point on this panel: nothing declared. + null, + ]); + // The build's own runtime record and attempt id stay in the point. + expect(JSON.stringify(timeline)).not.toContain("attempt_id"); +}); diff --git a/frontend/lib/microcosm/release-history-store.ts b/frontend/lib/microcosm/release-history-store.ts index 2dd09ebd..24ea8088 100644 --- a/frontend/lib/microcosm/release-history-store.ts +++ b/frontend/lib/microcosm/release-history-store.ts @@ -745,10 +745,15 @@ export interface ReferencesLock { * `withdrawn`: listed, but never a neighbour, so no step starts or ends at it. `sameFileAs`: the * earliest earlier build that publishes the same file. `state`: the file's state on this panel, * `missing` when it was never run. `status`: the stored point's (ok, partial or refused). - * `reason`: a gap's refusal reason, or the last error of a failed or retrying file. + * `reason`: a gap's refusal reason, or the last error of a failed or retrying file. `declared`: + * what the build the point was fetched through declares about its file (the model and core it + * was built with, its Microcosm commit, its target set), for the page's step card and marks. */ export type TimelineBuild = Timeline["builds"][number]; +/** A build's declared facts on the timeline; a timeline written before they were carried has none. */ +export type TimelineDeclared = NonNullable; + /** One output in one period, with a value per build in the order of the timeline's `builds`. */ export type TimelineOutput = Timeline["outputs"][number]; @@ -788,6 +793,28 @@ function stateOfStored(document: MeasurementDocument): PointState { return document.status === "refused" ? "gap" : "measured"; } +/** + * What the build a point was fetched through declares about its file: a copy of the point's + * facts, so the page reads a step's two builds from the timeline alone. + */ +function declaredFacts(point: MeasurementDocument): TimelineDeclared { + const declared = point.fetched_from.declared; + const provenance = declared.build_provenance; + return { + fetchedThrough: point.fetched_from.build_id, + builtAt: declared.built_at, + builtWithModel: declared.built_with_model ?? null, + builtWithCore: declared.built_with_core ?? null, + compatibleModels: declared.compatible_models ?? null, + codeRepository: provenance?.code_repository ?? null, + codeCommit: provenance?.code_commit ?? null, + targetSurfaceSha256: provenance?.target_surface_sha256 ?? null, + nTargets: provenance?.n_targets ?? null, + targetRegistryVersion: provenance?.target_registry_version ?? null, + householdWeightYear: provenance?.household_weight_year ?? null, + }; +} + /** * Each listed build with its file's state on the panel: the stored point's when there is one, * else the manifest's (retrying or failed), else missing. @@ -819,6 +846,7 @@ function timelineBuilds( reason: point ? point.reason : state?.lastError ?? null, referenceModelCompatibility: point?.fetched_from?.declared?.reference_model_compatibility ?? null, unknownColumns: point?.data?.unknown_columns ?? null, + declared: point ? declaredFacts(point) : null, }; }); } diff --git a/release_history/schemas/timeline.schema.json b/release_history/schemas/timeline.schema.json index 6ac458e8..9f789ee4 100644 --- a/release_history/schemas/timeline.schema.json +++ b/release_history/schemas/timeline.schema.json @@ -210,6 +210,83 @@ } ], "description": "Columns of the file the reference model does not define; null where the panel holds no point or the point is a gap." + }, + "declared": { + "description": "Added after the first timelines were written, so not required: what the build the panel's point was fetched through declares about its file, copied from the point (`fetched_from.declared`). Null where the panel holds no point.", + "anyOf": [ + { + "type": "null" + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "fetchedThrough", + "builtAt", + "builtWithModel", + "builtWithCore", + "compatibleModels", + "codeRepository", + "codeCommit", + "targetSurfaceSha256", + "nTargets", + "targetRegistryVersion", + "householdWeightYear" + ], + "properties": { + "fetchedThrough": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$", + "description": "The build the point was fetched through: another build than this one where two builds publish the same file." + }, + "builtAt": { + "type": [ + "string", + "null" + ] + }, + "builtWithModel": { + "description": "Copied as the upstream document holds it; its shape is that document's." + }, + "builtWithCore": { + "description": "Copied as the upstream document holds it; its shape is that document's." + }, + "compatibleModels": { + "description": "Copied as the upstream document holds it; its shape is that document's." + }, + "codeRepository": { + "type": [ + "string", + "null" + ] + }, + "codeCommit": { + "type": [ + "string", + "null" + ] + }, + "targetSurfaceSha256": { + "type": [ + "string", + "null" + ] + }, + "nTargets": { + "type": [ + "number", + "null" + ] + }, + "targetRegistryVersion": { + "description": "Copied as the upstream document holds it; its shape is that document's." + }, + "householdWeightYear": { + "description": "Copied as the upstream document holds it; its shape is that document's." + } + } + } + ] } } } diff --git a/release_history/src/release_history/documents.py b/release_history/src/release_history/documents.py index 24f642c9..d3998a90 100644 --- a/release_history/src/release_history/documents.py +++ b/release_history/src/release_history/documents.py @@ -359,6 +359,23 @@ class TimelineLabel(TypedDict): source: JsonValue +class TimelineDeclared(TypedDict): + """What the build a point was fetched through declares about its file, as the timeline + copies it from the point's `fetched_from.declared`.""" + + fetchedThrough: str # noqa: N815 + builtAt: str | None # noqa: N815 + builtWithModel: JsonValue # noqa: N815 + builtWithCore: JsonValue # noqa: N815 + compatibleModels: JsonValue # noqa: N815 + codeRepository: str | None # noqa: N815 + codeCommit: str | None # noqa: N815 + targetSurfaceSha256: str | None # noqa: N815 + nTargets: int | None # noqa: N815 + targetRegistryVersion: JsonValue # noqa: N815 + householdWeightYear: JsonValue # noqa: N815 + + class TimelineBuild(TypedDict): buildId: str # noqa: N815 release: str @@ -374,6 +391,8 @@ class TimelineBuild(TypedDict): reason: str | None referenceModelCompatibility: Compatibility | None # noqa: N815 unknownColumns: list[str] | None # noqa: N815 + # Added after the first timelines were written, so a stored timeline may lack it. + declared: NotRequired[TimelineDeclared | None] class TimelineReference(TypedDict): diff --git a/release_history/tests/fixtures/uk/timeline.json b/release_history/tests/fixtures/uk/timeline.json index 8e3097af..986b35b1 100644 --- a/release_history/tests/fixtures/uk/timeline.json +++ b/release_history/tests/fixtures/uk/timeline.json @@ -94,7 +94,25 @@ "status": "ok", "reason": null, "referenceModelCompatibility": "inside", - "unknownColumns": [] + "unknownColumns": [], + "declared": { + "fetchedThrough": "microcosm-uk-2024-25-national/synthetic-build-1", + "builtAt": "2026-11-01T00:00:00+00:00", + "builtWithModel": null, + "builtWithCore": null, + "compatibleModels": [ + { + "name": "policyengine-uk", + "specifier": ">=1" + } + ], + "codeRepository": null, + "codeCommit": null, + "targetSurfaceSha256": null, + "nTargets": null, + "targetRegistryVersion": null, + "householdWeightYear": null + } }, { "buildId": "microcosm-uk-2024-25-national/synthetic-build-2", @@ -110,7 +128,25 @@ "status": "ok", "reason": null, "referenceModelCompatibility": "inside", - "unknownColumns": [] + "unknownColumns": [], + "declared": { + "fetchedThrough": "microcosm-uk-2024-25-national/synthetic-build-1", + "builtAt": "2026-11-01T00:00:00+00:00", + "builtWithModel": null, + "builtWithCore": null, + "compatibleModels": [ + { + "name": "policyengine-uk", + "specifier": ">=1" + } + ], + "codeRepository": null, + "codeCommit": null, + "targetSurfaceSha256": null, + "nTargets": null, + "targetRegistryVersion": null, + "householdWeightYear": null + } }, { "buildId": "microcosm-uk-2024-25-national/synthetic-build-3", @@ -126,7 +162,25 @@ "status": "ok", "reason": null, "referenceModelCompatibility": "inside", - "unknownColumns": [] + "unknownColumns": [], + "declared": { + "fetchedThrough": "microcosm-uk-2024-25-national/synthetic-build-3", + "builtAt": "2026-11-01T00:00:00+00:00", + "builtWithModel": null, + "builtWithCore": null, + "compatibleModels": [ + { + "name": "policyengine-uk", + "specifier": ">=1" + } + ], + "codeRepository": null, + "codeCommit": null, + "targetSurfaceSha256": null, + "nTargets": null, + "targetRegistryVersion": null, + "householdWeightYear": null + } }, { "buildId": "microcosm-uk-2024-25-national/synthetic-build-4", @@ -142,7 +196,8 @@ "status": null, "reason": null, "referenceModelCompatibility": null, - "unknownColumns": null + "unknownColumns": null, + "declared": null }, { "buildId": "microcosm-uk-2024-25-national/synthetic-build-5", @@ -158,7 +213,25 @@ "status": "refused", "reason": "disclosure_source_ids_missing", "referenceModelCompatibility": "inside", - "unknownColumns": null + "unknownColumns": null, + "declared": { + "fetchedThrough": "microcosm-uk-2024-25-national/synthetic-build-5", + "builtAt": "2026-11-01T00:00:00+00:00", + "builtWithModel": null, + "builtWithCore": null, + "compatibleModels": [ + { + "name": "policyengine-uk", + "specifier": ">=1" + } + ], + "codeRepository": null, + "codeCommit": null, + "targetSurfaceSha256": null, + "nTargets": null, + "targetRegistryVersion": null, + "householdWeightYear": null + } } ], "outputs": [ diff --git a/release_history/tests/fixtures/us/timeline.json b/release_history/tests/fixtures/us/timeline.json index 4323a37e..ca827e85 100644 --- a/release_history/tests/fixtures/us/timeline.json +++ b/release_history/tests/fixtures/us/timeline.json @@ -49,7 +49,25 @@ "status": "ok", "reason": null, "referenceModelCompatibility": "inside", - "unknownColumns": [] + "unknownColumns": [], + "declared": { + "fetchedThrough": "microcosm-us-2024-national/synthetic-build-1", + "builtAt": "2026-11-01T00:00:00+00:00", + "builtWithModel": null, + "builtWithCore": null, + "compatibleModels": [ + { + "name": "policyengine-us", + "specifier": ">=1" + } + ], + "codeRepository": null, + "codeCommit": null, + "targetSurfaceSha256": null, + "nTargets": null, + "targetRegistryVersion": null, + "householdWeightYear": null + } }, { "buildId": "microcosm-us-2024-national/synthetic-build-2", @@ -65,7 +83,25 @@ "status": "ok", "reason": null, "referenceModelCompatibility": "inside", - "unknownColumns": [] + "unknownColumns": [], + "declared": { + "fetchedThrough": "microcosm-us-2024-national/synthetic-build-1", + "builtAt": "2026-11-01T00:00:00+00:00", + "builtWithModel": null, + "builtWithCore": null, + "compatibleModels": [ + { + "name": "policyengine-us", + "specifier": ">=1" + } + ], + "codeRepository": null, + "codeCommit": null, + "targetSurfaceSha256": null, + "nTargets": null, + "targetRegistryVersion": null, + "householdWeightYear": null + } }, { "buildId": "microcosm-us-2024-national/synthetic-build-3", @@ -81,7 +117,25 @@ "status": "ok", "reason": null, "referenceModelCompatibility": "inside", - "unknownColumns": [] + "unknownColumns": [], + "declared": { + "fetchedThrough": "microcosm-us-2024-national/synthetic-build-3", + "builtAt": "2026-11-01T00:00:00+00:00", + "builtWithModel": null, + "builtWithCore": null, + "compatibleModels": [ + { + "name": "policyengine-us", + "specifier": ">=1" + } + ], + "codeRepository": null, + "codeCommit": null, + "targetSurfaceSha256": null, + "nTargets": null, + "targetRegistryVersion": null, + "householdWeightYear": null + } }, { "buildId": "microcosm-us-2024-national/synthetic-build-4", @@ -97,7 +151,8 @@ "status": null, "reason": null, "referenceModelCompatibility": null, - "unknownColumns": null + "unknownColumns": null, + "declared": null }, { "buildId": "microcosm-us-2024-national/synthetic-build-5", @@ -113,7 +168,8 @@ "status": null, "reason": null, "referenceModelCompatibility": null, - "unknownColumns": null + "unknownColumns": null, + "declared": null } ], "outputs": [ From 890ef4487c868746ad437c109d9a1bb06ba5a210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:36:36 +0000 Subject: [PATCH 2/6] Add the release history page's read routes: the manifest summary, one panel's timeline, and its CSV The page (PR 2 of #224) reads the store PR 1 writes. Three routes read it on the server, through the store module, so the browser never gets a Blob URL or token. - `GET /api/microcosm/release-history?country=`: the country's panels, one per reference engine that holds a measured file, with engine, coverage and whether the definition equals the default panel's, and the panel the page opens. That is the served panel: after an engine bump the pinned panel fills first and the page moves to it once it is complete. A country with no measured file answers `available: false`. The per-file entries stay in the manifest. - `GET /api/microcosm/release-history/timeline?country=&panel=`: one panel's summary, its whole `timeline.json`, and what its `panel.json` says about presenting its outputs (currency, period labels, the baseline items and reforms in spec order, the disclosure policy). Without `panel` it serves the default one. Only a panel the country's manifest entry lists is read, and a stored timeline of another panel or format is a 502. - `GET /api/microcosm/release-history/export?country=&panel=`: the same timeline as a CSV download with the columns of the producer's `export` command; a test reads the column list from the Python file. A withheld value is an empty cell. - A timeline grows with every build and a function's response is capped, so the timeline and the CSV are sent gzipped to a client that accepts it. - Every route requires a country and answers an unknown code with the shared not-configured response before reading; all three join the every-route test. - `RELEASE_HISTORY_LOCAL_DIR` names a local folder in the store's layout (a pulled panel, or a synthetic one) for the routes to read instead of Blob. It is read-only, never leaves the folder, and is unset on a hosted deployment. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/country-not-configured.test.ts | 4 + .../release-history/export/route.test.ts | 42 +++ .../microcosm/release-history/export/route.ts | 43 +++ .../microcosm/release-history/route.test.ts | 96 ++++++ .../api/microcosm/release-history/route.ts | 36 +++ .../release-history/timeline/route.test.ts | 122 ++++++++ .../release-history/timeline/route.ts | 41 +++ .../lib/microcosm/calibration-tree-http.ts | 2 +- .../microcosm/release-history-export.test.ts | 94 ++++++ .../lib/microcosm/release-history-export.ts | 101 +++++++ .../lib/microcosm/release-history-http.ts | 84 ++++++ .../lib/microcosm/release-history-read.ts | 92 ++++++ .../microcosm/release-history-source.test.ts | 52 ++++ .../lib/microcosm/release-history-source.ts | 91 ++++++ .../microcosm/release-history-summary.test.ts | 276 ++++++++++++++++++ .../lib/microcosm/release-history-summary.ts | 222 ++++++++++++++ .../release-history-fixture-store.ts | 97 ++++++ 17 files changed, 1494 insertions(+), 1 deletion(-) create mode 100644 frontend/app/api/microcosm/release-history/export/route.test.ts create mode 100644 frontend/app/api/microcosm/release-history/export/route.ts create mode 100644 frontend/app/api/microcosm/release-history/route.test.ts create mode 100644 frontend/app/api/microcosm/release-history/route.ts create mode 100644 frontend/app/api/microcosm/release-history/timeline/route.test.ts create mode 100644 frontend/app/api/microcosm/release-history/timeline/route.ts create mode 100644 frontend/lib/microcosm/release-history-export.test.ts create mode 100644 frontend/lib/microcosm/release-history-export.ts create mode 100644 frontend/lib/microcosm/release-history-http.ts create mode 100644 frontend/lib/microcosm/release-history-read.ts create mode 100644 frontend/lib/microcosm/release-history-source.test.ts create mode 100644 frontend/lib/microcosm/release-history-source.ts create mode 100644 frontend/lib/microcosm/release-history-summary.test.ts create mode 100644 frontend/lib/microcosm/release-history-summary.ts create mode 100644 frontend/lib/microcosm/test-support/release-history-fixture-store.ts diff --git a/frontend/app/api/microcosm/country-not-configured.test.ts b/frontend/app/api/microcosm/country-not-configured.test.ts index 7462f463..6d9397df 100644 --- a/frontend/app/api/microcosm/country-not-configured.test.ts +++ b/frontend/app/api/microcosm/country-not-configured.test.ts @@ -18,6 +18,9 @@ const COUNTRY_ROUTES: Record Promise> = { "microcosm/comparison-tree/target-detail": () => import("./comparison-tree/target-detail/route"), "microcosm/cross-dataset": () => import("./cross-dataset/route"), + "microcosm/release-history": () => import("./release-history/route"), + "microcosm/release-history/export": () => import("./release-history/export/route"), + "microcosm/release-history/timeline": () => import("./release-history/timeline/route"), "microcosm/releases": () => import("./releases/route"), "microcosm/staging/compare": () => import("./staging/compare/route"), "microcosm/staging/run": () => import("./staging/run/route"), @@ -40,6 +43,7 @@ const OTHER_PARAMETERS = { a: "a".repeat(64), b: "b".repeat(64), build: "c".repeat(64), + panel: "d".repeat(64), release: "microcosm-us-2024", part: "index", mode: "reported", diff --git a/frontend/app/api/microcosm/release-history/export/route.test.ts b/frontend/app/api/microcosm/release-history/export/route.test.ts new file mode 100644 index 00000000..f79a5700 --- /dev/null +++ b/frontend/app/api/microcosm/release-history/export/route.test.ts @@ -0,0 +1,42 @@ +import { expect, test } from "bun:test"; +import { gunzipSync } from "node:zlib"; + +import { timelineCsv } from "@/lib/microcosm/release-history-export"; +import type { ReleaseHistoryStore } from "@/lib/microcosm/release-history-store"; +import { fixtureStore } from "@/lib/microcosm/test-support/release-history-fixture-store"; +import { createReleaseHistoryExportHandler } from "./route"; + +const URL_BASE = "https://dashboard.example/calibration/dashboard/api/microcosm/release-history/export"; + +function handler(store: ReleaseHistoryStore) { + return createReleaseHistoryExportHandler({ store: () => store }); +} + +test("the export is the panel's table as a CSV download named by country and panel", async () => { + const { store, fixtures } = await fixtureStore(); + const response = await handler(store)(new Request(`${URL_BASE}?country=uk`)); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("text/csv; charset=utf-8"); + expect(response.headers.get("content-disposition")).toBe( + `attachment; filename="release-history-uk-${fixtures.uk.panel.panel_id.slice(0, 12)}.csv"`, + ); + const text = await response.text(); + expect(text).toBe(timelineCsv(fixtures.uk.timeline)); + expect(text.startsWith("build_id,published_at,current,withdrawn,")).toBe(true); + + const compressed = await handler(store)( + new Request(`${URL_BASE}?country=us&panel=${fixtures.us.panel.panel_id}`, { headers: { "accept-encoding": "gzip" } }), + ); + expect(compressed.headers.get("content-encoding")).toBe("gzip"); + expect(gunzipSync(new Uint8Array(await compressed.arrayBuffer())).toString("utf8")) + .toBe(timelineCsv(fixtures.us.timeline)); +}); + +test("the export refuses what the timeline route refuses", async () => { + const { store } = await fixtureStore(["uk"]); + expect((await handler(store)(new Request(URL_BASE))).status).toBe(400); + expect((await handler(store)(new Request(`${URL_BASE}?country=zz`))).status).toBe(404); + expect((await handler(store)(new Request(`${URL_BASE}?country=uk&panel=nope`))).status).toBe(400); + expect((await handler(store)(new Request(`${URL_BASE}?country=uk&panel=${"0".repeat(64)}`))).status).toBe(404); + expect((await handler(store)(new Request(`${URL_BASE}?country=us`))).status).toBe(404); +}); diff --git a/frontend/app/api/microcosm/release-history/export/route.ts b/frontend/app/api/microcosm/release-history/export/route.ts new file mode 100644 index 00000000..1cc5541b --- /dev/null +++ b/frontend/app/api/microcosm/release-history/export/route.ts @@ -0,0 +1,43 @@ +import { requiredCountry } from "@/lib/api/request-country"; +import { timelineCsv, timelineCsvFileName } from "@/lib/microcosm/release-history-export"; +import { + compressedResponse, + DEFAULT_RELEASE_HISTORY_ROUTE_DEPENDENCIES, + panelProblemResponse, + readFailureResponse, + RELEASE_HISTORY_CACHE_HEADERS, + requestedPanel, + type ReleaseHistoryRouteDependencies, +} from "@/lib/microcosm/release-history-http"; +import { readPanelView } from "@/lib/microcosm/release-history-read"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +// A panel's timeline as a CSV download: the table `release-history export` writes, one row per +// build and output. It holds what the page shows and nothing more: a withheld value is an empty +// cell. +export function createReleaseHistoryExportHandler( + dependencies: ReleaseHistoryRouteDependencies = DEFAULT_RELEASE_HISTORY_ROUTE_DEPENDENCIES, +) { + return async function GET(request: Request) { + const params = new URL(request.url).searchParams; + const country = requiredCountry(params); + if (country instanceof Response) return country; + const panel = requestedPanel(params); + if (panel instanceof Response) return panel; + try { + const result = await readPanelView(dependencies.store(), country, panel); + if (result.kind !== "ok") return panelProblemResponse(result, country); + return compressedResponse(request, timelineCsv(result.view.timeline), { + ...RELEASE_HISTORY_CACHE_HEADERS, + "Content-Type": "text/csv; charset=utf-8", + "Content-Disposition": `attachment; filename="${timelineCsvFileName(country, result.view.panelId)}"`, + }); + } catch (error) { + return readFailureResponse(error); + } + }; +} + +export const GET = createReleaseHistoryExportHandler(); diff --git a/frontend/app/api/microcosm/release-history/route.test.ts b/frontend/app/api/microcosm/release-history/route.test.ts new file mode 100644 index 00000000..2fb446f1 --- /dev/null +++ b/frontend/app/api/microcosm/release-history/route.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from "bun:test"; + +import { + encodeDocument, + memoryStore, + RELEASE_HISTORY_MANIFEST_PATH, + type ReleaseHistoryStore, +} from "@/lib/microcosm/release-history-store"; +import type { ReleaseHistorySummary } from "@/lib/microcosm/release-history-summary"; +import { fixtureStore } from "@/lib/microcosm/test-support/release-history-fixture-store"; +import { createReleaseHistorySummaryHandler } from "./route"; + +const URL_BASE = "https://dashboard.example/calibration/dashboard/api/microcosm/release-history"; + +function handler(store: ReleaseHistoryStore) { + return createReleaseHistorySummaryHandler({ store: () => store }); +} + +test("the summary names a country's panels, their engines, and the panel the page opens", async () => { + const { store, fixtures } = await fixtureStore(); + const response = await handler(store)(new Request(`${URL_BASE}?country=uk`)); + expect(response.status).toBe(200); + const body = (await response.json()) as ReleaseHistorySummary; + const panelId = fixtures.uk.panel.panel_id; + expect(body).toMatchObject({ + country: "uk", + available: true, + defaultPanelId: panelId, + pinnedPanelId: panelId, + servedPanelId: panelId, + }); + expect(body.panels).toHaveLength(1); + expect(body.panels[0]).toMatchObject({ + panelId, + engine: { policyengine: "6.16.1", model: "policyengine-uk==1.0.0", core: "policyengine-core==3.33.3" }, + pinned: true, + served: true, + complete: true, + // Five listed builds; the withdrawn one is off the axis, and two builds share a file. + coverage: { builds: 4, files: 3, measured: 2, gap: 1, retrying: 0, failed: 0, missing: 0 }, + }); + expect(response.headers.get("cache-control")).toBe("public, max-age=0, must-revalidate"); + expect(response.headers.get("vercel-cdn-cache-control")).toContain("max-age=60"); + // The other country's panels are its own. + const us = (await (await handler(store)(new Request(`${URL_BASE}?country=us`))).json()) as ReleaseHistorySummary; + expect(us.defaultPanelId).toBe(fixtures.us.panel.panel_id); + expect(us.panels.map((panel) => panel.panelId)).toEqual([fixtures.us.panel.panel_id]); +}); + +test("a configured country with no stored history answers available: false", async () => { + const { store } = await fixtureStore(["uk"]); + for (const target of [store, memoryStore()]) { + const response = await handler(target)(new Request(`${URL_BASE}?country=us`)); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ country: "us", available: false, defaultPanelId: null, panels: [] }); + } +}); + +test("the summary needs a country, and refuses one the dashboard does not serve before reading", async () => { + let reads = 0; + const counting: ReleaseHistoryStore = { + ...memoryStore(), + read: async () => { + reads += 1; + return null; + }, + }; + expect((await handler(counting)(new Request(URL_BASE))).status).toBe(400); + const response = await handler(counting)(new Request(`${URL_BASE}?country=zz`)); + expect(response.status).toBe(404); + expect(await response.json()).toMatchObject({ error: "country_not_configured", requested_country: "zz" }); + expect(reads).toBe(0); +}); + +test("a store that cannot be read, or a manifest this code does not read, is a 503 that says no more", async () => { + const failing: ReleaseHistoryStore = { + ...memoryStore(), + read: async () => { + throw new Error("token vercel_blob_rw_secret refused"); + }, + }; + const unreadable = memoryStore(); + await unreadable.write(RELEASE_HISTORY_MANIFEST_PATH, encodeDocument({ formatVersion: 2, countries: {} }), "create", false); + const logged = console.error; + console.error = () => {}; + try { + for (const store of [failing, unreadable]) { + const response = await handler(store)(new Request(`${URL_BASE}?country=uk`)); + expect(response.status).toBe(503); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(await response.json()).toEqual({ detail: "The release history could not be read." }); + } + } finally { + console.error = logged; + } +}); diff --git a/frontend/app/api/microcosm/release-history/route.ts b/frontend/app/api/microcosm/release-history/route.ts new file mode 100644 index 00000000..70e8409d --- /dev/null +++ b/frontend/app/api/microcosm/release-history/route.ts @@ -0,0 +1,36 @@ +import { NextResponse } from "next/server"; + +import { requiredCountry } from "@/lib/api/request-country"; +import { + DEFAULT_RELEASE_HISTORY_ROUTE_DEPENDENCIES, + readFailureResponse, + RELEASE_HISTORY_CACHE_HEADERS, + type ReleaseHistoryRouteDependencies, +} from "@/lib/microcosm/release-history-http"; +import { readReleaseHistoryManifest } from "@/lib/microcosm/release-history-read"; +import { releaseHistorySummary } from "@/lib/microcosm/release-history-summary"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +// The release history page's first read: a country's panels, one per reference engine, and the +// panel the page opens. It is read from the manifest in private Blob; a country with no measured +// file yet answers `available: false`, never another country's panels. +export function createReleaseHistorySummaryHandler( + dependencies: ReleaseHistoryRouteDependencies = DEFAULT_RELEASE_HISTORY_ROUTE_DEPENDENCIES, +) { + return async function GET(request: Request) { + const country = requiredCountry(new URL(request.url).searchParams); + if (country instanceof Response) return country; + try { + const manifest = await readReleaseHistoryManifest(dependencies.store()); + return NextResponse.json(releaseHistorySummary(country, manifest), { + headers: RELEASE_HISTORY_CACHE_HEADERS, + }); + } catch (error) { + return readFailureResponse(error); + } + }; +} + +export const GET = createReleaseHistorySummaryHandler(); diff --git a/frontend/app/api/microcosm/release-history/timeline/route.test.ts b/frontend/app/api/microcosm/release-history/timeline/route.test.ts new file mode 100644 index 00000000..f50c9730 --- /dev/null +++ b/frontend/app/api/microcosm/release-history/timeline/route.test.ts @@ -0,0 +1,122 @@ +import { expect, test } from "bun:test"; +import { gunzipSync } from "node:zlib"; + +import { + encodeDocument, + panelPrefix, + type ReleaseHistoryStore, +} from "@/lib/microcosm/release-history-store"; +import type { ReleaseHistoryPanelView } from "@/lib/microcosm/release-history-summary"; +import { fixtureStore } from "@/lib/microcosm/test-support/release-history-fixture-store"; +import { createReleaseHistoryTimelineHandler } from "./route"; + +const URL_BASE = "https://dashboard.example/calibration/dashboard/api/microcosm/release-history/timeline"; + +function handler(store: ReleaseHistoryStore) { + return createReleaseHistoryTimelineHandler({ store: () => store }); +} + +async function silenced(run: () => Promise): Promise { + const logged = console.error; + console.error = () => {}; + try { + return await run(); + } finally { + console.error = logged; + } +} + +test("without a panel the route serves the panel the page opens: its summary, presentation and whole timeline", async () => { + const { store, fixtures } = await fixtureStore(); + const response = await handler(store)(new Request(`${URL_BASE}?country=uk`)); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("application/json; charset=utf-8"); + expect(response.headers.get("content-encoding")).toBeNull(); + expect(response.headers.get("vary")).toBe("Accept-Encoding"); + expect(response.headers.get("vercel-cdn-cache-control")).toContain("max-age=60"); + const view = (await response.json()) as ReleaseHistoryPanelView; + expect(view.country).toBe("uk"); + expect(view.panelId).toBe(fixtures.uk.panel.panel_id); + expect(view.panel).toMatchObject({ panelId: fixtures.uk.panel.panel_id, served: true, complete: true }); + expect(view.presentation).toMatchObject({ currency: "GBP", periodLabel: "fiscal_year", periods: [2026] }); + expect(view.timeline).toEqual(fixtures.uk.timeline); + // Naming that panel gives the same document. + const named = await handler(store)(new Request(`${URL_BASE}?country=uk&panel=${fixtures.uk.panel.panel_id}`)); + expect(await named.json()).toEqual(view); +}); + +test("a client that accepts gzip gets the same document compressed", async () => { + const { store } = await fixtureStore(["uk"]); + const plain = await (await handler(store)(new Request(`${URL_BASE}?country=uk`))).text(); + const response = await handler(store)( + new Request(`${URL_BASE}?country=uk`, { headers: { "accept-encoding": "gzip, br" } }), + ); + expect(response.headers.get("content-encoding")).toBe("gzip"); + const compressed = new Uint8Array(await response.arrayBuffer()); + expect(gunzipSync(compressed).toString("utf8")).toBe(plain); + expect(compressed.length).toBeLessThan(plain.length / 4); +}); + +test("a panel id must be well formed, and only a panel the country's manifest lists is read", async () => { + const { store, fixtures } = await fixtureStore(); + const malformed = await handler(store)(new Request(`${URL_BASE}?country=uk&panel=../us`)); + expect(malformed.status).toBe(400); + + const unknown = await handler(store)(new Request(`${URL_BASE}?country=uk&panel=${"0".repeat(64)}`)); + expect(unknown.status).toBe(404); + expect(await unknown.json()).toEqual({ detail: "No such release history panel for uk." }); + + // Another country's panel is not this country's. + const foreign = await handler(store)(new Request(`${URL_BASE}?country=uk&panel=${fixtures.us.panel.panel_id}`)); + expect(foreign.status).toBe(404); + + // A timeline that sits in the store under a panel the manifest does not list is never served. + const stray = "d".repeat(64); + await store.write( + `${panelPrefix("uk", stray)}timeline.json`, + encodeDocument({ ...fixtures.uk.timeline, panelId: stray }), + "replace", + false, + ); + expect((await handler(store)(new Request(`${URL_BASE}?country=uk&panel=${stray}`))).status).toBe(404); +}); + +test("a country with no history, and a panel with no timeline, are 404s with no cache", async () => { + const { store, fixtures } = await fixtureStore(["uk"]); + const none = await handler(store)(new Request(`${URL_BASE}?country=us`)); + expect(none.status).toBe(404); + expect(none.headers.get("cache-control")).toBe("no-store"); + expect(await none.json()).toEqual({ detail: "No release history is stored for us yet." }); + + store.objects.delete(`${panelPrefix("uk", fixtures.uk.panel.panel_id)}timeline.json`); + const missing = await handler(store)(new Request(`${URL_BASE}?country=uk`)); + expect(missing.status).toBe(404); + expect(await missing.json()).toEqual({ detail: "This panel has no timeline yet." }); +}); + +test("a stored timeline that is not this panel's, or not a timeline, is a 502", async () => { + const { store, fixtures } = await fixtureStore(); + const path = `${panelPrefix("uk", fixtures.uk.panel.panel_id)}timeline.json`; + const wrong = [ + fixtures.us.timeline, + { ...fixtures.uk.timeline, formatVersion: 2 }, + { ...fixtures.uk.timeline, kind: "release_history.series" }, + { ...fixtures.uk.timeline, outputs: null }, + ]; + await silenced(async () => { + for (const document of wrong) { + await store.write(path, encodeDocument(document), "replace", false); + const response = await handler(store)(new Request(`${URL_BASE}?country=uk`)); + expect(response.status).toBe(502); + expect(await response.json()).toEqual({ detail: "The stored timeline could not be read." }); + } + }); +}); + +test("the route needs a country and refuses one the dashboard does not serve", async () => { + const { store } = await fixtureStore(["uk"]); + expect((await handler(store)(new Request(URL_BASE))).status).toBe(400); + const response = await handler(store)(new Request(`${URL_BASE}?country=nz`)); + expect(response.status).toBe(404); + expect(await response.json()).toMatchObject({ error: "country_not_configured" }); +}); diff --git a/frontend/app/api/microcosm/release-history/timeline/route.ts b/frontend/app/api/microcosm/release-history/timeline/route.ts new file mode 100644 index 00000000..f526fc65 --- /dev/null +++ b/frontend/app/api/microcosm/release-history/timeline/route.ts @@ -0,0 +1,41 @@ +import { requiredCountry } from "@/lib/api/request-country"; +import { + compressedResponse, + DEFAULT_RELEASE_HISTORY_ROUTE_DEPENDENCIES, + panelProblemResponse, + readFailureResponse, + RELEASE_HISTORY_CACHE_HEADERS, + requestedPanel, + type ReleaseHistoryRouteDependencies, +} from "@/lib/microcosm/release-history-http"; +import { readPanelView } from "@/lib/microcosm/release-history-read"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +// One panel as the page loads it: the panel's summary, how to present its outputs, and its whole +// `timeline.json`, read from private Blob. `?panel=` names the panel of one reference engine; +// without it the route serves the panel the page opens. +export function createReleaseHistoryTimelineHandler( + dependencies: ReleaseHistoryRouteDependencies = DEFAULT_RELEASE_HISTORY_ROUTE_DEPENDENCIES, +) { + return async function GET(request: Request) { + const params = new URL(request.url).searchParams; + const country = requiredCountry(params); + if (country instanceof Response) return country; + const panel = requestedPanel(params); + if (panel instanceof Response) return panel; + try { + const result = await readPanelView(dependencies.store(), country, panel); + if (result.kind !== "ok") return panelProblemResponse(result, country); + return compressedResponse(request, JSON.stringify(result.view), { + ...RELEASE_HISTORY_CACHE_HEADERS, + "Content-Type": "application/json; charset=utf-8", + }); + } catch (error) { + return readFailureResponse(error); + } + }; +} + +export const GET = createReleaseHistoryTimelineHandler(); diff --git a/frontend/lib/microcosm/calibration-tree-http.ts b/frontend/lib/microcosm/calibration-tree-http.ts index 23b31f54..30f816ae 100644 --- a/frontend/lib/microcosm/calibration-tree-http.ts +++ b/frontend/lib/microcosm/calibration-tree-http.ts @@ -3,7 +3,7 @@ import { NextResponse } from "next/server"; import { calibrationTreeBlobText } from "@policyengine/calibration-tree/calibration-tree-blob"; -function acceptsGzip(request: Request): boolean { +export function acceptsGzip(request: Request): boolean { return (request.headers.get("accept-encoding") ?? "") .split(",") .map((item) => item.trim().toLowerCase()) diff --git a/frontend/lib/microcosm/release-history-export.test.ts b/frontend/lib/microcosm/release-history-export.test.ts new file mode 100644 index 00000000..9752d0b7 --- /dev/null +++ b/frontend/lib/microcosm/release-history-export.test.ts @@ -0,0 +1,94 @@ +import { expect, test } from "bun:test"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { + TIMELINE_CSV_COLUMNS, + timelineCsv, + timelineCsvFileName, + timelineCsvRows, +} from "./release-history-export"; +import type { Timeline } from "./release-history-store"; +import { readCountryFixture } from "./test-support/release-history-fixture-store"; + +const PRODUCER_EXPORT = join( + import.meta.dir, "..", "..", "..", "release_history", "src", "release_history", "export.py", +); + +test("the table has the columns of the producer's export command", async () => { + const source = await readFile(PRODUCER_EXPORT, "utf8"); + const block = /TIMELINE_COLUMNS = \[([^\]]*)\]/.exec(source)?.[1] ?? ""; + const columns = [...block.matchAll(/"([a-z_]+)"/g)].map((match) => match[1]); + expect(columns.length).toBeGreaterThan(0); + expect([...TIMELINE_CSV_COLUMNS] as string[]).toEqual(columns); +}); + +test("one row per build and output, with the step and the official reference", async () => { + const { timeline } = await readCountryFixture("uk"); + const rows = timelineCsvRows(timeline); + expect(rows).toHaveLength(timeline.builds.length * timeline.outputs.length); + const row = rows.find((candidate) => + candidate.output === "baseline/income_tax" && String(candidate.build_id).endsWith("synthetic-build-3"))!; + const output = timeline.outputs.find((candidate) => candidate.output === "baseline/income_tax")!; + const value = output.values.find((candidate) => candidate.buildId === row.build_id)!; + expect(row).toMatchObject({ + published_at: "2026-10-24T09:00:00+00:00", + current: true, + withdrawn: false, + state: "measured", + period: 2026, + unit: "currency", + value: value.value, + status: "ok", + compared_with: "microcosm-uk-2024-25-national/synthetic-build-2", + change: value.change, + relative_change: value.relativeChange, + change_status: "ok", + reference_status: "resolved", + reference_value: output.reference?.modelSignValue, + reference_basis: "forecast", + }); + // The second build publishes the first one's file. + expect(rows.find((candidate) => String(candidate.build_id).endsWith("synthetic-build-2"))).toMatchObject({ + same_file_as: "microcosm-uk-2024-25-national/synthetic-build-1", + }); +}); + +test("a withheld value is an empty cell with its status, and no step beside it carries a number", async () => { + const { timeline } = await readCountryFixture("uk"); + const rows = timelineCsvRows(timeline); + const withheld = rows.filter((row) => row.status === "withheld"); + expect(withheld.length).toBeGreaterThan(0); + for (const row of withheld) expect(row.value).toBeNull(); + const withheldSteps = rows.filter((row) => row.change_status === "withheld"); + expect(withheldSteps.length).toBeGreaterThan(0); + for (const row of withheldSteps) { + expect([row.change, row.relative_change, row.change_points]).toEqual([null, null, null]); + } + expect(Object.keys(rows[0])).not.toContain("reason"); + + // A document that carried a number beside a withheld status would still export none. + const leaking: Timeline = structuredClone(timeline); + const cell = leaking.outputs.flatMap((output) => output.values).find((value) => value.status === "withheld")!; + cell.value = 12345.678; + cell.change = 1; + cell.changeStatus = "withheld"; + expect(timelineCsv(leaking)).not.toContain("12345.678"); +}); + +test("the text is RFC 4180: a header, CRLF rows, and quotes around a field that needs them", async () => { + const { timeline } = await readCountryFixture("us"); + const quoted: Timeline = structuredClone(timeline); + quoted.builds[0].unknownColumns = ['a "quoted" column', "one,two"]; + const lines = timelineCsv(quoted).split("\r\n"); + expect(lines[0]).toBe(TIMELINE_CSV_COLUMNS.join(",")); + expect(lines.at(-1)).toBe(""); + expect(lines).toHaveLength(1 + quoted.builds.length * quoted.outputs.length + 1); + expect(lines[1]).toContain('"a ""quoted"" column;one,two"'); + // A build the panel never measured: empty cells, never the text "null". + expect(timelineCsv(quoted)).not.toContain("null"); +}); + +test("a download is named by its country and panel", () => { + expect(timelineCsvFileName("uk", "af35ceddec5f".padEnd(64, "0"))).toBe("release-history-uk-af35ceddec5f.csv"); +}); diff --git a/frontend/lib/microcosm/release-history-export.ts b/frontend/lib/microcosm/release-history-export.ts new file mode 100644 index 00000000..b4ed072f --- /dev/null +++ b/frontend/lib/microcosm/release-history-export.ts @@ -0,0 +1,101 @@ +/** + * A panel's timeline as a long table (calibration-diagnostics#224): one row per build and + * output, with the step from the build before it on the series and the output's official + * reference. The columns and rows are those of the producer's `release-history export` + * (`release_history/export.py`, `TIMELINE_COLUMNS` and `timeline_rows`); a test compares the + * column lists. A withheld value is an empty cell with the status `withheld`. + */ +import type { Timeline } from "./release-history-store"; + +export const TIMELINE_CSV_COLUMNS = [ + "build_id", + "published_at", + "current", + "withdrawn", + "same_file_as", + "state", + "measurement_id", + "reference_model_compatibility", + "unknown_columns", + "period", + "output", + "unit", + "value", + "status", + "compared_with", + "change", + "relative_change", + "change_points", + "change_status", + "reference_status", + "reference_value", + "reference_basis", +] as const; + +export type TimelineCsvColumn = (typeof TIMELINE_CSV_COLUMNS)[number]; +export type TimelineCsvRow = Record; + +/** The official figure in the model's sign convention, when the reference has a value. */ +function referenceValue(reference: Timeline["outputs"][number]["reference"]): number | null { + if (!reference) return null; + if (typeof reference.modelSignValue === "number") return reference.modelSignValue; + return typeof reference.value === "number" ? reference.value : null; +} + +export function timelineCsvRows(timeline: Timeline): TimelineCsvRow[] { + const builds = new Map(timeline.builds.map((build) => [build.buildId, build])); + const rows: TimelineCsvRow[] = []; + for (const output of timeline.outputs) { + const reference = output.reference; + for (const entry of output.values) { + const build = builds.get(entry.buildId); + if (!build) continue; + rows.push({ + build_id: build.buildId, + published_at: build.publishedAt, + current: build.current, + withdrawn: build.withdrawn, + same_file_as: build.sameFileAs, + state: build.state, + measurement_id: build.measurementId, + reference_model_compatibility: build.referenceModelCompatibility, + unknown_columns: (build.unknownColumns ?? []).join(";"), + period: output.period, + output: output.output, + unit: output.unit, + // A withheld cell never carries its value into the export. + value: entry.status === "ok" ? entry.value : null, + status: entry.status, + compared_with: entry.comparedWith, + change: entry.changeStatus === "ok" ? entry.change : null, + relative_change: entry.changeStatus === "ok" ? entry.relativeChange : null, + change_points: entry.changeStatus === "ok" ? entry.changePoints : null, + change_status: entry.changeStatus, + reference_status: reference ? reference.status : null, + reference_value: referenceValue(reference), + reference_basis: typeof reference?.basis === "string" ? reference.basis : null, + }); + } + } + return rows; +} + +function csvField(value: string | number | boolean | null): string { + if (value === null) return ""; + const field = String(value); + return /[",\r\n]/.test(field) ? `"${field.replace(/"/g, '""')}"` : field; +} + +/** The table as RFC 4180 text, with a header row. */ +export function timelineCsv(timeline: Timeline): string { + const lines = [TIMELINE_CSV_COLUMNS.join(",")]; + for (const row of timelineCsvRows(timeline)) { + lines.push(TIMELINE_CSV_COLUMNS.map((column) => csvField(row[column])).join(",")); + } + return `${lines.join("\r\n")}\r\n`; +} + +/** The file name a download of a panel's table gets. */ +export function timelineCsvFileName(country: string, panelId: string): string { + return `release-history-${country}-${panelId.slice(0, 12)}.csv`; +} diff --git a/frontend/lib/microcosm/release-history-http.ts b/frontend/lib/microcosm/release-history-http.ts new file mode 100644 index 00000000..0b24515f --- /dev/null +++ b/frontend/lib/microcosm/release-history-http.ts @@ -0,0 +1,84 @@ +/** + * What the release history page's routes share (calibration-diagnostics#224): the store they + * read by default, the `panel` parameter, their cache headers, and a response that compresses + * itself. A timeline grows with every build, and a function's response has a size limit, so the + * routes send gzip to a client that accepts it. + */ +import { gzipSync } from "node:zlib"; +import { NextResponse } from "next/server"; + +import { acceptsGzip } from "./calibration-tree-http"; +import { PANEL_ID_PATTERN, type PanelViewResult } from "./release-history-read"; +import { releaseHistoryReadStore } from "./release-history-source"; +import type { ReleaseHistoryStore } from "./release-history-store"; + +export interface ReleaseHistoryRouteDependencies { + /** The store a request reads: private Blob, or the local folder the environment names. */ + store(): ReleaseHistoryStore; +} + +export const DEFAULT_RELEASE_HISTORY_ROUTE_DEPENDENCIES: ReleaseHistoryRouteDependencies = { + store: () => releaseHistoryReadStore(), +}; + +// The manifest and every timeline change at each run, so the CDN keeps a response for a minute. +export const RELEASE_HISTORY_CACHE_HEADERS = { + "Cache-Control": "public, max-age=0, must-revalidate", + "Vercel-CDN-Cache-Control": "public, max-age=60, stale-if-error=86400", +}; + +export const NO_STORE_HEADERS = { "Cache-Control": "no-store" }; + +/** The panel a request names, null when it names none, or the 400 for a malformed id. */ +export function requestedPanel(searchParams: URLSearchParams): string | null | NextResponse { + const panel = searchParams.get("panel")?.trim(); + if (!panel) return null; + if (PANEL_ID_PATTERN.test(panel)) return panel; + return NextResponse.json( + { detail: "A panel id is 64 hexadecimal characters." }, + { status: 400, headers: NO_STORE_HEADERS }, + ); +} + +/** The response for a panel that could not be served. */ +export function panelProblemResponse( + result: Exclude, + country: string, +): NextResponse { + if (result.kind === "mismatch") { + console.error(`Release history timeline refused for ${country}: ${result.detail}`); + return NextResponse.json( + { detail: "The stored timeline could not be read." }, + { status: 502, headers: NO_STORE_HEADERS }, + ); + } + const detail = { + no_history: `No release history is stored for ${country} yet.`, + unknown_panel: `No such release history panel for ${country}.`, + no_timeline: "This panel has no timeline yet.", + }[result.kind]; + return NextResponse.json({ detail }, { status: 404, headers: NO_STORE_HEADERS }); +} + +/** A read of the store that failed: logged with its cause, answered without it. */ +export function readFailureResponse(error: unknown): NextResponse { + console.error("Release history read failed:", error); + return NextResponse.json( + { detail: "The release history could not be read." }, + { status: 503, headers: NO_STORE_HEADERS }, + ); +} + +/** A text response, compressed with gzip for a client that accepts it. */ +export function compressedResponse( + request: Request, + body: string, + headers: Record, +): NextResponse { + const responseHeaders = { ...headers, Vary: "Accept-Encoding" }; + if (!acceptsGzip(request)) return new NextResponse(body, { status: 200, headers: responseHeaders }); + return new NextResponse(new Uint8Array(gzipSync(body)), { + status: 200, + headers: { ...responseHeaders, "Content-Encoding": "gzip" }, + }); +} diff --git a/frontend/lib/microcosm/release-history-read.ts b/frontend/lib/microcosm/release-history-read.ts new file mode 100644 index 00000000..c78831a5 --- /dev/null +++ b/frontend/lib/microcosm/release-history-read.ts @@ -0,0 +1,92 @@ +/** + * Server-side reads for the release history page's routes (calibration-diagnostics#224): the + * manifest, and one panel as the page loads it. Everything is read through a ReleaseHistoryStore, + * so the routes' tests use the in-memory one. + */ +import { + panelPrefix, + parseManifest, + readJson, + RELEASE_HISTORY_MANIFEST_PATH, + TIMELINE_FORMAT_VERSION, + type PanelDocument, + type ReleaseHistoryManifest, + type ReleaseHistoryStore, + type Timeline, +} from "./release-history-store"; +import { + panelPresentation, + releaseHistorySummary, + type ReleaseHistoryPanelView, +} from "./release-history-summary"; + +export const PANEL_ID_PATTERN = /^[0-9a-f]{64}$/; + +/** The stored manifest, or null while the store holds none. */ +export async function readReleaseHistoryManifest( + store: ReleaseHistoryStore, +): Promise { + const found = await readJson(store, RELEASE_HISTORY_MANIFEST_PATH); + return found === null ? null : parseManifest(found); +} + +/** + * `no_history`: the country has no measured file. `unknown_panel`: the manifest lists no such + * panel with a measured file. `no_timeline`: the panel's timeline is not in the store. + * `mismatch`: the stored timeline is not this panel's, or not a timeline this code reads. + */ +export type PanelViewResult = + | { kind: "ok"; view: ReleaseHistoryPanelView } + | { kind: "no_history" } + | { kind: "unknown_panel" } + | { kind: "no_timeline" } + | { kind: "mismatch"; detail: string }; + +function timelineProblem(timeline: Timeline, country: string, panelId: string): string | null { + if (timeline === null || typeof timeline !== "object") return "The stored timeline is not an object."; + if (timeline.kind !== "release_history.timeline") return "The stored document is not a timeline."; + if (timeline.formatVersion !== TIMELINE_FORMAT_VERSION) { + return `Unsupported timeline format ${String(timeline.formatVersion)}.`; + } + if (timeline.country !== country || timeline.panelId !== panelId) { + return "The stored timeline belongs to another country or panel."; + } + if (!Array.isArray(timeline.builds) || !Array.isArray(timeline.outputs)) { + return "The stored timeline has no builds or no outputs."; + } + return null; +} + +/** + * One panel of a country: the one asked for, or the one the page opens when none is named. Only + * a panel the country's manifest entry lists is ever read. + */ +export async function readPanelView( + store: ReleaseHistoryStore, + country: string, + requestedPanelId: string | null, +): Promise { + const summary = releaseHistorySummary(country, await readReleaseHistoryManifest(store)); + if (!summary.available) return { kind: "no_history" }; + const panelId = requestedPanelId ?? summary.defaultPanelId; + const panel = summary.panels.find((candidate) => candidate.panelId === panelId); + if (!panel) return { kind: "unknown_panel" }; + const prefix = panelPrefix(country, panel.panelId); + const [timeline, document] = await Promise.all([ + readJson(store, `${prefix}timeline.json`), + readJson(store, `${prefix}panel.json`), + ]); + if (!timeline) return { kind: "no_timeline" }; + const problem = timelineProblem(timeline, country, panel.panelId); + if (problem) return { kind: "mismatch", detail: problem }; + return { + kind: "ok", + view: { + country, + panelId: panel.panelId, + panel, + presentation: panelPresentation(document), + timeline, + }, + }; +} diff --git a/frontend/lib/microcosm/release-history-source.test.ts b/frontend/lib/microcosm/release-history-source.test.ts new file mode 100644 index 00000000..c246b67d --- /dev/null +++ b/frontend/lib/microcosm/release-history-source.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from "bun:test"; +import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + directoryStore, + RELEASE_HISTORY_LOCAL_DIR_ENV, + releaseHistoryLocalDirectory, +} from "./release-history-source"; +import { readJson, RELEASE_HISTORY_MANIFEST_PATH } from "./release-history-store"; + +async function folder(): Promise { + const root = await mkdtemp(join(tmpdir(), "release-history-source-")); + await mkdir(join(root, "release-history", "zz", "a".repeat(64)), { recursive: true }); + await writeFile(join(root, RELEASE_HISTORY_MANIFEST_PATH), JSON.stringify({ formatVersion: 1 })); + await writeFile(join(root, "release-history", "zz", "series.json"), "{}"); + await writeFile(join(root, "release-history", "zz", "a".repeat(64), "timeline.json"), "{}"); + return root; +} + +test("a local folder reads and lists in the store's layout, and is never written", async () => { + const store = directoryStore(await folder()); + expect(await readJson<{ formatVersion: number }>(store, RELEASE_HISTORY_MANIFEST_PATH)).toEqual({ formatVersion: 1 }); + expect(await store.read("release-history/zz/labels.json")).toBeNull(); + // A folder where a file is asked for is not a document. + expect(await store.read("release-history/zz")).toBeNull(); + expect(await store.list("release-history/zz/")).toEqual([ + `release-history/zz/${"a".repeat(64)}/timeline.json`, + "release-history/zz/series.json", + ]); + expect(await store.list("release-history/us/")).toEqual([]); + await expect(store.write("release-history/zz/series.json", new Uint8Array(), "replace", false)) + .rejects.toThrow("read-only"); +}); + +test("a path that leaves the folder is not read, and a link is not followed when listing", async () => { + const root = await folder(); + const outside = await mkdtemp(join(tmpdir(), "release-history-outside-")); + await writeFile(join(outside, "secret.json"), "{}"); + await symlink(outside, join(root, "release-history", "linked")); + const store = directoryStore(root); + expect(await store.read(`../${outside.split("/").pop()}/secret.json`)).toBeNull(); + expect(await store.read("/etc/hosts")).toBeNull(); + expect((await store.list("release-history/")).some((path) => path.includes("linked"))).toBe(false); +}); + +test("the folder is read only when the environment names it", () => { + expect(releaseHistoryLocalDirectory({})).toBeNull(); + expect(releaseHistoryLocalDirectory({ [RELEASE_HISTORY_LOCAL_DIR_ENV]: " " })).toBeNull(); + expect(releaseHistoryLocalDirectory({ [RELEASE_HISTORY_LOCAL_DIR_ENV]: "/tmp/store" })).toBe("/tmp/store"); +}); diff --git a/frontend/lib/microcosm/release-history-source.ts b/frontend/lib/microcosm/release-history-source.ts new file mode 100644 index 00000000..d30243d9 --- /dev/null +++ b/frontend/lib/microcosm/release-history-source.ts @@ -0,0 +1,91 @@ +/** + * Where the release history routes read from (calibration-diagnostics#224): the private Vercel + * Blob store, or a local folder in the same layout. + * + * The folder is for development and for looking at a pulled panel: `scripts/release-history.ts + * pull --out ` and the Python producer both write this layout. It is read only when + * RELEASE_HISTORY_LOCAL_DIR names it, so a hosted deployment never reads its own filesystem. + */ +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; + +import { + vercelBlobStore, + type ReleaseHistoryStore, + type StoredObject, +} from "./release-history-store"; + +export const RELEASE_HISTORY_LOCAL_DIR_ENV = "RELEASE_HISTORY_LOCAL_DIR"; + +const MISSING = new Set(["ENOENT", "ENOTDIR", "EISDIR"]); + +function isMissing(error: unknown): boolean { + return MISSING.has((error as NodeJS.ErrnoException | null)?.code ?? ""); +} + +async function filesUnder(directory: string): Promise { + let entries; + try { + entries = await readdir(directory, { withFileTypes: true }); + } catch (error) { + if (isMissing(error)) return []; + throw error; + } + const files: string[] = []; + for (const entry of entries) { + const child = path.join(directory, entry.name); + // A link could lead out of the folder, so it is never followed. + if (entry.isDirectory()) files.push(...await filesUnder(child)); + else if (entry.isFile()) files.push(child); + } + return files; +} + +/** A read-only store over a local folder that holds `release-history/...` as Blob does. */ +export function directoryStore(root: string): ReleaseHistoryStore { + const base = path.resolve(root); + const inside = (storePath: string): string | null => { + const resolved = path.resolve(base, storePath); + return resolved.startsWith(`${base}${path.sep}`) ? resolved : null; + }; + return { + async read(storePath): Promise { + const file = inside(storePath); + if (!file) return null; + try { + const [body, facts] = await Promise.all([readFile(file), stat(file)]); + return { body: new Uint8Array(body), etag: `"${facts.size}-${Math.round(facts.mtimeMs)}"` }; + } catch (error) { + if (isMissing(error)) return null; + throw error; + } + }, + async write(storePath) { + throw new Error(`The local release history folder is read-only: ${storePath} was not written.`); + }, + async list(prefix) { + return (await filesUnder(base)) + .map((file) => path.relative(base, file).split(path.sep).join("/")) + .filter((storePath) => storePath.startsWith(prefix)) + .sort(); + }, + }; +} + +/** The local folder the environment names, or null when it names none. */ +export function releaseHistoryLocalDirectory( + environment: Record = process.env, +): string | null { + const named = environment[RELEASE_HISTORY_LOCAL_DIR_ENV]?.trim(); + return named ? path.resolve(named) : null; +} + +/** The store the page's routes read: the named local folder, otherwise private Blob. */ +export function releaseHistoryReadStore( + environment: Record = process.env, +): ReleaseHistoryStore { + const directory = releaseHistoryLocalDirectory(environment); + return directory + ? directoryStore(directory) + : vercelBlobStore(environment.BLOB_READ_WRITE_TOKEN || undefined); +} diff --git a/frontend/lib/microcosm/release-history-summary.test.ts b/frontend/lib/microcosm/release-history-summary.test.ts new file mode 100644 index 00000000..1ad32ac5 --- /dev/null +++ b/frontend/lib/microcosm/release-history-summary.test.ts @@ -0,0 +1,276 @@ +import { expect, test } from "bun:test"; + +import { + finalizeCountry, + type ManifestCountry, + type MeasurementDocument, + type PanelSummary, + type PlannedPoint, + type ReleaseHistoryManifest, + type SeriesBuild, + type SeriesRecord, +} from "./release-history-store"; +import { + defaultPanelId, + panelPresentation, + releaseHistorySummary, +} from "./release-history-summary"; +import { readCountryFixture } from "./test-support/release-history-fixture-store"; +import { measurementDocument } from "./test-support/release-history-documents"; + +const LINE = "zz-national"; +const EARLIER = "a".repeat(64); +const NEWER = "b".repeat(64); +const OFF_BRANCH = "c".repeat(64); +const file = (index: number) => index.toString(16).padStart(64, "0"); + +function build(index: number): SeriesBuild { + return { + build_id: `${LINE}/b${index}`, + release: LINE, + build: `b${index}`, + release_directory: `${LINE}/b${index}`, + published_at: `2026-11-${String(index).padStart(2, "0")}T00:00:00Z`, + withdrawn: false, + current: false, + in_default_release: true, + role: "national", + digest: file(index), + dataset_path: `releases/${LINE}/b${index}/zz.h5`, + release_manifest_sha256: "f".repeat(64), + listing_status: "ok", + listing_reason: null, + }; +} + +const SERIES: SeriesRecord = { + format_version: 1, + kind: "release_history.series", + country: "zz", + release_repo: "policyengine/zz", + rule: { releases: [LINE], since: null }, + revision: "main", + commit: "1".repeat(40), + listed_at: "2026-11-12T00:00:00Z", + record: { present: true, sha256: "d".repeat(64), default: LINE }, + lines: [{ release: LINE, present: true, role: "national" }], + builds: [build(1), build(2), build(3)], +}; + +function point(panelId: string, index: number): MeasurementDocument { + return measurementDocument({ country: "zz", panelId, measurementId: `${index}`.padStart(64, "9"), digest: file(index) }); +} + +function panel(panelId: string, version: string, spec = "s".repeat(64)): PanelSummary { + return { + panelId, + engine: { policyengine: "6.16.1", model: `policyengine-zz==${version}`, core: "policyengine-core==3.33.3" }, + specSha256: spec, + producerVersion: "1", + }; +} + +function planned(index: number): PlannedPoint { + return { + build_id: `${LINE}/b${index}`, + release_directory: `${LINE}/b${index}`, + hf_repo: "policyengine/zz", + hf_commit: "1".repeat(40), + digest: file(index), + attempt: 1, + last_attempt: false, + }; +} + +/** The earlier engine's panel, complete, pinned and served. */ +function afterFirstBackfill(): ManifestCountry { + return finalizeCountry({ + entry: undefined, + panel: panel(EARLIER, "1.0.0"), + series: SERIES, + mode: "backfill", + planned: [], + stored: [1, 2, 3].map((index) => point(EARLIER, index)), + pin: true, + at: "2026-11-05T00:00:00Z", + }); +} + +/** An engine bump whose first top-up stored two of three files; the third is retrying. */ +function midBump(): ManifestCountry { + return finalizeCountry({ + entry: afterFirstBackfill(), + panel: panel(NEWER, "1.1.0"), + series: SERIES, + mode: "topup", + planned: [planned(1), planned(2), planned(3)], + stored: [1, 2].map((index) => point(NEWER, index)), + pin: true, + at: "2026-11-10T00:00:00Z", + }); +} + +function manifest(entry: ManifestCountry): ReleaseHistoryManifest { + return { formatVersion: 1, updatedAt: "2026-11-10T00:00:00Z", countries: { zz: entry } }; +} + +test("a country with one complete panel opens it", () => { + const summary = releaseHistorySummary("zz", manifest(afterFirstBackfill())); + expect(summary).toMatchObject({ + country: "zz", + available: true, + defaultPanelId: EARLIER, + pinnedPanelId: EARLIER, + servedPanelId: EARLIER, + }); + expect(summary.panels).toHaveLength(1); + expect(summary.panels[0]).toMatchObject({ + panelId: EARLIER, + engine: { policyengine: "6.16.1", model: "policyengine-zz==1.0.0", core: "policyengine-core==3.33.3" }, + pinned: true, + served: true, + complete: true, + sameDefinitionAsDefault: true, + coverage: { builds: 3, files: 3, measured: 3, missing: 0 }, + }); +}); + +test("after an engine bump the page opens the served panel until the pinned one is complete", () => { + const filling = midBump(); + expect(filling.pinnedPanelId).toBe(NEWER); + expect(filling.currentPanelId).toBe(EARLIER); + const summary = releaseHistorySummary("zz", manifest(filling)); + expect(summary.defaultPanelId).toBe(EARLIER); + // The default panel is first; the pinned one follows, with what it holds so far. + expect(summary.panels.map((listed) => [listed.panelId, listed.pinned, listed.served, listed.complete])).toEqual([ + [EARLIER, false, true, true], + [NEWER, true, false, false], + ]); + expect(summary.panels[1].coverage).toMatchObject({ files: 3, measured: 2, retrying: 1 }); + + // The next top-up stores the third file: the pinned panel is complete and the page moves. + const complete = finalizeCountry({ + entry: filling, + panel: panel(NEWER, "1.1.0"), + series: SERIES, + mode: "topup", + planned: [{ ...planned(3), attempt: 2 }], + stored: [1, 2, 3].map((index) => point(NEWER, index)), + pin: true, + at: "2026-11-17T00:00:00Z", + }); + const moved = releaseHistorySummary("zz", manifest(complete)); + expect(moved.defaultPanelId).toBe(NEWER); + expect(moved.panels.map((listed) => listed.panelId)).toEqual([NEWER, EARLIER]); +}); + +test("a first panel that is still filling opens once it holds a measured file", () => { + const filling = finalizeCountry({ + entry: undefined, + panel: panel(EARLIER, "1.0.0"), + series: SERIES, + mode: "backfill", + planned: [planned(1), planned(2), planned(3)], + stored: [point(EARLIER, 1)], + pin: true, + at: "2026-11-05T00:00:00Z", + }); + expect(filling.currentPanelId).toBeNull(); + expect(defaultPanelId(filling)).toBe(EARLIER); + + // A panel that holds no measured file is not a history yet. + const nothing = finalizeCountry({ + entry: undefined, + panel: panel(EARLIER, "1.0.0"), + series: SERIES, + mode: "backfill", + planned: [planned(1)], + stored: [], + pin: true, + at: "2026-11-05T00:00:00Z", + }); + expect(releaseHistorySummary("zz", manifest(nothing))).toMatchObject({ + available: false, + defaultPanelId: null, + panels: [], + }); +}); + +test("a panel a run from another ref filled is listed, never opened by default, and says when its definition differs", () => { + const entry = finalizeCountry({ + entry: afterFirstBackfill(), + panel: panel(OFF_BRANCH, "0.9.0", "t".repeat(64)), + series: SERIES, + mode: "release", + planned: [planned(2)], + stored: [point(OFF_BRANCH, 2)], + pin: false, + at: "2026-11-11T00:00:00Z", + }); + const summary = releaseHistorySummary("zz", manifest(entry)); + expect(summary.defaultPanelId).toBe(EARLIER); + expect(summary.panels.map((listed) => [listed.panelId, listed.pinnedAt, listed.sameDefinitionAsDefault])).toEqual([ + [EARLIER, "2026-11-05T00:00:00Z", true], + [OFF_BRANCH, null, false], + ]); + expect(summary.panels[1].coverage).toMatchObject({ measured: 1, missing: 2 }); +}); + +test("a country the manifest does not hold has no history, and never another country's", () => { + const stored = manifest(afterFirstBackfill()); + expect(releaseHistorySummary("uk", stored)).toEqual({ + country: "uk", + available: false, + updatedAt: "2026-11-10T00:00:00Z", + defaultPanelId: null, + pinnedPanelId: null, + servedPanelId: null, + panels: [], + }); + expect(releaseHistorySummary("uk", null)).toMatchObject({ available: false, updatedAt: null }); + // A country code that names a property every object has is still no country. + expect(releaseHistorySummary("constructor", stored).available).toBe(false); +}); + +test("the summary carries no per-file entry of the manifest", () => { + const text = JSON.stringify(releaseHistorySummary("zz", manifest(midBump()))); + expect(text).not.toContain("points"); + expect(text).not.toContain("lastError"); + for (const index of [1, 2, 3]) expect(text).not.toContain(file(index)); +}); + +test("each country's panel.json gives the page its currency, periods, order and kinds", async () => { + const uk = panelPresentation((await readCountryFixture("uk")).panel); + expect(uk).toMatchObject({ + currency: "GBP", + periodLabel: "fiscal_year", + periods: [2026], + // panel.json holds the hashed spec with its keys sorted, so a map's order is alphabetical; + // the lists (baseline items, reforms) keep the spec's order. + povertyMeasures: ["absolute_ahc", "absolute_bhc", "relative_ahc", "relative_bhc"], + groups: ["all", "children"], + disclosure: { policy: "source_household_small_cells", minSourceHouseholds: 3 }, + }); + expect(uk.baseline.slice(0, 2)).toEqual([ + { id: "income_tax", kind: "tax", stat: "sum", byDecile: false }, + { id: "national_insurance", kind: "tax", stat: "sum", byDecile: false }, + ]); + expect(uk.baseline.at(-1)).toEqual({ id: "household_net_income_mean", kind: "income", stat: "mean", byDecile: true }); + expect(uk.reforms[0]).toBe("basic_rate_plus_1p"); + expect(uk.reforms).toHaveLength(7); + + const us = panelPresentation((await readCountryFixture("us")).panel); + expect(us).toMatchObject({ currency: "USD", periodLabel: "calendar_year", disclosure: { policy: "none" } }); + + // No panel.json, or one with another shape: empty lists, never a throw. + expect(panelPresentation(null)).toEqual({ + currency: null, + periodLabel: "calendar_year", + periods: [], + baseline: [], + reforms: [], + povertyMeasures: [], + groups: [], + disclosure: { policy: null, minSourceHouseholds: null }, + }); +}); diff --git a/frontend/lib/microcosm/release-history-summary.ts b/frontend/lib/microcosm/release-history-summary.ts new file mode 100644 index 00000000..e13246d2 --- /dev/null +++ b/frontend/lib/microcosm/release-history-summary.ts @@ -0,0 +1,222 @@ +/** + * What the release history page's routes return (calibration-diagnostics#224): a country's + * panels from the manifest, the panel the page opens, and what a panel's `panel.json` says about + * how to present its outputs. Pure, with type-only imports, so the page imports it too. + */ +import type { + ManifestCountry, + ManifestPanel, + PanelCoverage, + PanelDocument, + ReleaseHistoryManifest, + Timeline, +} from "./release-history-store"; + +/** A panel's reference engine, as the manifest names it (`==`). */ +export interface ReleaseHistoryEngine { + policyengine: string | null; + model: string | null; + core: string | null; +} + +/** + * One panel of a country. `pinned`: the panel of the engine the default branch pins. `served`: + * the manifest's current panel, the last pinned one that was complete. The per-file entries stay + * in the manifest: the panel's timeline says which builds it has no run for. + */ +export interface ReleaseHistoryPanelSummary { + panelId: string; + engine: ReleaseHistoryEngine; + specSha256: string | null; + producerVersion: string | null; + createdAt: string | null; + pinnedAt: string | null; + pinned: boolean; + served: boolean; + complete: boolean; + coverage: PanelCoverage; + /** Whether its spec and producer version equal the default panel's, so its outputs are the same. */ + sameDefinitionAsDefault: boolean; +} + +export interface ReleaseHistorySummary { + country: string; + /** False while the store holds no measured file for the country. */ + available: boolean; + updatedAt: string | null; + /** The panel the page opens when the URL names none. */ + defaultPanelId: string | null; + pinnedPanelId: string | null; + servedPanelId: string | null; + /** Every panel that holds a measured file, the default one first. */ + panels: ReleaseHistoryPanelSummary[]; +} + +function text(value: unknown): string | null { + return typeof value === "string" && value.trim() ? value : null; +} + +function holdsMeasuredFile(panel: ManifestPanel): boolean { + return Object.values(panel.points ?? {}).some((point) => point.state === "measured"); +} + +/** Newest first, by when a panel was last pinned, or created when it never was. */ +function byRecency(left: ManifestPanel, right: ManifestPanel): number { + const leftAt = left.pinnedAt ?? left.createdAt ?? ""; + const rightAt = right.pinnedAt ?? right.createdAt ?? ""; + if (leftAt !== rightAt) return leftAt < rightAt ? 1 : -1; + return left.panelId < right.panelId ? -1 : left.panelId > right.panelId ? 1 : 0; +} + +/** + * The panel the page opens: the served panel, which is the last complete one. After an engine + * bump the pinned panel fills first and the page moves to it only once it is complete (María, + * 26 November 2026). Before any panel is complete it is the pinned one, and failing that the + * newest panel that holds a measured file. + */ +export function defaultPanelId(entry: ManifestCountry | undefined): string | null { + if (!entry) return null; + const listed = Object.values(entry.panels ?? {}).filter(holdsMeasuredFile); + const has = (panelId: string | null) => listed.some((panel) => panel.panelId === panelId); + if (has(entry.currentPanelId)) return entry.currentPanelId; + if (has(entry.pinnedPanelId)) return entry.pinnedPanelId; + return [...listed].sort(byRecency)[0]?.panelId ?? null; +} + +function panelSummary( + panel: ManifestPanel, + entry: ManifestCountry, + chosen: ManifestPanel | undefined, +): ReleaseHistoryPanelSummary { + return { + panelId: panel.panelId, + engine: { + policyengine: text(panel.engine?.policyengine), + model: text(panel.engine?.model), + core: text(panel.engine?.core), + }, + specSha256: panel.specSha256, + producerVersion: panel.producerVersion, + createdAt: panel.createdAt, + pinnedAt: panel.pinnedAt, + pinned: entry.pinnedPanelId === panel.panelId, + served: entry.currentPanelId === panel.panelId, + complete: panel.complete, + coverage: panel.coverage, + sameDefinitionAsDefault: + panel.specSha256 === (chosen?.specSha256 ?? null) && + panel.producerVersion === (chosen?.producerVersion ?? null), + }; +} + +/** A country's panels and the one the page opens, from the manifest. */ +export function releaseHistorySummary( + country: string, + manifest: ReleaseHistoryManifest | null, +): ReleaseHistorySummary { + const entry = + manifest && Object.hasOwn(manifest.countries, country) ? manifest.countries[country] : undefined; + const chosenId = defaultPanelId(entry); + if (!entry || chosenId === null) { + return { + country, + available: false, + updatedAt: manifest?.updatedAt ?? null, + defaultPanelId: null, + pinnedPanelId: entry?.pinnedPanelId ?? null, + servedPanelId: entry?.currentPanelId ?? null, + panels: [], + }; + } + const chosen = entry.panels[chosenId]; + const others = Object.values(entry.panels) + .filter((panel) => panel.panelId !== chosenId && holdsMeasuredFile(panel)) + .sort(byRecency); + return { + country, + available: true, + updatedAt: manifest?.updatedAt ?? null, + defaultPanelId: chosenId, + pinnedPanelId: entry.pinnedPanelId, + servedPanelId: entry.currentPanelId, + panels: [chosen, ...others].map((panel) => panelSummary(panel, entry, chosen)), + }; +} + +// --------------------------------------------------------------------------- +// Presentation: what `panel.json` says about a panel's outputs + +/** A baseline item of the panel's spec: `kind` groups it, `byDecile` says it has decile rows. */ +export interface PresentationBaselineItem { + id: string; + kind: string | null; + stat: string | null; + byDecile: boolean; +} + +/** + * What the page needs from a panel's hashed spec to label, group and order its outputs. The + * timeline holds none of it. Reform labels are not here: they come with the timeline. + */ +export interface PanelPresentation { + currency: string | null; + /** How a period is named: 2026 is "2026-27" for a fiscal year. */ + periodLabel: "fiscal_year" | "calendar_year"; + periods: number[]; + baseline: PresentationBaselineItem[]; + /** Reform ids, in the spec's order. */ + reforms: string[]; + povertyMeasures: string[]; + groups: string[]; + disclosure: { policy: string | null; minSourceHouseholds: number | null }; +} + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +function list(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +/** The presentation of a panel; an absent or unreadable `panel.json` gives empty lists. */ +export function panelPresentation(panel: PanelDocument | null): PanelPresentation { + const definition = record(panel?.definition); + const variables = record(definition.variables); + const disclosure = record(definition.disclosure); + const baseline = list(definition.baseline).flatMap((item): PresentationBaselineItem[] => { + const entry = record(item); + const id = text(entry.id); + return id + ? [{ id, kind: text(entry.kind), stat: text(entry.stat), byDecile: text(entry.by) !== null }] + : []; + }); + return { + currency: text(definition.currency), + periodLabel: definition.period_label === "fiscal_year" ? "fiscal_year" : "calendar_year", + periods: list(definition.periods).filter((period): period is number => Number.isInteger(period)), + baseline, + reforms: list(definition.reforms).flatMap((reform) => { + const id = text(record(reform).id); + return id ? [id] : []; + }), + povertyMeasures: Object.keys(record(variables.poverty)), + groups: Object.keys(record(variables.groups)), + disclosure: { + policy: text(disclosure.policy), + minSourceHouseholds: + typeof disclosure.min_source_households === "number" ? disclosure.min_source_households : null, + }, + }; +} + +/** One panel as the page loads it: its summary, its presentation and its whole timeline. */ +export interface ReleaseHistoryPanelView { + country: string; + panelId: string; + panel: ReleaseHistoryPanelSummary; + presentation: PanelPresentation; + timeline: Timeline; +} diff --git a/frontend/lib/microcosm/test-support/release-history-fixture-store.ts b/frontend/lib/microcosm/test-support/release-history-fixture-store.ts new file mode 100644 index 00000000..f9b05cfe --- /dev/null +++ b/frontend/lib/microcosm/test-support/release-history-fixture-store.ts @@ -0,0 +1,97 @@ +// Test support: an in-memory release history store filled from the producer's committed +// fixtures (release_history/tests/fixtures//, each country's spec on a synthetic world), +// laid out and finalized as a run of the default branch would leave it. +import { readdir, readFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { + countryFilePath, + encodeDocument, + finalizeCountry, + memoryStore, + panelPrefix, + updateManifestCountry, + type MeasurementDocument, + type PanelDocument, + type PanelSummary, + type SeriesRecord, + type Timeline, +} from "../release-history-store"; + +const RELEASE_HISTORY = join(import.meta.dir, "..", "..", "..", "..", "release_history"); +export const RELEASE_HISTORY_FIXTURES = join(RELEASE_HISTORY, "tests", "fixtures"); +export const FIXTURE_FINALIZED_AT = "2026-11-12T00:00:00Z"; + +async function readFixture(...parts: string[]): Promise { + return JSON.parse(await readFile(join(...parts), "utf8")) as T; +} + +/** A panel's manifest summary, as `scripts/release-history.ts` writes it at finalize. */ +export function manifestPanelSummary(panel: PanelDocument): PanelSummary { + return { + panelId: panel.panel_id, + engine: { + policyengine: panel.engine.policyengine, + model: `${panel.engine.model.name}==${panel.engine.model.version}`, + core: `${panel.engine.core.name}==${panel.engine.core.version}`, + }, + specSha256: panel.spec_sha256, + producerVersion: panel.producer_version, + }; +} + +export interface CountryFixture { + panel: PanelDocument; + series: SeriesRecord; + points: MeasurementDocument[]; + timeline: Timeline; +} + +export async function readCountryFixture(country: string): Promise { + const folder = join(RELEASE_HISTORY_FIXTURES, country); + const points: MeasurementDocument[] = []; + for (const name of (await readdir(join(folder, "points"))).sort()) { + points.push(await readFixture(folder, "points", name)); + } + return { + panel: await readFixture(folder, "panel.json"), + series: await readFixture(folder, "series.json"), + points, + timeline: await readFixture(folder, "timeline.json"), + }; +} + +/** The store after one backfill of each country on the default branch. */ +export async function fixtureStore(countries: readonly string[] = ["uk", "us"]) { + const store = memoryStore(); + const fixtures: Record = {}; + for (const country of countries) { + const fixture = await readCountryFixture(country); + fixtures[country] = fixture; + const folder = join(RELEASE_HISTORY_FIXTURES, country); + const write = (path: string, document: unknown) => + store.write(path, encodeDocument(document), "replace", false); + await write(countryFilePath(country, "series"), fixture.series); + await write(countryFilePath(country, "labels"), await readFixture(folder, "labels.json")); + await write( + countryFilePath(country, "references"), + await readFixture(RELEASE_HISTORY, "countries", country, "references.lock.json"), + ); + const prefix = panelPrefix(country, fixture.panel.panel_id); + await write(`${prefix}panel.json`, fixture.panel); + for (const point of fixture.points) await write(`${prefix}${point.measurement_id}.json`, point); + await write(`${prefix}timeline.json`, fixture.timeline); + await updateManifestCountry(store, country, (entry) => + finalizeCountry({ + entry, + panel: manifestPanelSummary(fixture.panel), + series: fixture.series, + mode: "backfill", + planned: [], + stored: fixture.points, + pin: true, + at: FIXTURE_FINALIZED_AT, + }), FIXTURE_FINALIZED_AT); + } + return { store, fixtures }; +} From 53a50484689cde314c9b4e45eb4e3bd1cca9da10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:49:03 +0000 Subject: [PATCH 3/6] Add the release history page's logic, and a synthetic store to build and test it on No production data exists while the page is built, so the logic is tested on a synthetic store: each country's committed fixtures and a seeded generator, put through the real finalize and timeline code. Everything here is pure. - Outputs: each one gets a label, a group and a place in the order from its id and the panel's spec (receipts, spending, caseloads, population, incomes, poverty rates, then one group per reform), in neutral words. An entry holds one output's own values across builds, with every number removed from a cell or a step that is not `ok`, so nothing further down can show or derive a withheld value. Nothing adds or compares two outputs. - Chart layout: one column per build in publish order; Relative places each value as a percentage of the output's official figure and Absolute places the values; an output with no official figure is drawn in values under both. A build with no value keeps its column, shaded and labelled with why (withheld, not measured, gap, retrying, failed, withdrawn), so the axis is the same on every engine. A line joins two builds only where the timeline has a step. A withdrawn build's value is a hollow marker no line joins. - What moved: outputs ranked by their step beside their own typical step, the median of their earlier steps. A republished file is left out of that median, an output with fewer than three earlier steps is ranked after by the size of its step, and a step beside a withheld cell is counted and never ranked. A step is "nearer to" or "further from" the official figure. - Builds: the marks on the time axis (a new build engine, a republished file, a withdrawn build), the builds an engine has no run for by why, and the facts of a step's two builds with links to their Microcosm commits. - The page's state in its URL: the engine's panel, the output, the scale, the open step. Defaults are never written. - `scripts/release-history-dev-store.ts --out ` writes the synthetic store for `RELEASE_HISTORY_LOCAL_DIR`: the UK part-way through an engine bump, the US with a second engine's panel under another definition. Co-Authored-By: Claude Fable 5.2 --- .../microcosm/release-history-builds.test.ts | 154 +++++ .../lib/microcosm/release-history-builds.ts | 215 +++++++ .../microcosm/release-history-chart.test.ts | 208 +++++++ .../lib/microcosm/release-history-chart.ts | 260 ++++++++ .../microcosm/release-history-format.test.ts | 96 +++ .../lib/microcosm/release-history-format.ts | 161 +++++ .../microcosm/release-history-moved.test.ts | 169 ++++++ .../lib/microcosm/release-history-moved.ts | 162 +++++ .../microcosm/release-history-outputs.test.ts | 180 ++++++ .../lib/microcosm/release-history-outputs.ts | 296 +++++++++ .../lib/microcosm/release-history-url.test.ts | 69 +++ frontend/lib/microcosm/release-history-url.ts | 63 ++ .../release-history-small-timeline.ts | 94 +++ .../release-history-synthetic-store.ts | 570 ++++++++++++++++++ .../release-history-synthetic-view.ts | 18 + .../scripts/release-history-dev-store.test.ts | 72 +++ frontend/scripts/release-history-dev-store.ts | 39 ++ 17 files changed, 2826 insertions(+) create mode 100644 frontend/lib/microcosm/release-history-builds.test.ts create mode 100644 frontend/lib/microcosm/release-history-builds.ts create mode 100644 frontend/lib/microcosm/release-history-chart.test.ts create mode 100644 frontend/lib/microcosm/release-history-chart.ts create mode 100644 frontend/lib/microcosm/release-history-format.test.ts create mode 100644 frontend/lib/microcosm/release-history-format.ts create mode 100644 frontend/lib/microcosm/release-history-moved.test.ts create mode 100644 frontend/lib/microcosm/release-history-moved.ts create mode 100644 frontend/lib/microcosm/release-history-outputs.test.ts create mode 100644 frontend/lib/microcosm/release-history-outputs.ts create mode 100644 frontend/lib/microcosm/release-history-url.test.ts create mode 100644 frontend/lib/microcosm/release-history-url.ts create mode 100644 frontend/lib/microcosm/test-support/release-history-small-timeline.ts create mode 100644 frontend/lib/microcosm/test-support/release-history-synthetic-store.ts create mode 100644 frontend/lib/microcosm/test-support/release-history-synthetic-view.ts create mode 100644 frontend/scripts/release-history-dev-store.test.ts create mode 100644 frontend/scripts/release-history-dev-store.ts diff --git a/frontend/lib/microcosm/release-history-builds.test.ts b/frontend/lib/microcosm/release-history-builds.test.ts new file mode 100644 index 00000000..9f0e6d98 --- /dev/null +++ b/frontend/lib/microcosm/release-history-builds.test.ts @@ -0,0 +1,154 @@ +import { expect, test } from "bun:test"; + +import { + buildFacts, + buildMarks, + buildStateLabel, + buildsWithoutRun, + compatibleModelsLabel, + packageLabel, + stepFacts, + withoutRunCount, +} from "./release-history-builds"; +import { dateShort } from "./release-history-format"; +import type { TimelineBuild } from "./release-history-store"; +import { smallTimeline } from "./test-support/release-history-small-timeline"; +import { syntheticPanelView } from "./test-support/release-history-synthetic-view"; + +const dates = (builds: readonly TimelineBuild[]) => builds.map((build) => dateShort(build.publishedAt)); + +test("the time axis marks a new build engine, a republished file and a withdrawn build", async () => { + const { timeline } = await syntheticPanelView("uk"); + const marks = buildMarks(timeline.builds); + const marked = timeline.builds.flatMap((build, index) => + marks[index].length > 0 ? [[dateShort(build.publishedAt), ...marks[index]]] : [] + ); + expect(marked).toEqual([ + ["21 Oct", "same_file"], + ["29 Oct", "withdrawn"], + // The first build made with another model version than the build before it. + ["2 Nov", "new_build_engine"], + ]); + + // On the newer engine the withdrawn build holds no point, and the mark still falls on 2 Nov. + const newer = await syntheticPanelView("uk", "newer"); + expect(buildMarks(newer.timeline.builds).map((list) => list.join("+"))).toEqual(marks.map((list) => list.join("+"))); +}); + +test("a timeline written before it carried build facts has no build-engine mark and no facts", async () => { + const { timeline } = await syntheticPanelView("uk"); + const earlier = timeline.builds.map(({ declared: _declared, ...build }) => build as TimelineBuild); + expect(buildMarks(earlier).flat()).toEqual(["same_file", "withdrawn"]); + expect(buildFacts(earlier[0])).toMatchObject({ declared: false, builtWithModel: null, codeCommit: null, commitUrl: null }); +}); + +test("the builds an engine has no run for are named by why, and a withdrawn build is not among them", async () => { + const served = buildsWithoutRun((await syntheticPanelView("uk")).timeline.builds); + expect(served.onAxis).toBe(11); + expect(dates(served.neverRun)).toEqual(["17 Nov", "24 Nov"]); + expect(dates(served.refused)).toEqual(["24 Oct"]); + expect([served.retrying, served.failed]).toEqual([[], []]); + expect(withoutRunCount(served)).toBe(3); + + const pinned = buildsWithoutRun((await syntheticPanelView("uk", "newer")).timeline.builds); + // The build withdrawn before the bump was never measured on the newer engine, by design. + expect(pinned.neverRun).toEqual([]); + expect(dates(pinned.failed)).toEqual(["5 Nov"]); + expect(pinned.failed[0].reason).toBe("exceeds_runner_budget"); + expect(dates(pinned.retrying)).toEqual(["24 Nov"]); + expect(dates(pinned.refused)).toEqual(["24 Oct"]); + + const complete = buildsWithoutRun((await syntheticPanelView("us")).timeline.builds); + expect(withoutRunCount(complete)).toBe(0); + const other = buildsWithoutRun((await syntheticPanelView("us", "other")).timeline.builds); + expect(other.neverRun).toHaveLength(4); +}); + +test("a build's state reads in the page's words", () => { + expect(buildStateLabel({ state: "measured", status: "ok" })).toBe("Measured"); + expect(buildStateLabel({ state: "measured", status: "partial" })).toBe("Partial"); + expect(buildStateLabel({ state: "gap", status: "refused" })).toBe("Gap"); + expect(buildStateLabel({ state: "retrying", status: null })).toBe("Retrying"); + expect(buildStateLabel({ state: "failed", status: null })).toBe("Failed"); + expect(buildStateLabel({ state: "missing", status: null })).toBe("Not measured"); +}); + +test("a step's card holds the facts of its two builds, and its neighbour is never a withdrawn build", async () => { + const { timeline } = await syntheticPanelView("uk"); + const index = timeline.builds.findIndex((build) => dateShort(build.publishedAt) === "2 Nov"); + const step = stepFacts(timeline.builds, index)!; + expect(timeline.builds[index - 1].withdrawn).toBe(true); + expect(step.from!.build.buildId).toBe(timeline.builds[index - 2].buildId); + expect(step.noStepReason).toBeNull(); + expect(step.to).toMatchObject({ + declared: true, + fetchedThrough: null, + builtWithModel: "policyengine-uk 0.10.0", + builtWithCore: "policyengine-core 3.33.3", + compatibleModels: "policyengine-uk ==0.10.0", + codeRepository: "PolicyEngine/microcosm", + nTargets: 1214, + targetRegistryVersion: "2026.10", + householdWeightYear: "2024", + }); + expect(step.from).toMatchObject({ builtWithModel: "policyengine-uk 0.9.0", nTargets: 1200 }); + expect(step.to.commitUrl).toBe(`https://github.com/PolicyEngine/microcosm/commit/${step.to.codeCommit}`); + expect(step.compareUrl).toBe( + `https://github.com/PolicyEngine/microcosm/compare/${step.from!.codeCommit}...${step.to.codeCommit}`, + ); + expect(step).toMatchObject({ + buildEngineChanged: true, + targetSetChanged: true, + targetRegistryChanged: false, + columnsAdded: ["synthetic_new_column"], + columnsRemoved: [], + }); + // The next step keeps the engine and the target set. + expect(stepFacts(timeline.builds, index + 1)).toMatchObject({ + buildEngineChanged: false, + targetSetChanged: false, + columnsAdded: [], + compareUrl: expect.stringContaining("/compare/"), + }); +}); + +test("a build that cannot have a step says why", async () => { + const { timeline } = await syntheticPanelView("uk"); + const reason = (date: string) => + stepFacts(timeline.builds, timeline.builds.findIndex((build) => dateShort(build.publishedAt) === date))!.noStepReason; + expect(stepFacts(timeline.builds, 0)).toMatchObject({ from: null, noStepReason: "This is the first build of the series." }); + expect(reason("29 Oct")).toBe("This build was withdrawn, so no step starts or ends at it."); + expect(reason("24 Oct")).toBe("This engine holds no value for this build."); + expect(reason("27 Oct")).toBe("This engine holds no value for the build before it."); + expect(reason("17 Nov")).toBe("This engine holds no value for this build."); + expect(stepFacts(timeline.builds, 99)).toBeNull(); + // The republished file's facts are those of the build its point was fetched through. + const republished = stepFacts(timeline.builds, 2)!; + expect(republished.to.fetchedThrough).toBe(timeline.builds[1].buildId); + expect(republished).toMatchObject({ noStepReason: null, compareUrl: null, targetSetChanged: false }); +}); + +test("links to GitHub are made only from a repository and a commit that look like ones", () => { + const [build] = smallTimeline({ builds: [{}], outputs: { "baseline/tax": ["currency", [1]] } }).builds; + const declaring = (codeRepository: string | null, codeCommit: string | null): TimelineBuild => ({ + ...build, + declared: { ...build.declared!, codeRepository, codeCommit }, + }); + expect(buildFacts(declaring("PolicyEngine/microcosm", "a".repeat(40))).commitUrl) + .toBe(`https://github.com/PolicyEngine/microcosm/commit/${"a".repeat(40)}`); + expect(buildFacts(declaring("javascript:alert(1)//x/y", "a".repeat(40))).commitUrl).toBeNull(); + expect(buildFacts(declaring("PolicyEngine/microcosm", "main; rm -rf")).commitUrl).toBeNull(); + expect(buildFacts(declaring(null, "a".repeat(40))).commitUrl).toBeNull(); +}); + +test("packages and declared ranges are read from whatever shape the manifest gave them", () => { + expect(packageLabel({ name: "policyengine-uk", version: "2.174.1" })).toBe("policyengine-uk 2.174.1"); + expect(packageLabel("policyengine-uk==2.174.1")).toBe("policyengine-uk 2.174.1"); + expect(packageLabel({ name: "policyengine-uk" })).toBe("policyengine-uk"); + expect(packageLabel(null)).toBeNull(); + expect(packageLabel(["policyengine-uk"])).toBeNull(); + expect(compatibleModelsLabel([{ name: "policyengine-uk", specifier: ">=2,<3" }, { name: "policyengine-core" }])) + .toBe("policyengine-uk >=2,<3, policyengine-core"); + expect(compatibleModelsLabel("anything")).toBeNull(); + expect(compatibleModelsLabel([])).toBeNull(); +}); diff --git a/frontend/lib/microcosm/release-history-builds.ts b/frontend/lib/microcosm/release-history-builds.ts new file mode 100644 index 00000000..0e04f10e --- /dev/null +++ b/frontend/lib/microcosm/release-history-builds.ts @@ -0,0 +1,215 @@ +/** + * What the release history page says about the builds of a timeline + * (calibration-diagnostics#224): the marks on the time axis, the builds an engine has no run + * for, and the facts of a step's two builds. Everything comes from the timeline's `builds`: + * listing facts, the file's state on the panel, and what each build declares. No value of any + * output is read here. + */ +import type { TimelineBuild } from "./release-history-store"; + +/** + * A mark on the time axis. `new_build_engine`: the file was built with another model version + * than the build before it. `same_file`: the build publishes an earlier build's file. + * `withdrawn`: the publisher withdrew the build. + */ +export type BuildMark = "new_build_engine" | "same_file" | "withdrawn"; + +export const BUILD_MARK_LABELS: Readonly> = { + new_build_engine: "New build engine", + same_file: "Same file as an earlier build", + withdrawn: "Withdrawn", +}; + +/** A package as a manifest names it (`{name, version}`, or a pin as text): "name version". */ +export function packageLabel(value: unknown): string | null { + if (typeof value === "string" && value.trim()) return value.replace("==", " "); + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + const { name, version } = value as { name?: unknown; version?: unknown }; + if (typeof name === "string" && typeof version === "string") return `${name} ${version}`; + if (typeof name === "string") return name; + } + return null; +} + +/** The range of models a build declares: "policyengine-uk ==2.174.1". */ +export function compatibleModelsLabel(value: unknown): string | null { + if (!Array.isArray(value)) return null; + const ranges = value.flatMap((item) => { + const { name, specifier } = (item ?? {}) as { name?: unknown; specifier?: unknown }; + return typeof name === "string" ? [`${name} ${typeof specifier === "string" ? specifier : ""}`.trim()] : []; + }); + return ranges.length > 0 ? ranges.join(", ") : null; +} + +function plain(value: unknown): string | null { + if (typeof value === "string" && value.trim()) return value; + return typeof value === "number" && Number.isFinite(value) ? String(value) : null; +} + +/** Each build's marks, in the order of the timeline's builds. */ +export function buildMarks(builds: readonly TimelineBuild[]): BuildMark[][] { + let previousEngine: string | null = null; + return builds.map((build) => { + const marks: BuildMark[] = []; + const engine = packageLabel(build.declared?.builtWithModel); + // A republished file was built once, and a withdrawn build is no neighbour: neither starts + // or ends a change of build engine. + if (engine !== null && build.sameFileAs === null && !build.withdrawn) { + if (previousEngine !== null && engine !== previousEngine) marks.push("new_build_engine"); + previousEngine = engine; + } + if (build.sameFileAs !== null) marks.push("same_file"); + if (build.withdrawn) marks.push("withdrawn"); + return marks; + }); +} + +/** + * The builds on the axis this panel holds no value for, by why: never run on this engine, a run + * that failed and will be tried again, one that ran out of attempts, or a file the producer + * refused (a gap on every engine). A withdrawn build is never measured, so it is not listed. + */ +export interface BuildsWithoutRun { + neverRun: TimelineBuild[]; + retrying: TimelineBuild[]; + failed: TimelineBuild[]; + refused: TimelineBuild[]; + /** Builds on the axis: listed, with a file, not withdrawn. */ + onAxis: number; +} + +export function buildsWithoutRun(builds: readonly TimelineBuild[]): BuildsWithoutRun { + const axis = builds.filter((build) => !build.withdrawn); + const inState = (state: TimelineBuild["state"]) => axis.filter((build) => build.state === state); + return { + neverRun: inState("missing"), + retrying: inState("retrying"), + failed: inState("failed"), + refused: inState("gap"), + onAxis: axis.length, + }; +} + +export function withoutRunCount(without: BuildsWithoutRun): number { + return without.neverRun.length + without.retrying.length + without.failed.length + without.refused.length; +} + +/** One build's state on the panel, in the page's words. */ +export function buildStateLabel(build: Pick): string { + if (build.state === "measured") return build.status === "partial" ? "Partial" : "Measured"; + return { gap: "Gap", retrying: "Retrying", failed: "Failed", missing: "Not measured" }[build.state]; +} + +const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; +const COMMIT = /^[0-9a-f]{7,40}$/; + +function commitUrl(repository: string | null | undefined, commit: string | null | undefined): string | null { + return repository && commit && REPOSITORY.test(repository) && COMMIT.test(commit) + ? `https://github.com/${repository}/commit/${commit}` + : null; +} + +/** What one build declares, ready to show. Null fields are facts the build does not declare. */ +export interface BuildFacts { + build: TimelineBuild; + /** False for a timeline written before it carried build facts, or a build with no point. */ + declared: boolean; + /** Another build's id when the point was fetched through it: two builds, one file. */ + fetchedThrough: string | null; + builtAt: string | null; + builtWithModel: string | null; + builtWithCore: string | null; + compatibleModels: string | null; + codeRepository: string | null; + codeCommit: string | null; + commitUrl: string | null; + nTargets: number | null; + targetSurfaceSha256: string | null; + targetRegistryVersion: string | null; + householdWeightYear: string | null; +} + +export function buildFacts(build: TimelineBuild): BuildFacts { + const declared = build.declared ?? null; + return { + build, + declared: declared !== null, + fetchedThrough: declared && declared.fetchedThrough !== build.buildId ? declared.fetchedThrough : null, + builtAt: declared?.builtAt ?? null, + builtWithModel: packageLabel(declared?.builtWithModel), + builtWithCore: packageLabel(declared?.builtWithCore), + compatibleModels: compatibleModelsLabel(declared?.compatibleModels), + codeRepository: declared?.codeRepository ?? null, + codeCommit: declared?.codeCommit ?? null, + commitUrl: commitUrl(declared?.codeRepository, declared?.codeCommit), + nTargets: declared?.nTargets ?? null, + targetSurfaceSha256: declared?.targetSurfaceSha256 ?? null, + targetRegistryVersion: plain(declared?.targetRegistryVersion), + householdWeightYear: plain(declared?.householdWeightYear), + }; +} + +/** Whether two facts differ; null when either build does not declare the fact. */ +function changed(from: T | null, to: T | null): boolean | null { + return from === null || to === null ? null : from !== to; +} + +/** + * A step's two builds: the build it ends at, and its neighbour, the build before it on the axis + * (withdrawn builds are never neighbours). `noStepReason` says why no output has a step to this + * build, when none can. + */ +export interface StepFacts { + to: BuildFacts; + from: BuildFacts | null; + noStepReason: string | null; + /** GitHub's comparison of the two builds' Microcosm commits. */ + compareUrl: string | null; + buildEngineChanged: boolean | null; + targetSetChanged: boolean | null; + targetRegistryChanged: boolean | null; + /** Columns the reference model does not define, in one build and not the other. */ + columnsAdded: string[]; + columnsRemoved: string[]; +} + +function neighbourBefore(builds: readonly TimelineBuild[], index: number): TimelineBuild | null { + for (let before = index - 1; before >= 0; before -= 1) { + if (!builds[before].withdrawn) return builds[before]; + } + return null; +} + +function noStepReason(to: TimelineBuild, from: TimelineBuild | null): string | null { + if (to.withdrawn) return "This build was withdrawn, so no step starts or ends at it."; + if (!from) return "This is the first build of the series."; + if (to.state !== "measured") return "This engine holds no value for this build."; + if (from.state !== "measured") return "This engine holds no value for the build before it."; + return null; +} + +export function stepFacts(builds: readonly TimelineBuild[], index: number): StepFacts | null { + const build = builds[index]; + if (!build) return null; + const neighbour = build.withdrawn ? null : neighbourBefore(builds, index); + const to = buildFacts(build); + const from = neighbour ? buildFacts(neighbour) : null; + const sameRepository = from !== null && from.codeRepository !== null && from.codeRepository === to.codeRepository; + const fromColumns = new Set(neighbour?.unknownColumns ?? []); + const toColumns = new Set(build.unknownColumns ?? []); + const comparable = neighbour?.unknownColumns != null && build.unknownColumns != null; + return { + to, + from, + noStepReason: noStepReason(build, neighbour), + compareUrl: + sameRepository && from.commitUrl && to.commitUrl && from.codeCommit !== to.codeCommit + ? `https://github.com/${to.codeRepository}/compare/${from.codeCommit}...${to.codeCommit}` + : null, + buildEngineChanged: from ? changed(from.builtWithModel, to.builtWithModel) : null, + targetSetChanged: from ? changed(from.targetSurfaceSha256, to.targetSurfaceSha256) : null, + targetRegistryChanged: from ? changed(from.targetRegistryVersion, to.targetRegistryVersion) : null, + columnsAdded: comparable ? [...toColumns].filter((column) => !fromColumns.has(column)).sort() : [], + columnsRemoved: comparable ? [...fromColumns].filter((column) => !toColumns.has(column)).sort() : [], + }; +} diff --git a/frontend/lib/microcosm/release-history-chart.test.ts b/frontend/lib/microcosm/release-history-chart.test.ts new file mode 100644 index 00000000..99e55e6c --- /dev/null +++ b/frontend/lib/microcosm/release-history-chart.test.ts @@ -0,0 +1,208 @@ +import { expect, test } from "bun:test"; + +import { buildMarks } from "./release-history-builds"; +import { chartLayout, columnBand, niceTicks, sparklinePath } from "./release-history-chart"; +import { dateShort, versusOfficial } from "./release-history-format"; +import { outputEntries, type OutputEntry } from "./release-history-outputs"; +import type { Timeline } from "./release-history-store"; +import { panelPresentation } from "./release-history-summary"; +import type { ChartScale } from "./release-history-url"; +import { smallTimeline } from "./test-support/release-history-small-timeline"; +import { syntheticPanelView } from "./test-support/release-history-synthetic-view"; + +async function ukChart(output: string, scale: ChartScale, engine: "earlier" | "newer" = "earlier", width = 960) { + const { timeline, presentation } = await syntheticPanelView("uk", engine); + const entry = outputEntries(timeline, presentation).find((candidate) => candidate.id === output)!; + const layout = chartLayout({ + builds: timeline.builds, + entry, + scale, + currency: presentation.currency, + marks: buildMarks(timeline.builds), + width, + }); + return { timeline, entry, layout }; +} + +function small(timeline: Timeline, scale: ChartScale = "relative") { + const [entry] = outputEntries(timeline, panelPresentation(null)); + return { + entry, + layout: chartLayout({ builds: timeline.builds, entry, scale, currency: "GBP", marks: buildMarks(timeline.builds), width: 600 }), + }; +} + +const at = (timeline: Timeline, date: string) => + timeline.builds.findIndex((build) => dateShort(build.publishedAt) === date); + +test("the relative view places each value as a percentage of the official figure, with the figure at 0%", async () => { + const { timeline, entry, layout } = await ukChart("baseline/income_tax", "relative"); + expect(layout).toMatchObject({ relative: true, blocked: false, empty: false }); + expect(layout.official!.label).toStartWith("0% = official £"); + expect(layout.ticks.every((tick) => tick.label === "0%" || tick.label.endsWith("%"))).toBe(true); + expect(layout.ticks.some((tick) => Math.abs(tick.y - layout.official!.y) < 1e-6 && tick.label === "0%")).toBe(true); + // Two values, two heights: the higher value is drawn higher. + const [first, second] = [0, 1].map((index) => ({ + versus: versusOfficial(entry.values[index].value!, entry.official!), + y: layout.columns[index].point!.y, + })); + expect(Math.sign(first.versus - second.versus)).toBe(Math.sign(second.y - first.y)); + // The latest value is the one labelled, as a percentage; the two newest builds have no run here. + const latest = at(timeline, "10 Nov"); + expect(layout.latestLabel).toMatchObject({ x: layout.columns[latest].x, anchor: "middle" }); + expect(layout.latestLabel!.text).toMatch(/^[+−]\d+\.\d\d%$/); +}); + +test("the absolute view places the values, and keeps the official figure on the scale", async () => { + const { layout } = await ukChart("baseline/income_tax", "absolute"); + expect(layout).toMatchObject({ relative: false, blocked: false }); + expect(layout.official!.label).toStartWith("Official £"); + expect(layout.ticks.every((tick) => tick.label.startsWith("£"))).toBe(true); + expect(layout.official!.y).toBeGreaterThanOrEqual(layout.plot.top); + expect(layout.official!.y).toBeLessThanOrEqual(layout.plot.bottom); + expect(layout.latestLabel!.text).toStartWith("£"); +}); + +test("an output with no official figure is drawn in values under both views, and says the relative one could not be", async () => { + const relative = await ukChart("reform/basic_rate_plus_1p/budgetary_impact", "relative"); + expect(relative.layout).toMatchObject({ relative: false, blocked: true, official: null }); + const absolute = await ukChart("reform/basic_rate_plus_1p/budgetary_impact", "absolute"); + expect(absolute.layout).toMatchObject({ relative: false, blocked: false, official: null }); + expect(relative.layout.columns.map((column) => column.point?.y)).toEqual( + absolute.layout.columns.map((column) => column.point?.y), + ); +}); + +test("every build keeps its column: a build with no value is shaded and labelled with why", async () => { + const served = await ukChart("baseline/income_tax", "relative"); + const band = (date: string) => served.layout.columns[at(served.timeline, date)]; + expect(served.layout.columns).toHaveLength(served.timeline.builds.length); + expect(band("24 Oct")).toMatchObject({ band: "gap", point: null }); + expect(band("17 Nov")).toMatchObject({ band: "not measured", point: null }); + expect(band("24 Nov")).toMatchObject({ band: "not measured", point: null, current: true }); + expect(band("19 Oct")).toMatchObject({ band: null }); + // Measured before it was withdrawn: its column is shaded and its value is a hollow marker. + expect(band("29 Oct")).toMatchObject({ band: "withdrawn", point: { hollow: true } }); + + const pinned = await ukChart("baseline/income_tax", "relative", "newer"); + const pinnedBand = (date: string) => pinned.layout.columns[at(pinned.timeline, date)]; + // Never measured on the newer engine, which was pinned after the withdrawal. + expect(pinnedBand("29 Oct")).toMatchObject({ band: "withdrawn", point: null }); + expect(pinnedBand("5 Nov")).toMatchObject({ band: "failed", point: null }); + expect(pinnedBand("24 Nov")).toMatchObject({ band: "retrying", point: null }); + expect(pinnedBand("17 Nov")).toMatchObject({ band: null }); + // The axis is the same on both engines. + expect(pinned.layout.columns.map((column) => column.x)).toEqual(served.layout.columns.map((column) => column.x)); +}); + +test("a line joins two builds only where the timeline has a step between them", async () => { + const { timeline, layout } = await ukChart("baseline/income_tax", "relative"); + const joined = layout.segments.map((segment) => + `${dateShort(timeline.builds[segment.from].publishedAt)} → ${dateShort(timeline.builds[segment.to].publishedAt)}` + ); + expect(joined).toEqual([ + "19 Oct → 21 Oct", + // The same file, published again: a flat step. + "21 Oct → 21 Oct", + // No line into or out of the gap, and none to or from the withdrawn build: 27 Oct joins 2 Nov. + "27 Oct → 2 Nov", + "2 Nov → 5 Nov", + "5 Nov → 7 Nov", + "7 Nov → 10 Nov", + ]); + const flat = layout.segments[1]; + expect(flat.y1).toBe(flat.y2); +}); + +test("a withheld cell has a shaded column and no point, whatever the document carries", async () => { + // Withheld in some builds only: the fixture's two measured points differ in this cell. + const output = "baseline/household_net_income_mean/decile_1"; + const { timeline, entry, layout } = await ukChart(output, "absolute"); + const statuses = entry.values.map((value) => value.status); + expect(statuses).toContain("withheld"); + expect(statuses).toContain("ok"); + layout.columns.forEach((column, index) => { + if (statuses[index] !== "withheld" || timeline.builds[index].withdrawn) return; + expect(column).toMatchObject({ band: "withheld", point: null }); + }); + // No line reaches a withheld cell. + for (const segment of layout.segments) { + expect([statuses[segment.from], statuses[segment.to]]).toEqual(["ok", "ok"]); + } + + // A document that wrongly carried a number beside the withheld status draws nothing with it. + const leaking: Timeline = structuredClone(timeline); + const raw = leaking.outputs.find((candidate) => candidate.output === output)!; + const hidden = raw.values.findIndex((value) => value.status === "withheld"); + raw.values[hidden].value = 9.87e12; + const leaked = outputEntries(leaking, panelPresentation(null)).find((candidate) => candidate.id === output)!; + const drawn = chartLayout({ builds: leaking.builds, entry: leaked, scale: "absolute", currency: "GBP", marks: [], width: 960 }); + expect(drawn.columns[hidden].point).toBeNull(); + expect(drawn.ticks.map((tick) => tick.label)).toEqual(layout.ticks.map((tick) => tick.label)); +}); + +test("why a column is empty follows the build's state and the cell's status", () => { + const build = smallTimeline({ builds: [{}], outputs: { "baseline/tax": ["currency", [1]] } }).builds[0]; + expect(columnBand(build, "ok")).toBeNull(); + expect(columnBand(build, "withheld")).toBe("withheld"); + // A measured build whose point has no such cell, as after a reform that failed. + expect(columnBand(build, "missing")).toBe("no value"); + expect(columnBand({ ...build, state: "missing" }, "unmeasured")).toBe("not measured"); + expect(columnBand({ ...build, state: "gap" }, "unmeasured")).toBe("gap"); + expect(columnBand({ ...build, withdrawn: true }, "ok")).toBe("withdrawn"); +}); + +test("dates under the axis thin out where columns are narrow, and the current build always has one", async () => { + const wide = await ukChart("baseline/income_tax", "relative", "earlier", 1200); + expect(wide.layout.columns.every((column) => column.dateLabel !== null)).toBe(true); + // Twelve columns of 92px hold "not measured" on one line; narrower ones turn it on its side. + expect(wide.layout.verticalBandLabels).toBe(false); + const narrow = await ukChart("baseline/income_tax", "relative", "earlier", 360); + const labelled = narrow.layout.columns.filter((column) => column.dateLabel !== null); + expect(labelled.length).toBeLessThan(narrow.layout.columns.length); + expect(labelled.some((column) => column.current)).toBe(true); + expect(narrow.layout.verticalBandLabels).toBe(true); + // Labelled dates never sit closer than a date is wide. + for (let index = 1; index < labelled.length; index += 1) { + expect(labelled[index].x - labelled[index - 1].x).toBeGreaterThanOrEqual(46); + } + // The marks ride on their columns. + expect(wide.layout.columns[at(wide.timeline, "2 Nov")].marks).toEqual(["new_build_engine"]); +}); + +test("an output no build holds a value for has an empty chart, with its columns", () => { + const timeline = smallTimeline({ + builds: [{}, { unmeasured: true }], + outputs: { "baseline/tax": ["currency", ["withheld", null]] }, + }); + const { layout } = small(timeline); + expect(layout).toMatchObject({ empty: true, ticks: [], official: null, latestLabel: null, segments: [] }); + expect(layout.columns.map((column) => column.band)).toEqual(["withheld", "not measured"]); +}); + +test("one value still gets a scale around it", () => { + const { layout } = small(smallTimeline({ builds: [{}], outputs: { "baseline/tax": ["currency", [100]] } }), "absolute"); + expect(layout.ticks.length).toBeGreaterThan(1); + expect(layout.columns[0].point!.y).toBeGreaterThan(layout.plot.top); + expect(layout.columns[0].point!.y).toBeLessThan(layout.plot.bottom); + expect(layout.latestLabel).toMatchObject({ text: "£100", anchor: "end" }); +}); + +test("axis values are round and cover the range", () => { + expect(niceTicks(-3.2, 4.1)).toEqual({ ticks: [-4, -2, 0, 2, 4, 6], min: -4, max: 6 }); + expect(niceTicks(0, 10)).toEqual({ ticks: [0, 2.5, 5, 7.5, 10], min: 0, max: 10 }); + const flat = niceTicks(5, 5); + expect(flat.min).toBeLessThan(5); + expect(flat.max).toBeGreaterThan(5); +}); + +test("a sparkline breaks where a build holds no value and passes over a withdrawn one", async () => { + const { timeline, entry } = await ukChart("baseline/income_tax", "relative"); + const { path, last } = sparklinePath(entry, timeline.builds); + // 19 Oct to 21 Oct (twice), a break at the gap, then 27 Oct on to 10 Nov over the withdrawn build. + expect(path.match(/M/g)).toHaveLength(2); + expect(path.match(/L/g)).toHaveLength(2 + 4); + expect(last).not.toBeNull(); + const none: OutputEntry = { ...entry, values: entry.values.map((value) => ({ ...value, value: null })) }; + expect(sparklinePath(none, timeline.builds)).toEqual({ path: "", last: null }); +}); diff --git a/frontend/lib/microcosm/release-history-chart.ts b/frontend/lib/microcosm/release-history-chart.ts new file mode 100644 index 00000000..5e874b2c --- /dev/null +++ b/frontend/lib/microcosm/release-history-chart.ts @@ -0,0 +1,260 @@ +/** + * The layout of the release history chart (calibration-diagnostics#224): one output across the + * builds of a series, as positions the page draws. Pure, so the tests check it with no browser. + * + * - One column per build, in publish order. A build with no value keeps its column, shaded and + * labelled, so the axis is the same on every engine. + * - Relative: each value as a percentage above or below the output's official figure. Absolute: + * the values. An output with no official figure is drawn in values under both. + * - A line joins two builds only where the timeline has a step between them (`comparedWith`). + * - A withheld cell has a shaded column and no point: its value is never placed on the scale. + */ +import type { BuildMark } from "./release-history-builds"; +import { + dateShort, + formatPercent, + formatValue, + versusOfficial, +} from "./release-history-format"; +import type { OutputEntry } from "./release-history-outputs"; +import type { TimelineBuild } from "./release-history-store"; +import type { ChartScale } from "./release-history-url"; + +/** Why a column holds no point, in the words the chart prints on it. */ +export type ColumnBand = + | "withdrawn" + | "withheld" + | "not measured" + | "gap" + | "retrying" + | "failed" + | "no value"; + +export interface ChartColumn { + index: number; + buildId: string; + /** The column's centre, and the left edge and width of its band and hit area. */ + x: number; + left: number; + width: number; + band: ColumnBand | null; + /** The value's marker. `hollow`: a withdrawn build's value, which no step joins. */ + point: { y: number; hollow: boolean } | null; + current: boolean; + /** The publish date under the axis, where it fits. */ + dateLabel: string | null; + marks: BuildMark[]; +} + +export interface ChartLayout { + width: number; + height: number; + plot: { left: number; right: number; top: number; bottom: number }; + /** Whether the values are drawn against the official figure. */ + relative: boolean; + /** Relative was asked for, and the output has no official figure to draw against. */ + blocked: boolean; + ticks: { y: number; label: string }[]; + /** The official figure's line: at 0% in the relative view, at its value in the absolute one. */ + official: { y: number; label: string } | null; + columns: ChartColumn[]; + segments: { from: number; to: number; x1: number; y1: number; x2: number; y2: number }[]; + /** The one value the chart labels: the latest. */ + latestLabel: { x: number; y: number; text: string; anchor: "middle" | "end" } | null; + /** Whether the band labels are turned to fit narrow columns. */ + verticalBandLabels: boolean; + /** No build holds a value for this output. */ + empty: boolean; +} + +export const CHART_HEIGHT = 330; +const MARGIN = { top: 18, right: 18, bottom: 64, left: 72 }; +/** The least room a publish date needs under the axis. */ +const DATE_LABEL_WIDTH = 46; +/** Below this column width a band's label is turned on its side. */ +const HORIZONTAL_BAND_LABEL_WIDTH = 78; + +/** Round axis values that cover the range, and the range they span. */ +export function niceTicks(low: number, high: number, count = 4): { ticks: number[]; min: number; max: number } { + let min = low; + let max = high; + if (min === max) { + const pad = Math.abs(min) * 0.05 || 1; + min -= pad; + max += pad; + } + const raw = (max - min) / count; + const magnitude = 10 ** Math.floor(Math.log10(raw)); + const step = [1, 2, 2.5, 5, 10].map((multiple) => multiple * magnitude).find((size) => size >= raw) ?? 10 * magnitude; + const start = Math.floor(min / step) * step; + const end = Math.ceil(max / step) * step; + const ticks: number[] = []; + for (let tick = start; tick <= end + step / 2; tick += step) ticks.push(Number(tick.toPrecision(12))); + return { ticks, min: start, max: end }; +} + +/** As many decimals as the tick step needs, so a 2.5% step never prints as 3%. */ +function tickDecimals(ticks: number[]): number { + const step = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : 1; + const exact = (decimals: number) => Math.abs(Math.round(step * 10 ** decimals) - step * 10 ** decimals) < 1e-6; + return [0, 1, 2, 3].find(exact) ?? 3; +} + +/** Why a build's column holds no point for this output; null when it holds one. */ +export function columnBand(build: TimelineBuild, status: OutputEntry["values"][number]["status"]): ColumnBand | null { + if (build.withdrawn) return "withdrawn"; + if (status === "withheld") return "withheld"; + if (status === "ok") return null; + if (build.state === "gap") return "gap"; + if (build.state === "retrying") return "retrying"; + if (build.state === "failed") return "failed"; + return build.state === "missing" ? "not measured" : "no value"; +} + +/** Which builds get a publish date: every k-th from the newest, and always the current one. */ +function dateLabels(builds: readonly TimelineBuild[], xs: number[], step: number): (string | null)[] { + const every = Math.max(1, Math.ceil(DATE_LABEL_WIDTH / step)); + const current = builds.findIndex((build) => build.current); + return builds.map((build, index) => { + if (index === current) return dateShort(build.publishedAt); + if ((builds.length - 1 - index) % every !== 0) return null; + // A date that would touch the current build's gives way to it. + if (current !== -1 && Math.abs(xs[index] - xs[current]) < DATE_LABEL_WIDTH) return null; + return dateShort(build.publishedAt); + }); +} + +export function chartLayout(options: { + builds: readonly TimelineBuild[]; + entry: OutputEntry; + scale: ChartScale; + currency: string | null; + marks: readonly BuildMark[][]; + width: number; +}): ChartLayout { + const { builds, entry, currency } = options; + const width = Math.max(options.width, 280); + const plot = { + left: MARGIN.left, + right: width - MARGIN.right, + top: MARGIN.top, + bottom: CHART_HEIGHT - MARGIN.bottom, + }; + const official = entry.official; + const relative = options.scale === "relative" && official !== null; + // What the chart places for a stored value: the value, or its % above or below the official figure. + const placed = (value: number) => (relative && official !== null ? versusOfficial(value, official) : value); + const step = (plot.right - plot.left) / Math.max(builds.length, 1); + const xs = builds.map((_, index) => plot.left + step * (index + 0.5)); + const values = builds.map((_, index) => entry.values[index]?.value ?? null); + const known = values.filter((value): value is number => value !== null).map(placed); + const empty = known.length === 0; + + // The official figure is always in range: 0% in the relative view, its value in the absolute one. + const anchors = official === null ? [] : [placed(official)]; + const range = empty ? null : niceTicks(Math.min(...known, ...anchors), Math.max(...known, ...anchors)); + const yOf = (value: number) => + range === null + ? plot.bottom + : plot.bottom - ((value - range.min) / (range.max - range.min)) * (plot.bottom - plot.top); + const decimals = range ? tickDecimals(range.ticks) : 0; + const tickLabel = (tick: number) => + relative ? formatPercent(tick, decimals) : formatValue(tick, entry.unit, currency, 1); + + const dates = dateLabels(builds, xs, step); + const columns = builds.map((build, index): ChartColumn => { + const value = values[index]; + return { + index, + buildId: build.buildId, + x: xs[index], + left: xs[index] - step / 2, + width: step, + band: columnBand(build, entry.values[index]?.status ?? "unmeasured"), + point: value === null || range === null ? null : { y: yOf(placed(value)), hollow: build.withdrawn }, + current: build.current, + dateLabel: dates[index], + marks: [...(options.marks[index] ?? [])], + }; + }); + + const indexOf = new Map(builds.map((build, index) => [build.buildId, index])); + const segments: ChartLayout["segments"] = []; + entry.values.forEach((value, to) => { + const from = value.comparedWith === null ? undefined : indexOf.get(value.comparedWith); + if (from === undefined) return; + const start = columns[from]?.point; + const end = columns[to]?.point; + if (!start || !end) return; + segments.push({ from, to, x1: columns[from].x, y1: start.y, x2: columns[to].x, y2: end.y }); + }); + + let latestLabel: ChartLayout["latestLabel"] = null; + for (let index = columns.length - 1; index >= 0 && latestLabel === null; index -= 1) { + const value = values[index]; + const point = columns[index].point; + // A withdrawn build's value is drawn, hollow, and never labelled as the latest. + if (value === null || point === null || point.hollow) continue; + latestLabel = { + x: columns[index].x, + y: point.y - 12, + text: relative && official !== null + ? formatPercent(versusOfficial(value, official), 2) + : formatValue(value, entry.unit, currency), + anchor: index === columns.length - 1 ? "end" : "middle", + }; + } + + return { + width, + height: CHART_HEIGHT, + plot, + relative, + blocked: options.scale === "relative" && official === null, + ticks: range ? range.ticks.map((tick) => ({ y: yOf(tick), label: tickLabel(tick) })) : [], + official: + official === null || range === null + ? null + : { + y: yOf(placed(official)), + label: `${relative ? "0% = official " : "Official "}${formatValue(official, entry.unit, currency)}`, + }, + columns, + segments, + latestLabel, + verticalBandLabels: step < HORIZONTAL_BAND_LABEL_WIDTH, + empty, + }; +} + +/** + * A small line of an output's values across the builds, broken where a build on the axis holds + * none. A withdrawn build is passed over, as on the chart: no step starts or ends at it. + */ +export function sparklinePath( + entry: OutputEntry, + builds: ReadonlyArray>, + size: { width: number; height: number } = { width: 56, height: 18 }, +): { path: string; last: { x: number; y: number } | null } { + const onAxis = entry.values.map((value, index) => (builds[index]?.withdrawn ? undefined : value.value)); + const known = onAxis.filter((value): value is number => typeof value === "number"); + if (known.length === 0) return { path: "", last: null }; + const min = Math.min(...known); + const span = Math.max(...known) - min || 1; + const x = (index: number) => 3 + (index * (size.width - 6)) / Math.max(onAxis.length - 1, 1); + const y = (value: number) => size.height - 3 - ((value - min) / span) * (size.height - 6); + let path = ""; + let last: { x: number; y: number } | null = null; + let joined = false; + onAxis.forEach((value, index) => { + if (value === undefined) return; + if (value === null) { + joined = false; + return; + } + path += `${joined ? "L" : "M"}${x(index).toFixed(1)} ${y(value).toFixed(1)} `; + last = { x: x(index), y: y(value) }; + joined = true; + }); + return { path: path.trim(), last }; +} diff --git a/frontend/lib/microcosm/release-history-format.test.ts b/frontend/lib/microcosm/release-history-format.test.ts new file mode 100644 index 00000000..fea39214 --- /dev/null +++ b/frontend/lib/microcosm/release-history-format.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from "bun:test"; + +import { + commonPrefix, + currencySymbol, + dateLong, + dateShort, + dateTimeUtc, + engineLabel, + formatChange, + formatPercent, + formatPoints, + formatValue, + periodLabel, + shortBuildNames, + shortHash, + versusOfficial, +} from "./release-history-format"; +import { panelPresentation } from "./release-history-summary"; +import { readCountryFixture } from "./test-support/release-history-fixture-store"; + +test("a value is written in its unit", () => { + expect(currencySymbol("GBP")).toBe("£"); + expect(currencySymbol("USD")).toBe("$"); + expect(currencySymbol(null)).toBe(""); + expect(currencySymbol("not a currency")).toBe(""); + expect(formatValue(25_589_726_500, "currency", "GBP")).toBe("£25.6bn"); + expect(formatValue(-1_234_000_000_000, "currency", "USD")).toBe("−$1.23tn"); + expect(formatValue(4_560_000, "currency", "GBP", 2)).toBe("£4.56m"); + expect(formatValue(28_400_000, "count", null)).toBe("28.40m"); + expect(formatValue(12_345, "count", null)).toBe("12,345"); + expect(formatValue(0.1834, "rate", null)).toBe("18.3%"); + expect(formatValue(-0.4212, "ratio", null)).toBe("−0.42%"); + expect(formatValue(null, "currency", "GBP")).toBe("—"); + expect(formatValue(Number.NaN, "count", null)).toBe("—"); +}); + +test("percentages and points carry their sign, and zero carries none", () => { + expect(formatPercent(2.345)).toBe("+2.35%"); + expect(formatPercent(-0.5, 1)).toBe("−0.5%"); + expect(formatPercent(0.001)).toBe("0%"); + expect(formatPercent(null)).toBe("—"); + expect(formatPoints(0.125)).toBe("+0.13 pp"); + expect(formatPoints(-1.5)).toBe("−1.50 pp"); + expect(formatPoints(0)).toBe("0 pp"); + expect(versusOfficial(110, 100)).toBeCloseTo(10); + // A negative official figure (a cost, in the model's sign): above it is still above. + expect(versusOfficial(-90, -100)).toBeCloseTo(10); +}); + +test("a step is told in percent for money and counts, in points for rates, and never beside a withheld cell", () => { + const step = { change: 120_000_000, relativeChange: 0.0045, changePoints: null, changeStatus: "ok" as const }; + expect(formatChange(step, "currency", "GBP")).toBe("+£120.00m (+0.45%)"); + expect(formatChange({ ...step, change: -3_000, relativeChange: -0.01 }, "count", null)).toBe("−3,000 (−1.00%)"); + expect(formatChange({ ...step, relativeChange: null }, "currency", "USD")).toBe("+$120.00m"); + expect(formatChange({ change: 0.002, relativeChange: null, changePoints: 0.2, changeStatus: "ok" }, "rate", null)) + .toBe("+0.20 pp"); + expect(formatChange({ change: null, relativeChange: null, changePoints: null, changeStatus: "withheld" }, "currency", "GBP")) + .toBe("Withheld"); + expect(formatChange({ change: null, relativeChange: null, changePoints: null, changeStatus: "none" }, "currency", "GBP")) + .toBe("—"); +}); + +test("a period is named as the producer names it in each country's points", async () => { + for (const country of ["uk", "us"]) { + const fixture = await readCountryFixture(country); + const style = panelPresentation(fixture.panel).periodLabel; + for (const point of fixture.points) { + for (const period of point.periods) expect(periodLabel(period.period, style)).toBe(period.label); + } + } + expect(periodLabel(2099, "fiscal_year")).toBe("2099-00"); +}); + +test("publish times are written as UTC dates", () => { + expect(dateLong("2026-10-19T08:33:00+00:00")).toBe("19 Oct 2026"); + expect(dateShort("2026-11-07T23:30:00-05:00")).toBe("8 Nov"); + expect(dateTimeUtc("2026-10-19T08:33:00+00:00")).toBe("19 Oct 2026, 08:33 UTC"); + expect(dateTimeUtc(null)).toBe("—"); + expect(dateLong("not a date")).toBe("not a date"); +}); + +test("build names drop the prefix they share, cut back to a hyphen", () => { + const builds = [ + { buildId: "line/attempt-20261019T083300Z-aaaa1111", build: "attempt-20261019T083300Z-aaaa1111" }, + { buildId: "line/attempt-20261107T020434Z-bbbb2222", build: "attempt-20261107T020434Z-bbbb2222" }, + ]; + expect(commonPrefix(builds.map((build) => build.build))).toBe("attempt-"); + expect([...shortBuildNames(builds).values()]).toEqual(["20261019T083300Z-aaaa1111", "20261107T020434Z-bbbb2222"]); + // One build, or names with nothing in common, keep their whole name. + expect(shortBuildNames([builds[0]]).get(builds[0].buildId)).toBe(builds[0].build); + expect(commonPrefix(["alpha", "beta"])).toBe(""); + expect(shortHash("abcdef0123456789")).toBe("abcdef0123"); + expect(shortHash(null)).toBe("—"); + expect(engineLabel("policyengine-uk==1.0.0")).toBe("policyengine-uk 1.0.0"); +}); diff --git a/frontend/lib/microcosm/release-history-format.ts b/frontend/lib/microcosm/release-history-format.ts new file mode 100644 index 00000000..c715fa99 --- /dev/null +++ b/frontend/lib/microcosm/release-history-format.ts @@ -0,0 +1,161 @@ +/** + * How the release history page writes numbers, dates and build names + * (calibration-diagnostics#224). Pure, so the page and its tests share it. + */ +import type { TimelineBuild, TimelineValue } from "./release-history-store"; + +export type OutputUnit = "currency" | "count" | "rate" | "ratio"; + +const MINUS = "−"; +const NONE = "—"; + +/** The currency's short symbol ("£" for GBP), or nothing when the code is unknown. */ +export function currencySymbol(currency: string | null): string { + if (!currency) return ""; + try { + const parts = new Intl.NumberFormat("en", { + style: "currency", + currency, + currencyDisplay: "narrowSymbol", + }).formatToParts(0); + return parts.find((part) => part.type === "currency")?.value ?? ""; + } catch { + return ""; + } +} + +function compact(abs: number, decimals: number): string { + if (abs >= 1e12) return `${(abs / 1e12).toFixed(2)}tn`; + if (abs >= 1e9) return `${(abs / 1e9).toFixed(decimals)}bn`; + if (abs >= 1e6) return `${(abs / 1e6).toFixed(decimals)}m`; + if (abs >= 1e4) return Math.round(abs).toLocaleString("en-GB"); + return abs.toLocaleString("en-GB", { maximumFractionDigits: abs < 10 ? 2 : 0 }); +} + +/** + * A value in its unit: money with the currency's symbol, a count, a rate (a share, shown as a + * percentage) or a ratio (already a percentage). + */ +export function formatValue( + value: number | null | undefined, + unit: OutputUnit, + currency: string | null, + decimals = 1, +): string { + if (value === null || value === undefined || !Number.isFinite(value)) return NONE; + const abs = Math.abs(value); + let text: string; + if (unit === "currency") text = `${currencySymbol(currency)}${compact(abs, decimals)}`; + else if (unit === "count") text = compact(abs, Math.max(decimals, 2)); + else if (unit === "rate") text = `${(abs * 100).toFixed(1)}%`; + else text = `${abs.toFixed(2)}%`; + return value < 0 ? `${MINUS}${text}` : text; +} + +function signed(text: string, value: number): string { + if (value < 0) return `${MINUS}${text}`; + return value > 0 ? `+${text}` : text; +} + +/** A signed percentage; a value that rounds to zero is "0%". */ +export function formatPercent(value: number | null | undefined, decimals = 2): string { + if (value === null || value === undefined || !Number.isFinite(value)) return NONE; + const text = Math.abs(value).toFixed(decimals); + return Number(text) === 0 ? "0%" : signed(`${text}%`, value); +} + +/** A signed difference in percentage points. */ +export function formatPoints(value: number | null | undefined, decimals = 2): string { + if (value === null || value === undefined || !Number.isFinite(value)) return NONE; + const text = Math.abs(value).toFixed(decimals); + return Number(text) === 0 ? "0 pp" : signed(`${text} pp`, value); +} + +/** Whether a unit's steps are told in percentage points (rates and ratios) or in percent. */ +export function stepsInPoints(unit: OutputUnit): boolean { + return unit === "rate" || unit === "ratio"; +} + +/** + * The step to a build from the build before it: "Withheld" beside a withheld cell, a dash when + * there is no step, percentage points for a rate, and the amount with its percentage otherwise. + */ +export function formatChange( + value: Pick, + unit: OutputUnit, + currency: string | null, +): string { + if (value.changeStatus === "withheld") return "Withheld"; + if (value.changeStatus !== "ok" || value.change === null) return NONE; + if (stepsInPoints(unit)) return formatPoints(value.changePoints); + const amount = signed(formatValue(Math.abs(value.change), unit, currency, 2), value.change); + return value.relativeChange === null + ? amount + : `${amount} (${formatPercent(value.relativeChange * 100)})`; +} + +/** A value as a percentage above or below the output's official figure. */ +export function versusOfficial(value: number, official: number): number { + return ((value - official) / Math.abs(official)) * 100; +} + +/** A period's name: 2026 is "2026-27" for a fiscal year, as the producer labels it. */ +export function periodLabel(period: number, style: "fiscal_year" | "calendar_year"): string { + return style === "fiscal_year" + ? `${period}-${String((period + 1) % 100).padStart(2, "0")}` + : String(period); +} + +function utc(iso: string, options: Intl.DateTimeFormatOptions): string { + const time = Date.parse(iso); + if (Number.isNaN(time)) return iso; + return new Date(time).toLocaleString("en-GB", { ...options, timeZone: "UTC" }); +} + +/** "19 Oct 2026": publish times are shown as UTC dates, the same for every reader. */ +export function dateLong(iso: string): string { + return utc(iso, { day: "numeric", month: "short", year: "numeric" }); +} + +/** "19 Oct". */ +export function dateShort(iso: string): string { + return utc(iso, { day: "numeric", month: "short" }); +} + +/** "19 Oct 2026, 08:33 UTC". */ +export function dateTimeUtc(iso: string | null | undefined): string { + if (!iso) return NONE; + const date = dateLong(iso); + const time = utc(iso, { hour: "2-digit", minute: "2-digit", hour12: false }); + return date === iso ? iso : `${date}, ${time} UTC`; +} + +/** What every name starts with, cut back to a hyphen so a name is never cut mid-word. */ +export function commonPrefix(names: readonly string[]): string { + if (names.length < 2) return ""; + let prefix = names[0]; + for (const name of names.slice(1)) { + while (!name.startsWith(prefix)) prefix = prefix.slice(0, -1); + } + const cut = prefix.lastIndexOf("-"); + return cut > 0 ? prefix.slice(0, cut + 1) : ""; +} + +/** + * Builds of one series share a long prefix: each build's name without it, by build id. The full + * id stays available as a title. + */ +export function shortBuildNames(builds: ReadonlyArray>): Map { + const prefix = commonPrefix(builds.map((build) => build.build)); + return new Map(builds.map((build) => [build.buildId, build.build.slice(prefix.length) || build.build])); +} + +/** A digest or commit, shortened for display. */ +export function shortHash(value: string | null | undefined, length = 10): string { + return value ? value.slice(0, length) : NONE; +} + +/** "policyengine-uk==2.174.1" as "policyengine-uk 2.174.1". */ +export function engineLabel(pin: string | null | undefined): string { + return pin ? pin.replace("==", " ") : "an unnamed engine"; +} diff --git a/frontend/lib/microcosm/release-history-moved.test.ts b/frontend/lib/microcosm/release-history-moved.test.ts new file mode 100644 index 00000000..5cc61cdd --- /dev/null +++ b/frontend/lib/microcosm/release-history-moved.test.ts @@ -0,0 +1,169 @@ +import { expect, test } from "bun:test"; + +import { + latestMeasuredBuild, + stepOf, + stepSummary, + typicalStep, +} from "./release-history-moved"; +import { outputEntries } from "./release-history-outputs"; +import { panelPresentation } from "./release-history-summary"; +import { smallTimeline } from "./test-support/release-history-small-timeline"; +import { syntheticPanelView } from "./test-support/release-history-synthetic-view"; + +const PRESENTATION = panelPresentation(null); + +function ranked() { + const timeline = smallTimeline({ + builds: [{}, {}, {}, {}, {}], + outputs: { + "baseline/steady": ["currency", [100, 101, 100, 101, 106.05]], + "baseline/jumpy": ["currency", [100, 110, 99, 109, 120]], + "baseline/young": ["currency", [null, null, 100, 102, 110]], + "baseline/hidden": ["currency", [50, 51, 52, 53, "withheld"]], + "baseline/flat": ["count", [5, 5, 5, 5, 5]], + "baseline/share": ["rate", [0.1, 0.11, 0.1, 0.11, 0.14]], + "baseline/still": ["count", [7, 7, 7, 7, 8]], + "baseline/absent": ["currency", [1, 2, 3, null, null]], + }, + references: { + baseline: { + steady: { status: "resolved", value: 110, sign: 1 }, + jumpy: { status: "resolved", value: 100, sign: 1 }, + }, + reforms: {}, + }, + }); + return { timeline, entries: outputEntries(timeline, PRESENTATION) }; +} + +test("outputs are ranked by their step beside their own typical step, not by its size", () => { + const { timeline, entries } = ranked(); + const summary = stepSummary(entries, timeline.builds, 4); + expect(summary.fromBuildId).toBe("zz-national/b4"); + expect(summary.moved.map((move) => move.entry.id)).toEqual([ + // It never moved before, so any step is beyond its typical one. + "baseline/still", + // +5% beside a typical 1%. + "baseline/steady", + // +3 points beside a typical 1. + "baseline/share", + // +10%: its largest step in size, and an ordinary one for it. + "baseline/jumpy", + // One earlier step only: ranked after the others, by the size of its step. + "baseline/young", + ]); + const [still, steady, share, jumpy, young] = summary.moved; + expect(still).toMatchObject({ typical: 0, ratio: Number.POSITIVE_INFINITY, measure: "percent" }); + expect(steady.signed).toBeCloseTo(5); + expect(steady.typical).toBeCloseTo(1, 1); + expect(steady.ratio).toBeCloseTo(5, 0); + expect(share).toMatchObject({ measure: "points" }); + expect(share.signed).toBeCloseTo(3); + expect(share.ratio).toBeCloseTo(3); + expect(jumpy.ratio).toBeCloseTo(1, 0); + expect(jumpy.size).toBeGreaterThan(steady.size); + expect(young).toMatchObject({ typical: null, ratio: null }); + expect(summary).toMatchObject({ unchanged: 1, withheld: 1, noStep: 1, sameFile: false, rankedByTypical: true }); +}); + +test("a step is nearer to or further from the official figure, in those words only", () => { + const { timeline, entries } = ranked(); + const moves = new Map(stepSummary(entries, timeline.builds, 4).moved.map((move) => [move.entry.id, move.official])); + // 101 to 106.05, beside an official 110. + expect(moves.get("baseline/steady")).toMatchObject({ direction: "nearer" }); + expect(moves.get("baseline/steady")!.before).toBeCloseTo(9); + expect(moves.get("baseline/steady")!.after).toBeCloseTo(3.95); + // 109 to 120, beside an official 100. + expect(moves.get("baseline/jumpy")).toMatchObject({ direction: "further" }); + // No official figure: nothing is said. + expect(moves.get("baseline/share")).toBeNull(); +}); + +test("a withheld cell is counted and nothing else: no size, no rank, no typical step from it", () => { + const { timeline, entries } = ranked(); + const hidden = entries.find((entry) => entry.id === "baseline/hidden")!; + expect(stepOf(hidden, 4)).toBeNull(); + const summary = stepSummary(entries, timeline.builds, 4); + expect(summary.moved.some((move) => move.entry.id === "baseline/hidden")).toBe(false); + expect(summary.withheld).toBe(1); + + // A step out of a withheld cell is withheld too, and is no part of a later typical step. + const later = smallTimeline({ + builds: [{}, {}, {}, {}, {}, {}], + outputs: { "baseline/hidden": ["currency", [50, "withheld", 60, 61, 62, 70]] }, + }); + const entry = outputEntries(later, PRESENTATION)[0]; + expect(entry.values.map((value) => value.changeStatus)).toEqual(["none", "withheld", "withheld", "ok", "ok", "ok"]); + // Two published steps before the last build: too few for a typical step. + expect(typicalStep(entry, later.builds, 5)).toBeNull(); +}); + +test("a build that republishes a file moves nothing, and is left out of every typical step", () => { + const timeline = smallTimeline({ + builds: [{}, {}, { sameFileAs: 1 }, {}, {}, {}], + outputs: { "baseline/tax": ["currency", [100, 102, null, 106.08, 112.4448, 120]] }, + }); + const entries = outputEntries(timeline, PRESENTATION); + expect(timeline.builds[2].sameFileAs).toBe("zz-national/b2"); + expect(stepSummary(entries, timeline.builds, 2)).toMatchObject({ sameFile: true, moved: [], unchanged: 1 }); + // Steps of 2%, 4% and 6%: their median is 4. With the republished file's zero it would be 3. + expect(typicalStep(entries[0], timeline.builds, 5)).toBeCloseTo(4); +}); + +test("what moved speaks of the newest measured build on the axis", () => { + const timeline = smallTimeline({ + builds: [{}, {}, { withdrawn: true }, { unmeasured: true }], + outputs: { "baseline/tax": ["currency", [1, 2, 3, null]] }, + }); + expect(latestMeasuredBuild(timeline.builds)).toBe(1); + expect(latestMeasuredBuild(smallTimeline({ builds: [{ unmeasured: true }], outputs: {} }).builds)).toBeNull(); +}); + +test("a series too short for typical steps is ranked by the size of its steps", () => { + const timeline = smallTimeline({ + builds: [{}, {}, {}], + outputs: { + "baseline/small": ["currency", [100, 100, 101]], + "baseline/large": ["currency", [100, 100, 109]], + }, + }); + const summary = stepSummary(outputEntries(timeline, PRESENTATION), timeline.builds, 2); + expect(summary.rankedByTypical).toBe(false); + expect(summary.moved.map((move) => move.entry.id)).toEqual(["baseline/large", "baseline/small"]); +}); + +test("on the synthetic UK panel every output is ranked, unchanged, withheld, or has no step", async () => { + const { timeline, presentation } = await syntheticPanelView("uk"); + const entries = outputEntries(timeline, presentation); + const latest = latestMeasuredBuild(timeline.builds)!; + // The served panel never ran the two newest builds. + expect(timeline.builds[latest].publishedAt).toBe("2026-11-10T09:31:00+00:00"); + + // The build after a gap: its neighbour holds no value, so no output has a step to it. + const gap = timeline.builds.findIndex((build) => build.state === "gap"); + const afterGap = stepSummary(entries, timeline.builds, gap + 1); + expect(afterGap.moved).toEqual([]); + expect(afterGap.noStep + afterGap.withheld).toBe(entries.length); + + // The build where the target set changes: outputs moved, largest ratio first. + const index = timeline.builds.findIndex((build) => build.publishedAt === "2026-11-02T02:04:00+00:00"); + const all = stepSummary(entries, timeline.builds, index); + expect(all.moved.length + all.unchanged + all.withheld + all.noStep).toBe(entries.length); + expect(all.moved.length).toBeGreaterThan(10); + expect(all.withheld).toBeGreaterThan(0); + // The step runs from the build before the withdrawn one, which is no neighbour. + expect(timeline.builds[index - 1].withdrawn).toBe(true); + expect(all.fromBuildId).toBe(timeline.builds[index - 2].buildId); + for (const move of all.moved) expect(move.entry.values[index].status).toBe("ok"); + + // At the latest build the series is long enough for typical steps. + const atLatest = stepSummary(entries, timeline.builds, latest); + expect(atLatest.rankedByTypical).toBe(true); + const ratios = atLatest.moved.filter((move) => move.ratio !== null).map((move) => move.ratio!); + expect(ratios.length).toBeGreaterThan(10); + expect(ratios).toEqual([...ratios].sort((left, right) => right - left)); + const headline = stepSummary(entries.filter((entry) => entry.headline), timeline.builds, latest); + expect(headline.moved.every((move) => move.entry.headline)).toBe(true); + expect(headline.moved.length).toBeLessThan(atLatest.moved.length); +}); diff --git a/frontend/lib/microcosm/release-history-moved.ts b/frontend/lib/microcosm/release-history-moved.ts new file mode 100644 index 00000000..f896c91c --- /dev/null +++ b/frontend/lib/microcosm/release-history-moved.ts @@ -0,0 +1,162 @@ +/** + * What moved at a build (calibration-diagnostics#224): the outputs ranked by how large their + * step to that build is beside their own typical step. + * + * The yardstick is each output's own history (María, 26 November 2026): the step divided by the + * median of the output's earlier steps, so no outside threshold is needed. An output with fewer + * than three earlier steps is ranked by the size of its step alone, after the others. + * + * Every number here is one output's own published step. A step beside a withheld cell is never + * ranked, sized or compared: it is counted as withheld and nothing else. + */ +import { stepsInPoints } from "./release-history-format"; +import type { OutputEntry } from "./release-history-outputs"; +import type { TimelineBuild } from "./release-history-store"; + +/** How many earlier steps an output needs before its typical step means something. */ +export const MIN_STEPS_FOR_TYPICAL = 3; + +export interface StepMove { + entry: OutputEntry; + /** The step, signed: a percentage for money and counts, percentage points for rates. */ + signed: number; + size: number; + measure: "percent" | "points"; + /** The median size of the output's earlier steps; null with fewer than three of them. */ + typical: number | null; + /** `size / typical`; infinite when the output never moved before; null without a typical step. */ + ratio: number | null; + /** Whether the step took the output nearer to its official figure, when it has one. */ + official: { before: number; after: number; direction: "nearer" | "further" | "same" } | null; +} + +export interface StepSummary { + buildIndex: number; + /** The build the steps come from: the neighbour the outputs were compared with. */ + fromBuildId: string | null; + /** The build publishes the file of an earlier build, so no output can have moved. */ + sameFile: boolean; + /** The outputs that moved, largest first by the yardstick. */ + moved: StepMove[]; + unchanged: number; + withheld: number; + /** Outputs with no step to this build: no value here, or none at the build before. */ + noStep: number; + /** Whether any output is ranked by its typical step (false while the series is too short). */ + rankedByTypical: boolean; +} + +/** An output's step to a build, in the measure its unit is told in; null when it has none. */ +export function stepOf(entry: OutputEntry, buildIndex: number): { signed: number; measure: StepMove["measure"] } | null { + const value = entry.values[buildIndex]; + if (!value || value.changeStatus !== "ok") return null; + if (stepsInPoints(entry.unit)) { + return value.changePoints === null ? null : { signed: value.changePoints, measure: "points" }; + } + return value.relativeChange === null ? null : { signed: value.relativeChange * 100, measure: "percent" }; +} + +function median(sorted: number[]): number { + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; +} + +/** + * The median size of an output's steps before a build. A build that republishes an earlier + * build's file is left out: its step is zero by construction and says nothing about the data. + */ +export function typicalStep( + entry: OutputEntry, + builds: readonly TimelineBuild[], + buildIndex: number, +): number | null { + const sizes: number[] = []; + for (let index = 0; index < buildIndex; index += 1) { + if (builds[index].sameFileAs !== null) continue; + const step = stepOf(entry, index); + if (step) sizes.push(Math.abs(step.signed)); + } + return sizes.length < MIN_STEPS_FOR_TYPICAL ? null : median(sizes.sort((left, right) => left - right)); +} + +function officialMove( + entry: OutputEntry, + builds: readonly TimelineBuild[], + buildIndex: number, +): StepMove["official"] { + const value = entry.values[buildIndex]; + if (entry.official === null || value.value === null || value.comparedWith === null) return null; + const previous = entry.values[builds.findIndex((build) => build.buildId === value.comparedWith)]?.value; + if (previous === null || previous === undefined) return null; + const before = Math.abs(previous - entry.official); + const after = Math.abs(value.value - entry.official); + return { before, after, direction: after < before ? "nearer" : after > before ? "further" : "same" }; +} + +/** Largest ratio first; an output with no typical step comes after, by the size of its step. */ +function byYardstick(left: StepMove, right: StepMove): number { + if ((left.ratio === null) !== (right.ratio === null)) return left.ratio === null ? 1 : -1; + const leftRank = left.ratio ?? left.size; + const rightRank = right.ratio ?? right.size; + if (leftRank !== rightRank) return rightRank - leftRank; + if (left.size !== right.size) return right.size - left.size; + return left.entry.key < right.entry.key ? -1 : left.entry.key > right.entry.key ? 1 : 0; +} + +/** The newest build that is measured and on the axis: the build "what moved" speaks of. */ +export function latestMeasuredBuild(builds: readonly TimelineBuild[]): number | null { + for (let index = builds.length - 1; index >= 0; index -= 1) { + if (builds[index].state === "measured" && !builds[index].withdrawn) return index; + } + return null; +} + +/** What each output did at one build. `entries` are the outputs to rank: all, or the headline ones. */ +export function stepSummary( + entries: readonly OutputEntry[], + builds: readonly TimelineBuild[], + buildIndex: number, +): StepSummary { + const summary: StepSummary = { + buildIndex, + fromBuildId: null, + sameFile: builds[buildIndex]?.sameFileAs != null, + moved: [], + unchanged: 0, + withheld: 0, + noStep: 0, + rankedByTypical: false, + }; + for (const entry of entries) { + const value = entry.values[buildIndex]; + if (!value) continue; + if (value.comparedWith !== null) summary.fromBuildId ??= value.comparedWith; + if (value.changeStatus === "withheld" || value.status === "withheld") { + summary.withheld += 1; + continue; + } + const step = stepOf(entry, buildIndex); + if (!step) { + summary.noStep += 1; + continue; + } + const size = Math.abs(step.signed); + if (size === 0) { + summary.unchanged += 1; + continue; + } + const typical = typicalStep(entry, builds, buildIndex); + summary.moved.push({ + entry, + signed: step.signed, + size, + measure: step.measure, + typical, + ratio: typical === null ? null : typical === 0 ? Number.POSITIVE_INFINITY : size / typical, + official: officialMove(entry, builds, buildIndex), + }); + } + summary.moved.sort(byYardstick); + summary.rankedByTypical = summary.moved.some((move) => move.ratio !== null); + return summary; +} diff --git a/frontend/lib/microcosm/release-history-outputs.test.ts b/frontend/lib/microcosm/release-history-outputs.test.ts new file mode 100644 index 00000000..4991c1c2 --- /dev/null +++ b/frontend/lib/microcosm/release-history-outputs.test.ts @@ -0,0 +1,180 @@ +import { expect, test } from "bun:test"; + +import { + baselineLabel, + groupedOutputs, + humanizeId, + latestValue, + outputEntries, + referenceLine, + timelinePeriods, +} from "./release-history-outputs"; +import type { Timeline } from "./release-history-store"; +import { panelPresentation } from "./release-history-summary"; +import { syntheticPanelView } from "./test-support/release-history-synthetic-view"; + +test("ids become labels: acronyms in capitals, a person group after a comma, a housing-cost basis in brackets", () => { + expect(humanizeId("income_tax")).toBe("Income tax"); + expect(humanizeId("vat")).toBe("VAT"); + expect(humanizeId("refundable_ctc")).toBe("Refundable CTC"); + const groups = ["all", "children"]; + expect(baselineLabel("national_insurance", groups)).toBe("National insurance"); + expect(baselineLabel("absolute_poverty_bhc_all", groups)).toBe("Absolute poverty (BHC), everyone"); + expect(baselineLabel("relative_poverty_ahc_children", groups)).toBe("Relative poverty (AHC), children"); + // An id that only happens to end like a group it does not name stays whole. + expect(baselineLabel("children", groups)).toBe("Children"); + expect(baselineLabel("household_net_income_total", [])).toBe("Household net income total"); +}); + +test("the UK's outputs are grouped by the kind of each baseline item, then by reform, in the spec's order", async () => { + const { timeline, presentation } = await syntheticPanelView("uk"); + const entries = outputEntries(timeline, presentation); + expect(entries).toHaveLength(timeline.outputs.length); + expect(timelinePeriods(entries)).toEqual([2026]); + const groups = groupedOutputs(entries); + expect([...groups.keys()]).toEqual([ + "Receipts", + "Spending", + "Caseloads", + "Population", + "Incomes in the data", + "Household income", + "Poverty rates", + "Household net income mean by income decile", + "Reform · Basic rate +1p", + "Reform · Higher rate +1p", + "Reform · Additional rate +1p", + "Reform · Personal allowance +£100", + "Reform · Class 1 employee main NICs rate +1pp", + "Reform · Child Benefit subsequent child +£1 a week", + "Reform · VAT standard rate +1pp", + ]); + expect(groups.get("Receipts")!.map((entry) => entry.label)).toEqual([ + "Income tax", "National insurance", "VAT", "Council tax", "Capital gains tax", + ]); + expect(groups.get("Poverty rates")!.map((entry) => entry.label).slice(0, 2)).toEqual([ + "Absolute poverty (BHC), everyone", "Absolute poverty (AHC), everyone", + ]); + expect(groups.get("Household net income mean by income decile")!.map((entry) => entry.label)).toEqual( + Array.from({ length: 10 }, (_, index) => `Decile ${index + 1}`), + ); +}); + +test("a reform's outputs run from its target and budgetary impact to its poverty counts, in neutral words", async () => { + const { timeline, presentation } = await syntheticPanelView("uk"); + const reform = groupedOutputs(outputEntries(timeline, presentation)).get("Reform · Basic rate +1p")!; + const labels = reform.map((entry) => entry.label); + expect(labels.slice(0, 4)).toEqual([ + "Change in income tax (target)", + "Budgetary impact", + "Change in income tax", + "Change in national insurance", + ]); + expect(labels).toContain("Change in VAT"); + const after = labels.slice(labels.indexOf("Households with higher net income")); + expect(after.slice(0, 7)).toEqual([ + "Households with higher net income", + "Households with lower net income", + "People with higher net income", + "People with lower net income", + "Change in net income, all households", + "Change in net income, decile 1", + "Change in net income, decile 2", + ]); + expect(labels.at(-1)).toBe("Change in people in poverty, relative BHC, children"); + expect(reform[0].fullLabel).toBe("Basic rate +1p · Change in income tax (target)"); + // The page's words for an output never rank a household. + for (const entry of outputEntries(timeline, presentation)) { + expect(`${entry.group} ${entry.label}`).not.toMatch(/\b(gaining|losing|winners?|losers?|better|worse)\b/i); + } +}); + +test("headline outputs are the baseline totals and each reform's budgetary impact and target", async () => { + const { timeline, presentation } = await syntheticPanelView("uk"); + const headline = outputEntries(timeline, presentation).filter((entry) => entry.headline); + // 32 baseline items with a total (the 33rd has decile rows only), and two per reform. + expect(headline).toHaveLength(32 + 2 * 7); + expect(headline.every((entry) => !entry.id.includes("decile"))).toBe(true); +}); + +test("an output's official figure is the reference's value in the model's sign, where it has one", async () => { + const uk = await syntheticPanelView("uk"); + const entries = outputEntries(uk.timeline, uk.presentation); + const withOfficial = entries.filter((entry) => entry.official !== null); + // The references lock resolves 13 UK baseline totals; every reform is a citation with no value. + expect(withOfficial).toHaveLength(13); + expect(withOfficial.every((entry) => entry.id.startsWith("baseline/"))).toBe(true); + const incomeTax = entries.find((entry) => entry.id === "baseline/income_tax")!; + expect(incomeTax.official).toBe( + uk.timeline.outputs.find((output) => output.output === "baseline/income_tax")!.reference!.modelSignValue!, + ); + expect(referenceLine(incomeTax)).toBe("a published figure (forecast), from 1 Chronicle record."); + const reform = entries.find((entry) => entry.id === "reform/basic_rate_plus_1p/budgetary_impact")!; + expect(reform.official).toBeNull(); + expect(referenceLine(reform)).toStartWith( + "cited, with no value yet: HM Revenue & Customs, Direct effects of illustrative tax changes (tax ready reckoner), June 2025,", + ); + const poverty = entries.find((entry) => entry.id === "baseline/absolute_poverty_bhc_all")!; + expect(referenceLine(poverty)).toBe("HBAI has no 2026-27 figure yet."); + const decile = entries.find((entry) => entry.id === "baseline/household_net_income_mean/decile_3")!; + expect(referenceLine(decile)).toBe("none listed for this output."); + + const us = await syntheticPanelView("us"); + const usEntries = outputEntries(us.timeline, us.presentation); + expect(usEntries.some((entry) => entry.official !== null)).toBe(false); + expect([...groupedOutputs(usEntries).keys()]).toEqual([ + "Receipts", + "Other programmes", + "Spending", + "Population", + "Reform · All individual income tax rates +1pt", + "Reform · ARPA 2021 Child Tax Credit expansion", + ]); +}); + +test("an entry holds no number for a cell that is not ok, whatever the document carries", async () => { + const { timeline, presentation } = await syntheticPanelView("uk"); + const entries = outputEntries(timeline, presentation); + const withheld = entries.flatMap((entry) => entry.values).filter((value) => value.status === "withheld"); + expect(withheld.length).toBeGreaterThan(0); + for (const value of entries.flatMap((entry) => entry.values)) { + if (value.status !== "ok") expect(value.value).toBeNull(); + if (value.changeStatus !== "ok" || value.status !== "ok") { + expect([value.change, value.relativeChange, value.changePoints]).toEqual([null, null, null]); + } + } + + // A timeline that wrongly carried numbers beside a withheld status gives the page none. + const leaking: Timeline = structuredClone(timeline); + const output = leaking.outputs.find((candidate) => candidate.values.some((value) => value.status === "withheld"))!; + const index = output.values.findIndex((value) => value.status === "withheld"); + Object.assign(output.values[index], { value: 4321.5, change: 12, relativeChange: 0.5, changePoints: 3, changeStatus: "ok" }); + const entry = outputEntries(leaking, presentation).find((candidate) => candidate.id === output.output)!; + expect(entry.values[index]).toMatchObject({ status: "withheld", value: null, change: null, relativeChange: null, changePoints: null }); + expect(JSON.stringify(entry.values)).not.toContain("4321.5"); +}); + +test("the latest value is the newest one on the axis, never a withdrawn build's", async () => { + const { timeline, presentation } = await syntheticPanelView("uk"); + const entry = outputEntries(timeline, presentation).find((candidate) => candidate.id === "baseline/income_tax")!; + const latest = latestValue(entry, timeline.builds)!; + // The served panel never ran the two newest builds: its latest value is the 10 November build's. + expect(timeline.builds[latest.index].publishedAt).toBe("2026-11-10T09:31:00+00:00"); + const withdrawnOnly = { + ...entry, + values: entry.values.map((value, index) => (timeline.builds[index].withdrawn ? value : { ...value, value: null })), + }; + expect(withdrawnOnly.values.some((value) => value.value !== null)).toBe(true); + expect(latestValue(withdrawnOnly, timeline.builds)).toBeNull(); +}); + +test("an output the spec does not name still gets a label, after the ones it does", async () => { + const { timeline } = await syntheticPanelView("us"); + const entries = outputEntries( + { ...timeline, outputs: [...timeline.outputs, { ...timeline.outputs[0], output: "something/new_kind" }] }, + panelPresentation(null), + ); + expect(entries.at(-1)).toMatchObject({ group: "Other outputs", label: "Something new kind", headline: false }); + // With no panel.json every baseline item is still listed, in one group. + expect(entries[0].group).toBe("Other baseline items"); +}); diff --git a/frontend/lib/microcosm/release-history-outputs.ts b/frontend/lib/microcosm/release-history-outputs.ts new file mode 100644 index 00000000..f1856624 --- /dev/null +++ b/frontend/lib/microcosm/release-history-outputs.ts @@ -0,0 +1,296 @@ +/** + * A panel's outputs as the release history page lists them (calibration-diagnostics#224): each + * with a label, a group and a place in the order, from the output's id and the panel's spec. + * + * Nothing here adds, subtracts or compares two outputs. Each entry holds one output's own values + * across builds, with every number removed from a cell that is not `ok`, so a withheld value can + * never be shown, drawn or derived from further down. + */ +import type { OutputUnit } from "./release-history-format"; +import type { Timeline, TimelineBuild, TimelineOutput, TimelineValue } from "./release-history-store"; +import type { PanelPresentation } from "./release-history-summary"; + +export interface OutputEntry { + /** `@`: one row of the timeline. */ + key: string; + id: string; + period: number; + unit: OutputUnit; + /** The group's title, and the label inside that group. */ + group: string; + label: string; + /** The label with its reform's name, for a list that mixes groups. */ + fullLabel: string; + /** A baseline total, or a reform's budgetary impact or target: what a short list ranks. */ + headline: boolean; + reference: TimelineOutput["reference"]; + /** The official figure in the model's sign, when the reference has a value that is not zero. */ + official: number | null; + /** One per build, in the order of the timeline's builds, with no number where none is shown. */ + values: TimelineValue[]; +} + +// Words shown in capitals. A display list only: no output is treated differently for it. +const ACRONYMS = new Set([ + "ahc", "amt", "bhc", "cgt", "ctc", "dla", "eitc", "esa", "jsa", "nics", "pip", "snap", "ssi", "tanf", + "uc", "uk", "us", "vat", "wic", +]); + +function word(token: string): string { + return ACRONYMS.has(token.toLowerCase()) ? token.toUpperCase() : token; +} + +function capitalise(text: string): string { + return text ? `${text[0].toUpperCase()}${text.slice(1)}` : text; +} + +/** "income_tax" as "income tax", with acronyms in capitals. */ +function words(id: string): string { + return id.split("_").filter(Boolean).map(word).join(" "); +} + +/** "income_tax" as "Income tax"; "vat" as "VAT". */ +export function humanizeId(id: string): string { + return capitalise(words(id)); +} + +/** A person group of the spec: `all` reads "everyone". */ +function groupLabel(group: string): string { + return group === "all" ? "everyone" : words(group); +} + +/** + * A baseline item's label. An id that ends in one of the spec's person groups names the group + * after a comma, and a housing-cost basis goes in brackets: "absolute_poverty_bhc_all" reads + * "Absolute poverty (BHC), everyone". + */ +export function baselineLabel(id: string, groups: readonly string[]): string { + const suffix = [...groups] + .sort((left, right) => right.length - left.length) + .find((group) => id.endsWith(`_${group}`) && id.length > group.length + 1); + const stem = suffix ? id.slice(0, -(suffix.length + 1)) : id; + const text = capitalise( + stem.split("_").filter(Boolean) + .map((token) => (token === "bhc" || token === "ahc" ? `(${token.toUpperCase()})` : word(token))) + .join(" "), + ); + return suffix ? `${text}, ${groupLabel(suffix)}` : text; +} + +const KIND_GROUPS: Readonly> = { + tax: "Receipts", + benefit: "Spending", + caseload: "Caseloads", + population: "Population", + input: "Incomes in the data", + income: "Household income", + rate: "Poverty rates", + other: "Other programmes", +}; + +const REFORM_LABELS: Readonly> = { + budgetary_impact: "Budgetary impact", + households_gaining: "Households with higher net income", + households_losing: "Households with lower net income", + people_gaining: "People with higher net income", + people_losing: "People with lower net income", + net_income_change_pct: "Change in net income, all households", +}; + +// Where each kind of reform output sits inside its reform's group. +const REFORM_ORDER: Readonly> = { + target: 0, + budgetary_impact: 1, + programme: 2, + households_gaining: 40, + households_losing: 41, + people_gaining: 42, + people_losing: 43, + net_income_change_pct: 50, + decile_relative_change: 51, + poverty: 60, +}; + +function decileOf(part: string | undefined): number { + const decile = Number(part?.split("_")[1]); + return Number.isFinite(decile) ? decile : 0; +} + +function position(list: readonly string[], item: string): number { + const found = list.indexOf(item); + return found === -1 ? list.length : found; +} + +interface Described { + group: string; + label: string; + fullLabel: string; + headline: boolean; + order: number[]; +} + +function describeBaseline(parts: string[], presentation: PanelPresentation): Described { + const [, item, decilePart] = parts; + const index = presentation.baseline.findIndex((candidate) => candidate.id === item); + const kind = index === -1 ? null : presentation.baseline[index].kind; + const label = baselineLabel(item, presentation.groups); + const order = [0, index === -1 ? presentation.baseline.length : index]; + if (decilePart) { + const decile = decileOf(decilePart); + return { + group: `${label} by income decile`, + label: `Decile ${decile}`, + fullLabel: `${label}, decile ${decile}`, + headline: false, + order: [...order, decile], + }; + } + return { + group: (kind && KIND_GROUPS[kind]) || "Other baseline items", + label, + fullLabel: label, + headline: true, + order: [...order, 0], + }; +} + +function reformOutputLabel(rest: string[]): string { + const [kind, first, second] = rest; + if (kind === "target") return `Change in ${words(first ?? "")} (target)`; + if (kind === "programme") return `Change in ${words(first ?? "")}`; + if (kind === "decile_relative_change") return `Change in net income, decile ${decileOf(first)}`; + if (kind === "poverty") { + const basis = words(first ?? ""); + return `Change in people in poverty, ${basis}, ${groupLabel(second ?? "all")}`; + } + return REFORM_LABELS[kind] ?? humanizeId(rest.join("_")); +} + +function describeReform(parts: string[], timeline: Timeline, presentation: PanelPresentation): Described { + const [, reform, ...rest] = parts; + const kind = rest[0] ?? ""; + const name = timeline.labels[reform]?.label ?? humanizeId(reform); + const label = reformOutputLabel(rest); + let minor = 0; + if (kind === "programme") minor = position(presentation.baseline.map((item) => item.id), rest[1] ?? ""); + if (kind === "decile_relative_change") minor = decileOf(rest[1]); + if (kind === "poverty") { + minor = position(presentation.povertyMeasures, rest[1] ?? "") * 100 + position(presentation.groups, rest[2] ?? ""); + } + return { + group: `Reform · ${name}`, + label, + fullLabel: `${name} · ${label}`, + headline: kind === "budgetary_impact" || kind === "target", + order: [1, position(presentation.reforms, reform), REFORM_ORDER[kind] ?? 90, minor], + }; +} + +function describe(output: TimelineOutput, timeline: Timeline, presentation: PanelPresentation): Described { + const parts = output.output.split("/"); + if (parts[0] === "baseline" && parts.length >= 2) return describeBaseline(parts, presentation); + if (parts[0] === "reform" && parts.length >= 3) return describeReform(parts, timeline, presentation); + const label = humanizeId(output.output.replace(/\//g, "_")); + return { group: "Other outputs", label, fullLabel: label, headline: false, order: [2] }; +} + +/** A value as the page may use it: no number where the cell or the step is not `ok`. */ +function shownValue(value: TimelineValue): TimelineValue { + const hasValue = value.status === "ok" && typeof value.value === "number"; + const hasStep = hasValue && value.changeStatus === "ok"; + return { + ...value, + value: hasValue ? value.value : null, + change: hasStep ? value.change : null, + relativeChange: hasStep ? value.relativeChange : null, + changePoints: hasStep ? value.changePoints : null, + }; +} + +function compareOrder(left: number[], right: number[]): number { + for (let index = 0; index < Math.max(left.length, right.length); index += 1) { + const difference = (left[index] ?? 0) - (right[index] ?? 0); + if (difference !== 0) return difference; + } + return 0; +} + +export function outputKey(id: string, period: number): string { + return `${id}@${period}`; +} + +/** Every output of the timeline, labelled and in the page's order. */ +export function outputEntries(timeline: Timeline, presentation: PanelPresentation): OutputEntry[] { + return timeline.outputs + .map((output) => { + const described = describe(output, timeline, presentation); + const official = output.reference?.modelSignValue; + const entry: OutputEntry = { + key: outputKey(output.output, output.period), + id: output.output, + period: output.period, + unit: output.unit, + group: described.group, + label: described.label, + fullLabel: described.fullLabel, + headline: described.headline, + reference: output.reference, + official: typeof official === "number" && Number.isFinite(official) && official !== 0 ? official : null, + values: output.values.map(shownValue), + }; + return { entry, order: described.order }; + }) + .sort((left, right) => + compareOrder(left.order, right.order) || + (left.entry.id < right.entry.id ? -1 : left.entry.id > right.entry.id ? 1 : 0) || + left.entry.period - right.entry.period + ) + .map(({ entry }) => entry); +} + +/** The entries of one period, by group, in the page's order. */ +export function groupedOutputs(entries: readonly OutputEntry[]): Map { + const groups = new Map(); + for (const entry of entries) groups.set(entry.group, [...(groups.get(entry.group) ?? []), entry]); + return groups; +} + +/** The periods the timeline measures, ascending. */ +export function timelinePeriods(entries: readonly OutputEntry[]): number[] { + return [...new Set(entries.map((entry) => entry.period))].sort((left, right) => left - right); +} + +/** + * The newest build on the axis that holds a value for the output, and that value. A withdrawn + * build's value is never the latest: the publisher took the build back. + */ +export function latestValue( + entry: OutputEntry, + builds: ReadonlyArray>, +): { index: number; value: number } | null { + for (let index = entry.values.length - 1; index >= 0; index -= 1) { + const value = entry.values[index].value; + if (value !== null && !builds[index]?.withdrawn) return { index, value }; + } + return null; +} + +/** In one line, where the output's official figure comes from, or why it has none. */ +export function referenceLine(entry: OutputEntry): string { + const reference = entry.reference; + if (!reference) return "none listed for this output."; + const basis = typeof reference.basis === "string" ? ` (${reference.basis.replace(/_/g, " ")})` : ""; + if (reference.status === "resolved") { + const facts = Array.isArray(reference.facts) ? reference.facts.length : 0; + const from = facts > 0 ? `, from ${facts} Chronicle ${facts === 1 ? "record" : "records"}` : ""; + return `a published figure${basis}${from}.`; + } + if (reference.status === "citation") { + const citation = (reference.citation ?? {}) as Record; + const named = [citation.publisher, citation.document, citation.edition, citation.row] + .filter((part): part is string => typeof part === "string" && part.length > 0) + .join(", "); + return `cited, with no value yet: ${named || "a publication"}${basis}.`; + } + return typeof reference.reason === "string" && reference.reason ? reference.reason : "none."; +} diff --git a/frontend/lib/microcosm/release-history-url.test.ts b/frontend/lib/microcosm/release-history-url.test.ts new file mode 100644 index 00000000..cc3cc0c1 --- /dev/null +++ b/frontend/lib/microcosm/release-history-url.test.ts @@ -0,0 +1,69 @@ +import { expect, test } from "bun:test"; + +import { releaseHistoryUrlState, withReleaseHistoryState } from "./release-history-url"; + +const PAGE = "https://dashboard.example/calibration/dashboard/microcosm/release-history"; + +test("a bare URL is the default view: the default panel, the first output, Relative, no step", () => { + expect(releaseHistoryUrlState(new URLSearchParams("country=uk"))).toEqual({ + panel: null, + output: null, + period: null, + scale: "relative", + step: null, + moved: "headline", + }); +}); + +test("the URL names the engine's panel, the output, the scale and the open step", () => { + const search = new URLSearchParams({ + country: "uk", + panel: "a".repeat(64), + output: "baseline/income_tax", + period: "2027", + scale: "absolute", + step: "microcosm-uk-2024-25-national/attempt-20261107T020434Z-eeb6093e", + moved: "all", + }); + expect(releaseHistoryUrlState(search)).toEqual({ + panel: "a".repeat(64), + output: "baseline/income_tax", + period: 2027, + scale: "absolute", + step: "microcosm-uk-2024-25-national/attempt-20261107T020434Z-eeb6093e", + moved: "all", + }); + // Anything else for the scale, the scope or the period is the default. + expect(releaseHistoryUrlState(new URLSearchParams("scale=log&moved=some&period=soon&panel=%20"))).toMatchObject({ + panel: null, + period: null, + scale: "relative", + moved: "headline", + }); +}); + +test("writing the state keeps every other parameter and leaves the defaults out", () => { + const chosen = withReleaseHistoryState(`${PAGE}?country=uk&utm=x`, { + output: "reform/basic_rate_plus_1p/budgetary_impact", + scale: "absolute", + step: "line/build-1", + }); + const url = new URL(chosen); + expect(url.searchParams.get("country")).toBe("uk"); + expect(url.searchParams.get("utm")).toBe("x"); + expect(releaseHistoryUrlState(url.searchParams)).toMatchObject({ + output: "reform/basic_rate_plus_1p/budgetary_impact", + scale: "absolute", + step: "line/build-1", + }); + // Back to the defaults: the parameters go. + const cleared = withReleaseHistoryState(chosen, { output: null, scale: "relative", step: null }); + expect(cleared).toBe(`${PAGE}?country=uk&utm=x`); + // One part changes; the rest stays as the URL had it. + const panel = withReleaseHistoryState(chosen, { panel: "b".repeat(64) }); + expect(releaseHistoryUrlState(new URL(panel).searchParams)).toMatchObject({ + panel: "b".repeat(64), + output: "reform/basic_rate_plus_1p/budgetary_impact", + scale: "absolute", + }); +}); diff --git a/frontend/lib/microcosm/release-history-url.ts b/frontend/lib/microcosm/release-history-url.ts new file mode 100644 index 00000000..9ffaeaa3 --- /dev/null +++ b/frontend/lib/microcosm/release-history-url.ts @@ -0,0 +1,63 @@ +/** + * The release history page's state in its URL (calibration-diagnostics#224), so a link opens the + * same engine, output, scale and step. A default is never written, and a value the page cannot + * use (a panel of another country, an output this panel does not hold) is ignored by the page, + * not refused here. + */ + +export type ChartScale = "relative" | "absolute"; +export type MovedScope = "headline" | "all"; + +export interface ReleaseHistoryUrlState { + /** The panel of the chosen reference engine; null for the panel the page opens. */ + panel: string | null; + /** The selected output's id; null for the first output. */ + output: string | null; + /** The measured period; null for the first one. */ + period: number | null; + scale: ChartScale; + /** The build whose step card is open, as `/`. */ + step: string | null; + moved: MovedScope; +} + +const PARAMS = ["panel", "output", "period", "scale", "step", "moved"] as const; + +function value(search: URLSearchParams, name: string): string | null { + const found = search.get(name)?.trim(); + return found ? found : null; +} + +export function releaseHistoryUrlState(search: URLSearchParams): ReleaseHistoryUrlState { + const period = Number(value(search, "period")); + return { + panel: value(search, "panel"), + output: value(search, "output"), + period: Number.isInteger(period) && period > 0 ? period : null, + scale: value(search, "scale") === "absolute" ? "absolute" : "relative", + step: value(search, "step"), + moved: value(search, "moved") === "all" ? "all" : "headline", + }; +} + +/** `currentUrl` with part of the state changed, every other parameter kept, defaults left out. */ +export function withReleaseHistoryState( + currentUrl: string, + patch: Partial, +): string { + const url = new URL(currentUrl); + const next = { ...releaseHistoryUrlState(url.searchParams), ...patch }; + const written: Record<(typeof PARAMS)[number], string | null> = { + panel: next.panel, + output: next.output, + period: next.period === null ? null : String(next.period), + scale: next.scale === "absolute" ? "absolute" : null, + step: next.step, + moved: next.moved === "all" ? "all" : null, + }; + for (const name of PARAMS) { + if (written[name]) url.searchParams.set(name, written[name]); + else url.searchParams.delete(name); + } + return url.toString(); +} diff --git a/frontend/lib/microcosm/test-support/release-history-small-timeline.ts b/frontend/lib/microcosm/test-support/release-history-small-timeline.ts new file mode 100644 index 00000000..f82360d3 --- /dev/null +++ b/frontend/lib/microcosm/test-support/release-history-small-timeline.ts @@ -0,0 +1,94 @@ +// Test support: a small timeline with chosen values, built by the real `buildTimeline`, for +// tests that need exact numbers. Each column of `values` is one build, oldest first. +import { + buildTimeline, + type MeasurementCell, + type ReferencesLock, + type SeriesBuild, + type SeriesRecord, + type Timeline, +} from "../release-history-store"; +import { measurementDocument } from "./release-history-documents"; + +const LINE = "zz-national"; +const PANEL = "a".repeat(64); +const digest = (index: number) => index.toString(16).padStart(64, "0"); + +/** A cell's value, `"withheld"`, or `null` where the build's point holds no such cell. */ +export type SmallValue = number | "withheld" | null; + +export interface SmallBuild { + /** Publishes the file of this earlier build (by index). */ + sameFileAs?: number; + withdrawn?: boolean; + /** Listed and never measured on this panel. */ + unmeasured?: boolean; +} + +export function smallTimeline(options: { + builds: SmallBuild[]; + /** By output id: `[unit, values per build]`. */ + outputs: Record; + references?: ReferencesLock | null; +}): Timeline { + const builds = options.builds.map((build, index): SeriesBuild => ({ + build_id: `${LINE}/b${index + 1}`, + release: LINE, + build: `b${index + 1}`, + release_directory: `${LINE}/b${index + 1}`, + published_at: `2026-11-${String(index + 1).padStart(2, "0")}T00:00:00Z`, + withdrawn: build.withdrawn ?? false, + current: index === options.builds.length - 1, + in_default_release: true, + role: "national", + digest: digest((build.sameFileAs ?? index) + 1), + dataset_path: `releases/${LINE}/b${index + 1}/zz.h5`, + release_manifest_sha256: "f".repeat(64), + listing_status: "ok", + listing_reason: null, + })); + const series: SeriesRecord = { + format_version: 1, + kind: "release_history.series", + country: "zz", + release_repo: "policyengine/zz", + rule: { releases: [LINE], since: null }, + revision: "main", + commit: "1".repeat(40), + listed_at: "2026-11-30T00:00:00Z", + record: { present: true, sha256: "d".repeat(64), default: LINE }, + lines: [{ release: LINE, present: true, role: "national" }], + builds, + }; + const points = options.builds.flatMap((build, index) => { + if (build.unmeasured || build.sameFileAs !== undefined) return []; + const cells = Object.entries(options.outputs).flatMap(([output, [unit, values]]): MeasurementCell[] => { + const value = values[index]; + if (value === null || value === undefined) return []; + return [{ + output, + period: 2026, + unit, + value: value === "withheld" ? null : value, + status: value === "withheld" ? "withheld" : "ok", + reason: value === "withheld" ? "small_cell" : null, + }]; + }); + return [measurementDocument({ + country: "zz", + panelId: PANEL, + measurementId: digest(index + 1).replace(/^0/, "9"), + digest: digest(index + 1), + cells, + })]; + }); + return buildTimeline({ + country: "zz", + panelId: PANEL, + series, + points, + references: options.references ?? null, + labels: null, + builtAt: "2026-11-30T00:00:00Z", + }); +} diff --git a/frontend/lib/microcosm/test-support/release-history-synthetic-store.ts b/frontend/lib/microcosm/test-support/release-history-synthetic-store.ts new file mode 100644 index 00000000..53a5b2df --- /dev/null +++ b/frontend/lib/microcosm/test-support/release-history-synthetic-store.ts @@ -0,0 +1,570 @@ +// Test and development support: a whole release history store on synthetic values +// (calibration-diagnostics#224). No production data exists while the page is built, and the +// trial's values are never used, so this makes the cases the page must show from the producer's +// committed fixtures (each country's spec on a synthetic world) and a seeded generator, through +// the real `finalizeCountry` and `buildTimeline`: +// +// - uk: an engine bump in progress. The earlier engine's panel is the served one and lacks the +// two newest builds; the newer engine's panel is pinned and still filling, with one file +// retrying and one failed. One build was measured and then withdrawn, one file is published +// under two builds, one file is a gap, the build engine and the target set change part-way, +// and cells are withheld as in the fixture, one of them in some builds only. +// - us: one complete panel, and a second engine's panel that a run from another ref filled for +// two builds, under another definition. +// +// Values sit near each output's public official figure where the references hold one, so the +// Relative view looks like the real thing. Every name says "synthetic". +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { measurementIdFor } from "../../../scripts/release-history"; +import { + attemptPath, + buildTimeline, + countryFilePath, + encodeDocument, + finalizeCountry, + memoryStore, + panelPrefix, + updateManifestCountry, + type AttemptReport, + type LabelsDocument, + type ManifestCountry, + type MeasurementCell, + type MeasurementDocument, + type PanelDocument, + type PlanMode, + type PlannedPoint, + type ReferencesLock, + type ReleaseHistoryStore, + type SeriesBuild, + type SeriesRecord, + type Timeline, +} from "../release-history-store"; +import { + manifestPanelSummary, + readCountryFixture, + RELEASE_HISTORY_FIXTURES, + type CountryFixture, +} from "./release-history-fixture-store"; + +const sha256 = (text: string) => createHash("sha256").update(text).digest("hex"); + +/** A small seeded generator (mulberry32), so every run writes the same store. */ +function seeded(seed: string): () => number { + let state = Number.parseInt(sha256(seed).slice(0, 8), 16) >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let mixed = state; + mixed = Math.imul(mixed ^ (mixed >>> 15), mixed | 1); + mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61); + return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296; + }; +} + +const between = (random: () => number, low: number, high: number) => low + (high - low) * random(); + +// --------------------------------------------------------------------------- +// The scenario + +interface SyntheticBuild { + /** Day and time of publication, `MMDDTHHMM`, in 2026. */ + at: string; + /** Publishes the file of this earlier build (by index) under a new name. */ + sameFileAs?: number; + withdrawn?: boolean; + current?: boolean; + /** The release repository lists it with no file to measure. */ + refused?: boolean; + /** Its file carries no survey household ids: a stored refusal, a gap on every engine. */ + gap?: boolean; +} + +interface SyntheticRun { + panel: "earlier" | "newer" | "other"; + mode: PlanMode; + pin: boolean; + at: string; + /** The builds listed when the run finalized: a later build is not on its series yet. */ + listed: number; + /** Builds that were withdrawn only after this run. */ + notYetWithdrawn?: number[]; + /** Planned builds (by index) that stored nothing, with how their attempt ended. */ + failures?: Record; + /** The only builds the run planned; absent means every file the panel lacked. */ + only?: number[]; +} + +interface SyntheticCountry { + release: string; + releaseRepo: string; + since: string | null; + builds: SyntheticBuild[]; + /** The model versions of the three panels' engines. */ + engines: { earlier: string; newer?: string; other?: string }; + /** The builds (by index) from which the data build's own engine and target set change. */ + buildEngineChangesAt: number; + targetSetChangesAt: number[]; + runs: SyntheticRun[]; +} + +const SCENARIOS: Record = { + uk: { + release: "microcosm-uk-2024-25-national", + releaseRepo: "policyengine/populace-uk-private", + since: "2026-10-19", + builds: [ + { at: "1019T0833" }, + { at: "1021T0710" }, + { at: "1021T1642", sameFileAs: 1 }, + { at: "1024T0905", gap: true }, + { at: "1027T0214" }, + { at: "1029T1120", withdrawn: true }, + { at: "1102T0204" }, + { at: "1105T0204" }, + { at: "1107T0204" }, + { at: "1110T0931" }, + { at: "1112T1500", refused: true }, + { at: "1117T0204" }, + { at: "1124T0204", current: true }, + ], + engines: { earlier: "1.0.0", newer: "1.1.0" }, + buildEngineChangesAt: 6, + targetSetChangesAt: [6, 9], + runs: [ + // The earlier engine's backfill, when ten builds were listed and none was withdrawn. + { panel: "earlier", mode: "backfill", pin: true, at: "2026-11-11T05:00:00Z", listed: 10, notYetWithdrawn: [5] }, + // The engine bump's first top-up: the whole series on the new panel. One file is over the + // runner's budget and one download failed, so the panel is not complete yet. + { + panel: "newer", + mode: "topup", + pin: true, + at: "2026-11-25T05:00:00Z", + listed: 13, + failures: { + 7: { reason: "exceeds_runner_budget", stage: "open", lastAttempt: false }, + 12: { reason: "download_failed", stage: "download" }, + }, + }, + ], + }, + us: { + release: "microcosm-us-2024-national", + releaseRepo: "policyengine/populace-us", + since: null, + builds: [ + { at: "0902T1400" }, + { at: "0911T1400" }, + { at: "0915T1400", sameFileAs: 1 }, + { at: "1006T1400" }, + { at: "1020T1400" }, + { at: "1103T1400", current: true }, + ], + engines: { earlier: "1.0.0", other: "0.9.0" }, + buildEngineChangesAt: 3, + targetSetChangesAt: [3], + runs: [ + { panel: "earlier", mode: "backfill", pin: true, at: "2026-11-08T05:00:00Z", listed: 6 }, + // Two builds on another engine, by hand, from a ref that pins it and edits the spec. + { panel: "other", mode: "release", pin: false, at: "2026-11-09T12:00:00Z", listed: 6, only: [4] }, + { panel: "other", mode: "release", pin: false, at: "2026-11-09T13:00:00Z", listed: 6, only: [5] }, + ], + }, +}; + +function buildName(build: SyntheticBuild): string { + return `synthetic-2026${build.at}00Z-${sha256(build.at).slice(0, 8)}`; +} + +function publishedAt(build: SyntheticBuild): string { + const [, month, day, hour, minute] = /^(\d\d)(\d\d)T(\d\d)(\d\d)$/.exec(build.at)!; + return `2026-${month}-${day}T${hour}:${minute}:00+00:00`; +} + +function fileDigest(scenario: SyntheticCountry, index: number): string { + const build = scenario.builds[index]; + return sha256(`file:${scenario.release}:${buildName(scenario.builds[build.sameFileAs ?? index])}`); +} + +function seriesRecord( + country: string, + scenario: SyntheticCountry, + listed: number, + notYetWithdrawn: readonly number[], + listedAt: string, +): SeriesRecord { + const builds = scenario.builds.slice(0, listed).map((build, index): SeriesBuild => { + const name = buildName(build); + const digest = build.refused ? null : fileDigest(scenario, index); + return { + build_id: `${scenario.release}/${name}`, + release: scenario.release, + build: name, + release_directory: `${scenario.release}/${name}`, + published_at: publishedAt(build), + withdrawn: Boolean(build.withdrawn) && !notYetWithdrawn.includes(index), + // The record's current build is the newest one listed when it was read. + current: listed === scenario.builds.length ? Boolean(build.current) : index === listed - 1, + in_default_release: true, + role: "national", + digest, + dataset_path: digest ? `releases/${scenario.release}/${name}/national.h5` : null, + release_manifest_sha256: digest ? sha256(`manifest:${name}`) : null, + listing_status: digest ? "ok" : "refused", + listing_reason: digest ? null : "release_manifest_missing", + }; + }); + return { + format_version: 1, + kind: "release_history.series", + country, + release_repo: scenario.releaseRepo, + rule: { releases: [scenario.release], since: scenario.since }, + revision: "main", + commit: sha256(`series:${country}:${listed}`).slice(0, 40), + listed_at: listedAt, + record: { present: true, sha256: sha256(`record:${country}:${listed}`), default: scenario.release }, + lines: [{ release: scenario.release, present: true, role: "national" }], + builds, + }; +} + +// --------------------------------------------------------------------------- +// Values + +interface OutputPlan { + /** The level the series starts from. */ + base: number | null; + /** The size of an ordinary step: a share for money and counts, an amount for rates. */ + noise: number; + /** Whether the output takes a larger step where the data build changes. */ + jumps: boolean; + /** What the newer and the other engine add to the earlier engine's value. */ + engineShift: Record; +} + +function outputPlan(country: string, cell: MeasurementCell, official: number | undefined): OutputPlan { + const random = seeded(`plan:${country}:${cell.output}:${cell.period}`); + const offset = between(random, -0.06, 0.06); + const fallback = cell.unit === "rate" ? 0.15 : cell.unit === "ratio" ? 0.4 : 1_000_000; + return { + base: official !== undefined ? official * (1 + offset) : cell.value ?? fallback, + noise: between(random, 0.001, 0.006), + jumps: random() < 0.35, + engineShift: { earlier: 0, newer: between(random, -0.012, 0.012), other: between(random, -0.03, 0.03) }, + }; +} + +/** The output's value at one build on one engine: a seeded walk from its base. */ +function valueAt( + country: string, + cell: MeasurementCell, + plan: OutputPlan, + scenario: SyntheticCountry, + fileIndex: number, + engine: string, +): number | null { + if (plan.base === null) return null; + if (plan.base === 0) return 0; + const additive = cell.unit === "rate" || cell.unit === "ratio"; + const scale = additive ? Math.max(Math.abs(plan.base), 0.05) : 1; + let drift = 0; + for (let step = 1; step <= fileIndex; step += 1) { + // A build that republishes a file is that file: it takes no step of its own. + if (scenario.builds[step].sameFileAs !== undefined || scenario.builds[step].refused) continue; + const random = seeded(`step:${country}:${cell.output}:${cell.period}:${step}`); + drift += between(random, -plan.noise, plan.noise); + if (plan.jumps && scenario.targetSetChangesAt.includes(step)) drift += between(random, -0.035, 0.035); + } + const moved = drift + plan.engineShift[engine]; + if (!additive) return plan.base * (1 + moved); + const value = plan.base + moved * scale; + return cell.unit === "rate" ? Math.min(Math.max(value, 0), 1) : value; +} + +// --------------------------------------------------------------------------- +// Documents + +function panelDocument(fixture: CountryFixture, engine: string, version: string): PanelDocument { + const model = `${fixture.panel.engine.model.name}==${version}`; + // The other engine's ref also edits the spec, so its definition differs. + const specSha256 = engine === "other" ? sha256(`spec:${fixture.panel.country}:other`) : fixture.panel.spec_sha256; + const panelKey = { ...fixture.panel.panel_key, model, spec_sha256: specSha256 }; + return { + ...fixture.panel, + panel_id: sha256(JSON.stringify(panelKey)), + panel_key: panelKey, + engine: { ...fixture.panel.engine, model: { ...fixture.panel.engine.model, version } }, + spec_sha256: specSha256, + }; +} + +function declaredFacts( + template: MeasurementDocument, + scenario: SyntheticCountry, + index: number, +): MeasurementDocument["fetched_from"]["declared"] { + const build = scenario.builds[index]; + const name = buildName(build); + const package_ = String((template.fetched_from.declared.compatible_models as { name?: string }[] | null)?.[0]?.name ?? "policyengine"); + const builtWith = index >= scenario.buildEngineChangesAt ? "0.10.0" : "0.9.0"; + const targetSet = scenario.targetSetChangesAt.filter((change) => change <= index).length; + return { + build: name, + cut_tag: null, + migrated_from: null, + built_at: publishedAt(build), + built_with_model: { name: package_, version: builtWith }, + built_with_core: { name: "policyengine-core", version: "3.33.3" }, + // Most builds declare the one model version they were built with, which the reference + // engine is outside of; the newest declare a range it is inside. + compatible_models: [{ name: package_, specifier: index >= scenario.builds.length - 2 ? ">=1" : `==${builtWith}` }], + reference_model_compatibility: index >= scenario.builds.length - 2 ? "inside" : "outside", + description: null, + build_provenance: { + code_repository: "PolicyEngine/microcosm", + code_commit: sha256(`commit:${name}`).slice(0, 40), + attempt_id: name, + target_surface_sha256: sha256(`targets:${scenario.release}:${targetSet}`), + n_targets: 1200 + 14 * targetSet, + target_registry_version: targetSet >= 2 ? "2026.11" : "2026.10", + household_weight_year: 2024, + runtime: null, + }, + }; +} + +function measurement(options: { + country: string; + scenario: SyntheticCountry; + fixture: CountryFixture; + panel: PanelDocument; + engine: string; + index: number; + plans: Map; +}): MeasurementDocument { + const { country, scenario, fixture, panel, engine, index } = options; + const build = scenario.builds[index]; + const measured = fixture.points.filter((point) => point.status === "ok"); + // The fixture's measured points withhold slightly different cells: builds alternate between + // them, so a cell is withheld in some builds and published in others. + const template = measured[index % measured.length]; + const digest = fileDigest(scenario, index); + const name = buildName(build); + const fetchedFrom: MeasurementDocument["fetched_from"] = { + ...template.fetched_from, + build_id: `${scenario.release}/${name}`, + hf_repo: scenario.releaseRepo, + release_manifest: { + ...template.fetched_from.release_manifest, + path: `releases/${scenario.release}/${name}/release_manifest.json`, + sha256: sha256(`manifest:${name}`), + }, + dataset: { key: "national", path: `releases/${scenario.release}/${name}/national.h5` }, + declared: declaredFacts(template, scenario, index), + }; + const identity = { + country, + panel_id: panel.panel_id, + measurement_id: measurementIdFor(panel.panel_id, digest), + fetched_from: fetchedFrom, + file: { sha256: digest, bytes: template.file.bytes }, + }; + if (build.gap) { + const refused = fixture.points.find((point) => point.status === "refused") ?? template; + return { ...refused, ...identity, status: "refused", reason: "disclosure_source_ids_missing", cells: [], data: null }; + } + const cells = template.cells.map((cell): MeasurementCell => { + if (cell.status === "withheld") return { ...cell, value: null }; + const plan = options.plans.get(`${cell.output}@${cell.period}`)!; + return { ...cell, value: valueAt(country, cell, plan, scenario, index, engine) }; + }); + return { + ...template, + ...identity, + status: "ok", + reason: null, + cells, + data: template.data && { + ...template.data, + unknown_columns: index >= scenario.buildEngineChangesAt ? ["synthetic_new_column"] : [], + }, + runtime: { ...template.runtime, near_limits: [] }, + }; +} + +function plannedPoint(series: SeriesRecord, build: SeriesBuild, lastAttempt: boolean): PlannedPoint { + return { + build_id: build.build_id, + release_directory: build.release_directory, + hf_repo: series.release_repo, + hf_commit: series.commit, + digest: build.digest as string, + attempt: 1, + last_attempt: lastAttempt, + }; +} + +// --------------------------------------------------------------------------- +// The store + +export interface SyntheticCountryStore { + /** Panel ids by engine: `earlier` is the served panel. */ + panels: Record; + series: SeriesRecord; + entry: ManifestCountry; + timelines: Record; + panelDocuments: Record; +} + +export interface SyntheticReleaseHistory { + store: ReleaseHistoryStore & { objects: Map }; + countries: Record; +} + +async function readJsonFile(...parts: string[]): Promise { + return JSON.parse(await readFile(join(...parts), "utf8")) as T; +} + +async function fillCountry( + store: SyntheticReleaseHistory["store"], + country: string, + scenario: SyntheticCountry, +): Promise { + const fixture = await readCountryFixture(country); + const folder = join(RELEASE_HISTORY_FIXTURES, country); + const labels = await readJsonFile(folder, "labels.json"); + const references = await readJsonFile( + RELEASE_HISTORY_FIXTURES, "..", "..", "countries", country, "references.lock.json", + ); + const write = (path: string, document: unknown) => store.write(path, encodeDocument(document), "replace", false); + + // Each output starts near its official figure, where the fixture's timeline carries one. + const officials = new Map(); + for (const output of fixture.timeline.outputs) { + const official = output.reference?.modelSignValue; + if (typeof official === "number") officials.set(`${output.output}@${output.period}`, official); + } + const plans = new Map(); + for (const point of fixture.points) { + for (const cell of point.cells) { + const key = `${cell.output}@${cell.period}`; + if (cell.value !== null && !plans.has(key)) plans.set(key, outputPlan(country, cell, officials.get(key))); + } + } + for (const point of fixture.points) { + for (const cell of point.cells) { + const key = `${cell.output}@${cell.period}`; + if (!plans.has(key)) plans.set(key, outputPlan(country, cell, officials.get(key))); + } + } + + const panelDocuments: Record = {}; + for (const [engine, version] of Object.entries(scenario.engines)) { + if (version) panelDocuments[engine] = panelDocument(fixture, engine, version); + } + const stored: Record = {}; + let series = seriesRecord(country, scenario, scenario.builds.length, [], ""); + for (const run of scenario.runs) { + const panel = panelDocuments[run.panel]; + const prefix = panelPrefix(country, panel.panel_id); + series = seriesRecord(country, scenario, run.listed, run.notYetWithdrawn ?? [], run.at); + await write(`${prefix}panel.json`, panel); + const held = new Set((stored[run.panel] ?? []).map((point) => point.file.sha256)); + const planned: PlannedPoint[] = []; + const reports: Record = {}; + for (const [index, build] of series.builds.entries()) { + if (build.digest === null || build.withdrawn || held.has(build.digest)) continue; + if (run.only && !run.only.includes(index)) continue; + if (planned.some((point) => point.digest === build.digest)) continue; + const failure = run.failures?.[index]; + planned.push(plannedPoint(series, build, failure?.lastAttempt ?? false)); + if (failure) { + reports[build.digest] = { + format_version: 1, + kind: "release_history.attempt", + country, + panel_id: panel.panel_id, + digest: build.digest, + build_id: build.build_id, + attempt: 1, + last_attempt: failure.lastAttempt ?? false, + status: "failed", + stage: failure.stage, + reason: failure.reason, + error_class: null, + at: run.at, + producer: { version: panel.producer_version, commit: null }, + }; + await write(attemptPath(country, panel.panel_id, build.digest), reports[build.digest]); + continue; + } + const point = measurement({ country, scenario, fixture, panel, engine: run.panel, index, plans }); + (stored[run.panel] ??= []).push(point); + await write(`${prefix}${point.measurement_id}.json`, point); + } + // Only a run that pins replaces the country's files. + if (run.pin) { + await write(countryFilePath(country, "series"), series); + await write(countryFilePath(country, "labels"), labels); + await write(countryFilePath(country, "references"), references); + } + await updateManifestCountry(store, country, (entry) => + finalizeCountry({ + entry, + panel: manifestPanelSummary(panel), + series, + mode: run.mode, + planned, + stored: stored[run.panel] ?? [], + reports, + pin: run.pin, + at: run.at, + }), run.at); + } + + // As finalize does: every panel's timeline on the series as last listed. + const manifest = JSON.parse(new TextDecoder().decode((await store.read("release-history/manifest.json"))!.body)) as { + countries: Record; + }; + const entry = manifest.countries[country]; + const timelines: Record = {}; + const panels: Record = {}; + const lastRun = scenario.runs.at(-1)!; + for (const [engine, panel] of Object.entries(panelDocuments)) { + panels[engine] = panel.panel_id; + const timeline = buildTimeline({ + country, + panelId: panel.panel_id, + series, + points: stored[engine] ?? [], + states: entry.panels[panel.panel_id]?.points, + references, + labels, + builtAt: lastRun.at, + }); + timelines[panel.panel_id] = timeline; + await write(`${panelPrefix(country, panel.panel_id)}timeline.json`, timeline); + } + return { panels, series, entry, timelines, panelDocuments }; +} + +/** The synthetic store, the same on every call. */ +export async function syntheticReleaseHistory(): Promise { + const store = memoryStore(); + const countries: Record = {}; + for (const [country, scenario] of Object.entries(SCENARIOS)) { + countries[country] = await fillCountry(store, country, scenario); + } + return { store, countries }; +} + +let shared: Promise | null = null; + +/** One synthetic store for a whole test file: it is read, never written. */ +export function sharedSyntheticReleaseHistory(): Promise { + shared ??= syntheticReleaseHistory(); + return shared; +} diff --git a/frontend/lib/microcosm/test-support/release-history-synthetic-view.ts b/frontend/lib/microcosm/test-support/release-history-synthetic-view.ts new file mode 100644 index 00000000..38d37da6 --- /dev/null +++ b/frontend/lib/microcosm/test-support/release-history-synthetic-view.ts @@ -0,0 +1,18 @@ +// Test support: one synthetic panel as the page loads it, read through the routes' own reader. +import { readPanelView } from "../release-history-read"; +import type { ReleaseHistoryPanelView } from "../release-history-summary"; +import { sharedSyntheticReleaseHistory } from "./release-history-synthetic-store"; + +/** + * A panel of the synthetic store. `uk`: `earlier` is the served panel, `newer` the pinned one + * that is still filling. `us`: `earlier` is complete, `other` holds two builds on another engine. + */ +export async function syntheticPanelView( + country: "uk" | "us", + engine: "earlier" | "newer" | "other" = "earlier", +): Promise { + const { store, countries } = await sharedSyntheticReleaseHistory(); + const result = await readPanelView(store, country, countries[country].panels[engine]); + if (result.kind !== "ok") throw new Error(`No synthetic ${country} panel for the ${engine} engine: ${result.kind}.`); + return result.view; +} diff --git a/frontend/scripts/release-history-dev-store.test.ts b/frontend/scripts/release-history-dev-store.test.ts new file mode 100644 index 00000000..20f804d9 --- /dev/null +++ b/frontend/scripts/release-history-dev-store.test.ts @@ -0,0 +1,72 @@ +import { expect, test } from "bun:test"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { createReleaseHistorySummaryHandler } from "../app/api/microcosm/release-history/route"; +import { createReleaseHistoryTimelineHandler } from "../app/api/microcosm/release-history/timeline/route"; +import { versusOfficial } from "../lib/microcosm/release-history-format"; +import { outputEntries } from "../lib/microcosm/release-history-outputs"; +import { directoryStore } from "../lib/microcosm/release-history-source"; +import type { ReleaseHistoryPanelView, ReleaseHistorySummary } from "../lib/microcosm/release-history-summary"; +import { syntheticReleaseHistory } from "../lib/microcosm/test-support/release-history-synthetic-store"; +import { writeSyntheticStore } from "./release-history-dev-store"; + +const API = "https://dashboard.example/calibration/dashboard/api/microcosm/release-history"; + +test("the synthetic store is the same on every run, and says it is synthetic", async () => { + const [first, second] = await Promise.all([syntheticReleaseHistory(), syntheticReleaseHistory()]); + expect([...first.store.objects.keys()].sort()).toEqual([...second.store.objects.keys()].sort()); + for (const [path, object] of first.store.objects) { + expect(Buffer.from(object.body).equals(Buffer.from(second.store.objects.get(path)!.body))).toBe(true); + } + for (const country of Object.values(first.countries)) { + for (const build of country.series.builds) expect(build.build).toStartWith("synthetic-"); + } +}); + +test("the routes serve the written folder as they would serve Blob", async () => { + const out = await mkdtemp(join(tmpdir(), "release-history-dev-store-")); + const written = await writeSyntheticStore(out); + expect(written.countries).toEqual(["uk", "us"]); + expect(written.files).toBeGreaterThan(30); + const dependencies = { store: () => directoryStore(out) }; + + // The UK is mid-way through an engine bump: the page opens the served panel, on the earlier + // engine, and lists the pinned one, which is still filling. + const summary = (await (await createReleaseHistorySummaryHandler(dependencies)( + new Request(`${API}?country=uk`), + )).json()) as ReleaseHistorySummary; + expect(summary.available).toBe(true); + expect(summary.defaultPanelId).toBe(summary.servedPanelId); + expect(summary.pinnedPanelId).not.toBe(summary.servedPanelId); + expect(summary.panels.map((panel) => [panel.engine.model, panel.served, panel.pinned, panel.sameDefinitionAsDefault])).toEqual([ + ["policyengine-uk==1.0.0", true, false, true], + ["policyengine-uk==1.1.0", false, true, true], + ]); + expect(summary.panels[0].coverage).toMatchObject({ files: 10, measured: 7, gap: 1, missing: 2 }); + expect(summary.panels[1].coverage).toMatchObject({ files: 10, measured: 7, gap: 1, failed: 1, retrying: 1 }); + + const view = (await (await createReleaseHistoryTimelineHandler(dependencies)( + new Request(`${API}/timeline?country=uk`), + )).json()) as ReleaseHistoryPanelView; + expect(view.panelId).toBe(summary.defaultPanelId!); + expect(view.timeline.builds).toHaveLength(12); + // Values sit within a few percent of the official figure, where an output has one. + const entries = outputEntries(view.timeline, view.presentation).filter((entry) => entry.official !== null); + expect(entries).toHaveLength(13); + for (const entry of entries) { + for (const value of entry.values) { + if (value.value !== null) expect(Math.abs(versusOfficial(value.value, entry.official!))).toBeLessThan(20); + } + } + + // The US has a complete panel and a second engine's panel under another definition. + const us = (await (await createReleaseHistorySummaryHandler(dependencies)( + new Request(`${API}?country=us`), + )).json()) as ReleaseHistorySummary; + expect(us.panels.map((panel) => [panel.engine.model, panel.complete, panel.pinnedAt !== null, panel.sameDefinitionAsDefault])).toEqual([ + ["policyengine-us==1.0.0", true, true, true], + ["policyengine-us==0.9.0", false, false, false], + ]); +}); diff --git a/frontend/scripts/release-history-dev-store.ts b/frontend/scripts/release-history-dev-store.ts new file mode 100644 index 00000000..c9b799f8 --- /dev/null +++ b/frontend/scripts/release-history-dev-store.ts @@ -0,0 +1,39 @@ +/** + * Writes the synthetic release history store to a folder (calibration-diagnostics#224), so the + * page can be looked at with no production data and no Blob token: + * + * bun run scripts/release-history-dev-store.ts --out ../.tmp/release-history-store + * RELEASE_HISTORY_LOCAL_DIR=../.tmp/release-history-store bun run dev + * + * then open /microcosm/release-history?country=uk. The values are made up: each country's + * committed fixtures (its spec on a synthetic world) and a seeded generator, through the real + * finalize and timeline code. See lib/microcosm/test-support/release-history-synthetic-store.ts + * for the cases it holds. It writes local files only. + */ +import { mkdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { parseArgs } from "node:util"; + +import { syntheticReleaseHistory } from "../lib/microcosm/test-support/release-history-synthetic-store"; + +/** Write every document of the synthetic store under `out`, in the store's layout. */ +export async function writeSyntheticStore(out: string): Promise<{ files: number; countries: string[] }> { + const { store, countries } = await syntheticReleaseHistory(); + for (const [path, object] of store.objects) { + const target = join(out, path); + await mkdir(dirname(target), { recursive: true }); + await writeFile(target, object.body); + } + return { files: store.objects.size, countries: Object.keys(countries) }; +} + +if (import.meta.main) { + const { values } = parseArgs({ args: process.argv.slice(2), options: { out: { type: "string" } } }); + if (!values.out) { + console.error("Usage: release-history-dev-store.ts --out "); + process.exit(1); + } + const out = resolve(values.out); + const written = await writeSyntheticStore(out); + console.log(JSON.stringify({ out, ...written })); +} From ae0ed414e4cdb5e60995a54477df6e5358199971 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:09:01 +0000 Subject: [PATCH 4/6] Add the release history page: one panel's timeline, by reference engine `/microcosm/release-history?country=` draws what #304 stores: every national data file a country publishes, measured on one fixed engine. It is reachable by URL; a navigation entry needs a capability in the calibration tree package, which is a change in microcosm-collector. - The page opens the served panel. After an engine bump a notice says how many files the newer engine holds and links to it. The engine toggle lists every panel that holds a measured file, and the page names the builds the chosen engine has no value for, by why: never run, retrying, out of attempts, or a file the producer refused. - In order: the notices, the series facts, what moved at the latest build, the builds of the series, and the outputs, with the selected output's stats, chart, official reference, step card and table. The table sits behind a toggle, closed by default. - The chart is SVG drawn from the tested layout, with a Relative (%) / Absolute switch, Relative by default. Each column is a button: hover or focus reads out its value, and a click opens its step. A withdrawn build is listed and marked, and its column stays, shaded. - The step card sets what a step's two builds declare side by side, with links to their Microcosm commits and to each build's Calibration fit page. - The state is in the URL (the engine's panel, the output, the scale, the open step), and a value the loaded panel cannot use leaves the URL. - After a neutrality review of the page's text: an output "moved" and is "nearer to" or "further from" its official figure; the page labels every output and never prints an output's id, because four ids per reform spell "gaining" and "losing"; a build's state reads "Out of attempts" and "File refused", which say what happened to the run and are no verdict on the build. - Also in the logic: axis labels keep the decimals that tell two ticks apart, the latest value's label stays clear of the line and of a shaded column, and a step away from a value of zero ranks first with no percentage. - The rendered page is tested on the synthetic store, including that a number a timeline wrongly carried beside a withheld status reaches no markup. - `docs/release-history.md` gains a section on the page. Co-Authored-By: Claude Fable 5.2 --- docs/release-history.md | 102 ++++- .../app/microcosm/release-history/page.tsx | 21 + .../microcosm/release-history-chart.tsx | 358 +++++++++++++++ .../release-history-output-detail.tsx | 407 ++++++++++++++++++ .../microcosm/release-history-sections.tsx | 386 +++++++++++++++++ .../microcosm/release-history-step-card.tsx | 287 ++++++++++++ .../microcosm/release-history-view.test.tsx | 202 +++++++++ .../microcosm/release-history-view.tsx | 282 ++++++++++++ frontend/lib/api/hooks/use-release-history.ts | 49 +++ .../microcosm/release-history-builds.test.ts | 4 +- .../lib/microcosm/release-history-builds.ts | 6 +- .../microcosm/release-history-chart.test.ts | 40 +- .../lib/microcosm/release-history-chart.ts | 65 ++- .../lib/microcosm/release-history-format.ts | 15 + .../microcosm/release-history-moved.test.ts | 22 + .../lib/microcosm/release-history-moved.ts | 16 +- .../microcosm/release-history-page.test.ts | 143 ++++++ .../lib/microcosm/release-history-page.ts | 156 +++++++ .../release-history-synthetic-store.ts | 2 +- 19 files changed, 2532 insertions(+), 31 deletions(-) create mode 100644 frontend/app/microcosm/release-history/page.tsx create mode 100644 frontend/components/microcosm/release-history-chart.tsx create mode 100644 frontend/components/microcosm/release-history-output-detail.tsx create mode 100644 frontend/components/microcosm/release-history-sections.tsx create mode 100644 frontend/components/microcosm/release-history-step-card.tsx create mode 100644 frontend/components/microcosm/release-history-view.test.tsx create mode 100644 frontend/components/microcosm/release-history-view.tsx create mode 100644 frontend/lib/api/hooks/use-release-history.ts create mode 100644 frontend/lib/microcosm/release-history-page.test.ts create mode 100644 frontend/lib/microcosm/release-history-page.ts diff --git a/docs/release-history.md b/docs/release-history.md index b7d0d823..87d60642 100644 --- a/docs/release-history.md +++ b/docs/release-history.md @@ -3,8 +3,8 @@ Release history measures every published national Microcosm data file of a country on one fixed reference model, so a move between two releases comes from the data, not the model (calibration-diagnostics#224). This document -covers the backend: what is measured, where it is stored, when it is -regenerated, and how to add a country. The dashboard page is a later PR. +covers the backend (what is measured, where it is stored, when it is +regenerated, and how to add a country) and the dashboard page that reads it. For a short overview, and the discussion points for what comes next, see [release-history-roadmap.md](release-history-roadmap.md). @@ -55,6 +55,11 @@ release_history/ frontend/lib/microcosm/release-history-store.ts Blob layout, manifest, plan, finalize, timeline frontend/scripts/release-history.ts plan | upload | finalize | pull | timeline .github/workflows/release-history.yml weekly top-ups and manual runs +frontend/app/api/microcosm/release-history/ the page's read routes: summary, timeline, export +frontend/app/microcosm/release-history/ the page +frontend/lib/microcosm/release-history-*.ts the page's logic: summary, outputs, chart, moved, builds, url +frontend/components/microcosm/release-history-* the page's view, chart and step card +frontend/scripts/release-history-dev-store.ts a synthetic store for local development ``` Python does everything that touches PolicyEngine, an H5, the release @@ -280,6 +285,99 @@ run, with no simulation, so a corrected publish time or a definition change never re-measures. Pooled summaries (typical and 1-in-10 revisions, windows, floors) belong to the page. +## The page + +`/microcosm/release-history?country=` draws one panel's `timeline.json`. +It is reachable by URL and has no navigation entry yet: that needs a +capability in `@policyengine/calibration-tree`'s `countries.ts`, a change in +PolicyEngine/microcosm-collector. Nothing in the page or its routes branches +on a country code. A country the dashboard does not serve gets the +not-configured state, and one with no measured file an empty state. + +Three routes read the store on the server, so the browser never receives a +Blob URL or a token. Each requires `?country=`. + +- `GET /api/microcosm/release-history`: the country's panels from the + manifest, one per reference engine that holds a measured file, with engine, + coverage and whether the definition equals the default panel's, and the + panel the page opens. It leaves the per-file entries out. +- `GET /api/microcosm/release-history/timeline?panel=`: one panel's + summary, its whole `timeline.json`, and what its `panel.json` says about + presenting its outputs (currency, period labels, the baseline items and + reforms in spec order, the disclosure policy). Without `panel` it serves the + panel the page opens. Only a panel the country's manifest entry lists is + read. +- `GET /api/microcosm/release-history/export?panel=`: the same timeline + as a CSV download, with the columns of `release-history export`. + +A timeline grows with every build and a function's response is capped at +4.5 MB, which an uncompressed UK timeline reaches at about 70 builds, so the +timeline and the CSV are sent gzipped to a client that accepts it. A compact +encoding is the next step if a compressed timeline nears the cap. + +**Which panel opens.** The served panel: the last pinned one that was +complete. After an engine bump the pinned panel fills first, a notice links +to it, and the page moves to it once it is complete. The engine toggle lists +every panel that holds a measured file, including one a run from another ref +filled, and says when a panel's definition differs from the default one's. + +**State in the URL.** `panel` (the engine's panel), `output`, `period` (when +the panel measures more than one), `scale=absolute`, `step` (the build whose +step card is open) and `moved=all`. A default is never written, and a value +the page cannot use (a panel of another country, an output the panel does not +hold) falls back to its default. + +**What it shows**, in order: notices about the engine on screen and the +builds it has no value for; the series facts; what moved at the latest build; +the builds of the series; and the outputs, with the selected output's chart, +official reference, step card and table. Its words are neutral: an output +"moved", and is "nearer to" or "further from" its official figure. It labels +every output and never prints an output's id. + +- The chart has one column per build in publish order. Relative, the default, + places each value as a percentage above or below the output's official + figure (the timeline's `reference.modelSignValue`); Absolute places the + values. An output with no official figure is drawn in values under both, + with a note. A line joins two builds only where the timeline has a step. +- A build with no value keeps its column, shaded and labelled with why: not + measured on this engine, retrying, out of attempts (the store's `failed`), + file refused (the store's `gap`), withheld, or withdrawn. The builds an + engine has no value for are also named in a notice. +- A withdrawn build is listed and marked. A value measured before the + withdrawal is a hollow marker that no line joins. +- Marks under the axis: a new build engine (the file was built with another + model version than the build before it), the same file published again, and + a withdrawn build. +- What moved ranks outputs by their step beside their own typical step, the + median of their earlier steps on the panel. A build that republishes a file + is left out of that median, and an output with fewer than three earlier + steps is ranked after the others by the size of its step. +- The step card sets what a step's two builds declare side by side (from the + timeline's `declared` block), with links to their Microcosm commits and to + each build's Calibration fit page. + +**Withheld cells.** The page shows a withheld cell as "Withheld" and never as +a number. It removes every number from a cell or a step that is not `ok` +before anything is drawn, ranked or exported, and it computes nothing across +outputs: no sum of deciles, no total less its parts. What it does compute is +per output: the distance from the official figure, which is public, and the +typical step, from that output's published steps. + +**Local development.** No production data is needed. `bun run +scripts/release-history-dev-store.ts --out ` writes a synthetic store +(each country's committed fixtures and a seeded generator, through the real +finalize and timeline code), and the routes read a local folder in the +store's layout when `RELEASE_HISTORY_LOCAL_DIR` names it, in place of Blob: + +```bash +cd frontend +bun run scripts/release-history-dev-store.ts --out ../.tmp/release-history-store +RELEASE_HISTORY_LOCAL_DIR=../.tmp/release-history-store bun run dev +``` + +The same variable opens a panel fetched with `pull`. It is unset on a hosted +deployment, which never reads its own filesystem. + ## Document formats Each stored document has its own format version: the point, the panel, the diff --git a/frontend/app/microcosm/release-history/page.tsx b/frontend/app/microcosm/release-history/page.tsx new file mode 100644 index 00000000..2c890b63 --- /dev/null +++ b/frontend/app/microcosm/release-history/page.tsx @@ -0,0 +1,21 @@ +import type { Metadata } from "next"; +import { Suspense } from "react"; + +import { AppShell } from "@/components/layout/app-shell"; +import { ReleaseHistoryView } from "@/components/microcosm/release-history-view"; +import { LoadingBlock } from "@/components/shared/LoadingBlock"; + +export const metadata: Metadata = { title: "Release history" }; + +// Reachable by URL (?country=); the navigation gains an entry once a country registers the +// capability in @policyengine/calibration-tree. A country the dashboard does not serve gets the +// shell's not-configured state, and one with no measured file an empty state. +export default function ReleaseHistoryPage() { + return ( + + }> + + + + ); +} diff --git a/frontend/components/microcosm/release-history-chart.tsx b/frontend/components/microcosm/release-history-chart.tsx new file mode 100644 index 00000000..748315e3 --- /dev/null +++ b/frontend/components/microcosm/release-history-chart.tsx @@ -0,0 +1,358 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; + +import { + BUILD_MARK_LABELS, + type BuildMark, +} from "@/lib/microcosm/release-history-builds"; +import type { ChartColumn, ChartLayout } from "@/lib/microcosm/release-history-chart"; + +// The release history chart (calibration-diagnostics#224): one output across the builds of a +// series. The layout is computed by lib/microcosm/release-history-chart.ts; this draws it. +// +// One series in the dashboard's one hue. A column with no value is shaded and labelled, so no +// state is told by colour alone, and every value is also in the table under the chart. Each +// column is a button over the plot: hover or focus shows its values, a click opens its step. + +/** What the tooltip and a column's accessible name say about one build. */ +export interface ChartColumnReadout { + /** The build's date and name. */ + title: string; + /** The value as the chart places it, or why the column holds none. */ + value: string; + /** The value's other reading: beside the official figure, or in its unit. */ + detail: string | null; + /** The step from the build before, or why there is none. */ + step: string; +} + +export const DEFAULT_CHART_WIDTH = 760; + +/** The width of an element, followed as it resizes; `fallback` before it is measured. */ +export function useElementWidth(fallback: number) { + const ref = useRef(null); + const [width, setWidth] = useState(fallback); + useEffect(() => { + const element = ref.current; + if (!element) return; + const measure = () => { + const next = Math.round(element.clientWidth); + if (next > 0) setWidth((current) => (Math.abs(current - next) < 2 ? current : next)); + }; + measure(); + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => observer.disconnect(); + }, []); + return { ref, width }; +} + +const INK = "var(--text-secondary)"; + +function sentenceCase(text: string): string { + return `${text[0].toUpperCase()}${text.slice(1)}`; +} + +/** A mark's glyph, centred on (x, y): a diamond, two bars, or a cross. */ +export function MarkGlyph({ mark, x, y }: { mark: BuildMark; x: number; y: number }) { + if (mark === "new_build_engine") { + return ; + } + if (mark === "same_file") { + return ( + + ); + } + return ( + + ); +} + +/** The marks a chart carries, each with its glyph and what it means. */ +export function MarkLegend({ marks }: { marks: readonly BuildMark[] }) { + if (marks.length === 0) return null; + return ( +
    + {marks.map((mark) => ( +
  • + + {BUILD_MARK_LABELS[mark]} +
  • + ))} +
+ ); +} + +function Bands({ layout }: { layout: ChartLayout }) { + const { plot } = layout; + return ( + <> + {layout.columns.map((column) => { + if (!column.band) return null; + const inset = Math.min(3, column.width / 4); + return ( + + + {layout.verticalBandLabels ? ( + + {sentenceCase(column.band)} + + ) : ( + + {sentenceCase(column.band)} + + )} + + ); + })} + + ); +} + +function Scale({ layout }: { layout: ChartLayout }) { + const { plot } = layout; + return ( + <> + {layout.ticks.map((tick, index) => ( + + + + {tick.label} + + + ))} + {layout.official && ( + + + + {layout.official.label} + + + )} + + + ); +} + +function Series({ layout }: { layout: ChartLayout }) { + return ( + <> + {layout.segments.map((segment) => ( + + ))} + {layout.columns.map((column) => { + if (!column.point) return null; + // A ring in the card's colour keeps a marker legible where it sits on the line. A + // withdrawn build's value is hollow: it is shown, and it is on no line. + return column.point.hollow ? ( + + ) : ( + + ); + })} + {layout.latestLabel && ( + + {layout.latestLabel.text} + + )} + + ); +} + +function Axis({ layout }: { layout: ChartLayout }) { + const { plot } = layout; + return ( + <> + {layout.columns.map((column) => ( + + {column.marks.map((mark, index) => ( + + ))} + {column.dateLabel && ( + + {column.dateLabel} + + )} + {column.current && ( + + Current + + )} + + ))} + + ); +} + +function Tooltip({ layout, column, readout }: { layout: ChartLayout; column: ChartColumn; readout: ChartColumnReadout }) { + // Beside its column, so the value it reads out stays in view: to the right where it fits, + // otherwise to the left, and never outside the chart. + const width = 232; + const gap = 14; + const right = column.x + gap; + const left = Math.max(right + width <= layout.width ? right : column.x - gap - width, 0); + return ( +
+ {readout.value} + {readout.detail && {readout.detail}} + {readout.title} + {readout.step} +
+ ); +} + +export function ReleaseHistoryChart({ + layout, + label, + readout, + selectedIndex, + onSelect, +}: { + layout: ChartLayout; + /** What the chart shows, for a reader who cannot see it. */ + label: string; + readout: (index: number) => ChartColumnReadout; + /** The build whose step card is open. */ + selectedIndex: number | null; + onSelect: (index: number) => void; +}) { + const [active, setActive] = useState(null); + const { plot } = layout; + const activeColumn = active === null ? null : layout.columns[active] ?? null; + const selected = selectedIndex === null ? null : layout.columns[selectedIndex] ?? null; + return ( +
+ + + {selected && ( + + )} + + {layout.empty && ( + + No build holds a value for this output. + + )} + {activeColumn && ( + + )} + + + + {/* One button per column: the hover and focus target, wider than any mark. */} + {layout.columns.map((column) => { + const said = readout(column.index); + return ( +
+ ); +} + +/** A small line of one output's values, drawn from a path the layout computed. */ +export function Sparkline({ path, last }: { path: string; last: { x: number; y: number } | null }) { + return ( + + ); +} diff --git a/frontend/components/microcosm/release-history-output-detail.tsx b/frontend/components/microcosm/release-history-output-detail.tsx new file mode 100644 index 00000000..d06d21f9 --- /dev/null +++ b/frontend/components/microcosm/release-history-output-detail.tsx @@ -0,0 +1,407 @@ +"use client"; + +import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; + +import { ToolbarSelect } from "@/components/shared/toolbar-select"; +import type { BuildMark } from "@/lib/microcosm/release-history-builds"; +import { chartLayout, columnBand, sparklinePath } from "@/lib/microcosm/release-history-chart"; +import { + dateLong, + dateShort, + formatChange, + formatPercent, + formatValue, + periodLabel, + versusOfficial, +} from "@/lib/microcosm/release-history-format"; +import { + groupedOutputs, + latestValue, + referenceLine, + type OutputEntry, +} from "@/lib/microcosm/release-history-outputs"; +import type { TimelineBuild } from "@/lib/microcosm/release-history-store"; +import type { PanelPresentation } from "@/lib/microcosm/release-history-summary"; +import type { ChartScale } from "@/lib/microcosm/release-history-url"; + +import { + DEFAULT_CHART_WIDTH, + MarkLegend, + ReleaseHistoryChart, + Sparkline, + useElementWidth, + type ChartColumnReadout, +} from "./release-history-chart"; +import { BuildChips } from "./release-history-sections"; + +// The outputs of the release history page (calibration-diagnostics#224): a navigator of every +// output by group, and the selected output's stats, chart, official reference and table. + +const SCALES: { id: ChartScale; label: string }[] = [ + { id: "relative", label: "Relative (%)" }, + { id: "absolute", label: "Absolute" }, +]; + +function unitName(unit: OutputEntry["unit"], currency: string | null): string { + if (unit === "currency") return currency ? `in ${currency}` : "in currency"; + return { count: "a count", rate: "a share", ratio: "in percent" }[unit]; +} + +function capitalise(text: string): string { + return `${text[0].toUpperCase()}${text.slice(1)}`; +} + +/** The outputs by group, with a search: each row has the output's line and its latest value. */ +export function OutputNavigator({ + entries, + builds, + currency, + selectedId, + onSelect, +}: { + entries: readonly OutputEntry[]; + builds: readonly TimelineBuild[]; + currency: string | null; + selectedId: string | null; + onSelect: (id: string) => void; +}) { + const [query, setQuery] = useState(""); + const groups = useMemo(() => groupedOutputs(entries), [entries]); + // A link, or a row of "what moved", can select an output far down the list: bring it into view + // inside the navigator, without moving the page. + const list = useRef(null); + useEffect(() => { + const container = list.current; + const selected = container?.querySelector('[aria-current="true"]'); + if (!container || !selected) return; + const frame = container.getBoundingClientRect(); + const row = selected.getBoundingClientRect(); + // The search box stays pinned over the top 56px of the list. + if (row.top < frame.top + 56) container.scrollTop -= frame.top + 56 - row.top; + else if (row.bottom > frame.bottom) container.scrollTop += row.bottom - frame.bottom + 8; + }, [selectedId]); + const wanted = query.trim().toLowerCase(); + const shown = [...groups].flatMap(([group, outputs]): [string, OutputEntry[]][] => { + const matches = outputs.filter( + (entry) => !wanted || entry.label.toLowerCase().includes(wanted) || group.toLowerCase().includes(wanted), + ); + return matches.length > 0 ? [[group, matches]] : []; + }); + return ( + + ); +} + +function Stat({ label, value, small = false }: { label: string; value: ReactNode; small?: boolean }) { + return ( +
+ {label} + {value} +
+ ); +} + +/** What one column of the chart says, in the tooltip and to a screen reader. */ +function columnReadout(options: { + entry: OutputEntry; + builds: readonly TimelineBuild[]; + names: ReadonlyMap; + currency: string | null; + relative: boolean; + index: number; +}): ChartColumnReadout { + const { entry, builds, currency, index } = options; + const build = builds[index]; + const value = entry.values[index]; + const title = `${dateLong(build.publishedAt)} · ${options.names.get(build.buildId) ?? build.build}`; + const before = value.comparedWith === null ? null : builds.find((candidate) => candidate.buildId === value.comparedWith); + const step = before + ? `From ${dateShort(before.publishedAt)}: ${formatChange(value, entry.unit, currency)}.` + : build.withdrawn + ? "Withdrawn: no step joins it." + : "No step to this build."; + if (value.value === null) { + const band = columnBand(build, value.status) ?? "no value"; + return { title, value: capitalise(band), detail: build.reason, step }; + } + const amount = formatValue(value.value, entry.unit, currency, 2); + const versus = entry.official === null + ? null + : `${formatPercent(versusOfficial(value.value, entry.official))} against the official figure`; + return options.relative && versus + ? { title, value: versus, detail: amount, step } + : { title, value: amount, detail: versus ?? "No official figure", step }; +} + +function ValuesTable({ + entry, + builds, + marks, + names, + currency, + selectedIndex, + onSelect, +}: { + entry: OutputEntry; + builds: readonly TimelineBuild[]; + marks: readonly BuildMark[][]; + names: ReadonlyMap; + currency: string | null; + selectedIndex: number | null; + onSelect: (index: number) => void; +}) { + const official = entry.official; + const heading = "border-b border-border-dark px-2.5 py-1.5 text-left align-bottom font-mono text-[11px] font-medium uppercase tracking-[0.05em] text-muted-foreground"; + const cell = "border-b border-border px-2.5 py-1.5 whitespace-nowrap"; + const number = `${cell} text-right font-mono text-[12.5px] tabular-nums`; + return ( +
+ + + + + + + {official !== null && } + + + + + + {builds.map((build, index) => { + const value = entry.values[index]; + const band = value.value === null ? columnBand(build, value.status) : null; + return ( + + + + + {official !== null && ( + + )} + + + + ); + })} + +
BuildPublishedValueAgainst officialStep from the build beforeStatus
+ + {dateLong(build.publishedAt)}{value.value === null ? "—" : formatValue(value.value, entry.unit, currency, 2)} + {value.value === null ? "—" : formatPercent(versusOfficial(value.value, official))} + {formatChange(value, entry.unit, currency)} + + {band && band !== "withdrawn" && ( + + {capitalise(band)} + + )} + + +
+
+ ); +} + +/** The selected output: its stats, the Relative / Absolute switch, the chart and the table. */ +export function OutputDetail({ + entry, + entries, + periods, + period, + builds, + marks, + names, + presentation, + scale, + stepIndex, + onScale, + onPeriod, + onSelectOutput, + onSelectStep, + children, +}: { + entry: OutputEntry; + entries: readonly OutputEntry[]; + periods: readonly number[]; + period: number; + builds: readonly TimelineBuild[]; + marks: readonly BuildMark[][]; + names: ReadonlyMap; + presentation: PanelPresentation; + scale: ChartScale; + stepIndex: number | null; + onScale: (scale: ChartScale) => void; + onPeriod: (period: number) => void; + onSelectOutput: (id: string) => void; + onSelectStep: (index: number) => void; + /** The open step card, under the chart. */ + children?: ReactNode; +}) { + const { currency } = presentation; + const { ref, width } = useElementWidth(DEFAULT_CHART_WIDTH); + const layout = useMemo( + () => chartLayout({ builds, entry, scale, currency, marks, width }), + [builds, entry, scale, currency, marks, width], + ); + const latest = latestValue(entry, builds); + const withValue = entry.values.filter((value, index) => value.value !== null && !builds[index].withdrawn).length; + const withheld = entry.values.filter((value) => value.status === "withheld").length; + const official = entry.official; + const unit = unitName(entry.unit, currency); + const present = [...new Set(layout.columns.flatMap((column) => column.marks))]; + const modeNote = layout.relative && official !== null + ? `Each release as a % above or below the official figure, ${formatValue(official, entry.unit, currency)}.` + : layout.blocked + ? "No official figure for this output, so it shows values." + : `Values, ${unit}.`; + const pickerOptions = entries.map((candidate) => ({ value: candidate.id, label: candidate.label, group: candidate.group })); + return ( +
+ {/* Below the lg breakpoint the navigator gives way to this select. */} +
+ +
+
+

{entry.group}

+

{entry.label}

+

+ {periodLabel(entry.period, presentation.periodLabel)} · {unit} +

+
+
+ + {official !== null && latest && ( + + )} + + !build.withdrawn).length}${withheld ? ` · ${withheld} withheld` : ""}`} + small + /> +
+
+
+ {SCALES.map((option) => ( + + ))} +
+ {periods.length > 1 && ( + ({ value: String(candidate), label: periodLabel(candidate, presentation.periodLabel) }))} + onChange={(next) => onPeriod(Number(next))} + /> + )} +

{modeNote}

+
+
+ columnReadout({ entry, builds, names, currency, relative: layout.relative, index })} + selectedIndex={stepIndex} + onSelect={onSelectStep} + /> +
+ +

+ Official reference: + {entry.reference?.status === "resolved" && official !== null + ? `${formatValue(official, entry.unit, currency)}, ${referenceLine(entry)}` + : referenceLine(entry)} +

+ {children} +
+ + Show the table of builds + Hide the table of builds + + +
+
+ ); +} diff --git a/frontend/components/microcosm/release-history-sections.tsx b/frontend/components/microcosm/release-history-sections.tsx new file mode 100644 index 00000000..3c6e6870 --- /dev/null +++ b/frontend/components/microcosm/release-history-sections.tsx @@ -0,0 +1,386 @@ +"use client"; + +import type { ReactNode } from "react"; + +import { SectionCard } from "@/components/shared/section-card"; +import { StatusPill, type StatusTone } from "@/components/shared/status-pill"; +import { + BUILD_MARK_LABELS, + buildStateLabel, + withoutRunCount, + type BuildMark, + type BuildsWithoutRun, +} from "@/lib/microcosm/release-history-builds"; +import { + dateLong, + dateShort, + engineLabel, + periodLabel, + shortHash, +} from "@/lib/microcosm/release-history-format"; +import type { StepSummary } from "@/lib/microcosm/release-history-moved"; +import { disclosureLine, namedBuilds, type EngineNotice } from "@/lib/microcosm/release-history-page"; +import type { TimelineBuild } from "@/lib/microcosm/release-history-store"; +import type { ReleaseHistoryPanelView } from "@/lib/microcosm/release-history-summary"; +import type { MovedScope } from "@/lib/microcosm/release-history-url"; + +import { moveLine } from "./release-history-step-card"; + +// The blocks of the release history page above its outputs (calibration-diagnostics#224): the +// notices about the engine on screen, the series facts, what moved at the latest build, and the +// builds of the series. Each takes what lib/microcosm computed and writes it in neutral words. + +function Notice({ children }: { children: ReactNode }) { + return ( +
+ {children} +
+ ); +} + +function PanelLink({ onClick, children }: { onClick: () => void; children: ReactNode }) { + return ( + + ); +} + +/** What the page says about the engine on screen, with a link to the other panel it names. */ +export function EngineNotices({ + notices, + onSelectPanel, +}: { + notices: readonly EngineNotice[]; + onSelectPanel: (panelId: string) => void; +}) { + return ( + <> + {notices.map((notice) => { + if (notice.kind === "newer_engine_filling") { + return ( + + A newer engine is being measured.{" "} + {notice.engine} + {notice.pinnedAt ? ` was pinned on ${dateLong(notice.pinnedAt)} and` : ""} holds {notice.coverage} so far. + This page opens it once it is complete.{" "} + onSelectPanel(notice.panelId)}>View {notice.engine} + + ); + } + if (notice.kind === "viewing_filling_engine") { + return ( + + This engine's panel is filling.{" "} + {notice.engine} holds {notice.coverage}. Until it is complete this page opens {notice.defaultEngine}.{" "} + onSelectPanel(notice.defaultPanelId)}>View {notice.defaultEngine} + + ); + } + if (notice.kind === "viewing_other_engine") { + return ( + + {notice.engine} was measured on request.{" "} + New builds are measured automatically on the pinned engine only.{" "} + onSelectPanel(notice.defaultPanelId)}>View {notice.defaultEngine} + + ); + } + return ( + + Another definition.{" "} + This panel was measured under another spec or producer version than the default one, so its outputs + and their values are not like for like with it. + + ); + })} + + ); +} + +/** The builds this engine has no value for, named by why (María, 26 November 2026). */ +export function BuildsWithoutRunNotice({ + without, + names, +}: { + without: BuildsWithoutRun; + names: ReadonlyMap; +}) { + const count = withoutRunCount(without); + if (count === 0) return null; + const groups: [string, TimelineBuild[]][] = [ + ["Never run on this engine", without.neverRun], + ["A run failed and will be tried again", without.retrying], + ["Out of attempts", without.failed], + ["The file was refused", without.refused], + ]; + return ( + + + {count} of {without.onAxis} builds {count === 1 ? "has" : "have"} no value on this engine. + {" "} + {count === 1 ? "It keeps its" : "They keep their"} column on the chart, shaded. +
    + {groups.filter(([, builds]) => builds.length > 0).map(([label, builds]) => ( +
  • + {label}: {namedBuilds(builds, names)} +
  • + ))} +
+ {without.neverRun.length > 0 && ( +

+ New builds are measured automatically on the pinned engine only. A run on another engine is started by hand. +

+ )} +
+ ); +} + +function Fact({ term, children }: { term: string; children: ReactNode }) { + return ( +
+
{term}
+
{children}
+
+ ); +} + +/** The series facts: the engine, the panel, the series rule, coverage and the disclosure policy. */ +export function SeriesFacts({ view }: { view: ReleaseHistoryPanelView }) { + const { panel, presentation, timeline } = view; + const { rule } = timeline.listing; + const measured = timeline.builds.filter((build) => build.state === "measured"); + const outside = measured.filter((build) => build.referenceModelCompatibility === "outside").length; + const periods = presentation.periods.map((period) => periodLabel(period, presentation.periodLabel)).join(", "); + return ( +
+ + {engineLabel(panel.engine.model)} + + {panel.engine.policyengine ? ` · policyengine ${panel.engine.policyengine}` : ""} + {panel.engine.core ? ` · ${engineLabel(panel.engine.core)}` : ""} + + + + {shortHash(panel.panelId, 12)} + + {panel.pinnedAt ? ` · pinned ${dateLong(panel.pinnedAt)}` : " · never pinned: measured on request"} + + + + {rule.releases.join(", ")} + + {rule.since ? ` · published from ${dateLong(`${rule.since}T00:00:00Z`)}` : " · every build"} + {` · listed ${dateLong(timeline.listing.listedAt)}`} + + + + {timeline.builds.length} builds listed · {panel.coverage.measured} of {panel.coverage.files} files measured + + {periods ? ` · ${periods}` : ""} + {outside > 0 ? ` · this engine is outside the model range that ${outside} of ${measured.length} measured builds declare` : ""} + + + {disclosureLine(presentation.disclosure)} +
+ ); +} + +const SCOPES: { id: MovedScope; label: string }[] = [ + { id: "headline", label: "Headline outputs" }, + { id: "all", label: "All outputs" }, +]; + +/** What moved at the latest build: the outputs ranked by their own typical step. */ +export function WhatMoved({ + summary, + builds, + names, + scope, + onScope, + onSelect, +}: { + /** Null when no build of the panel is measured. */ + summary: StepSummary | null; + builds: readonly TimelineBuild[]; + names: ReadonlyMap; + scope: MovedScope; + onScope: (scope: MovedScope) => void; + /** Opens an output with this step's card. */ + onSelect: (outputId: string, buildId: string) => void; +}) { + const build = summary ? builds[summary.buildIndex] : null; + const from = summary?.fromBuildId ? builds.find((candidate) => candidate.buildId === summary.fromBuildId) : null; + const named = (target: TimelineBuild) => `${dateShort(target.publishedAt)} (${names.get(target.buildId) ?? target.build})`; + const counts = summary + ? `${summary.moved.length} moved, ${summary.unchanged} did not move, ${summary.withheld} withheld${summary.noStep > 0 ? `, ${summary.noStep} with no step` : ""}.` + : ""; + return ( + + {SCOPES.map((option) => ( + + ))} + + } + footer={ + summary && build + ? `${counts} ${ + summary.rankedByTypical + ? "Ranked by each output's step beside its own typical step: the median of its earlier steps on this engine. An output with fewer than three earlier steps comes after, by the size of its step." + : "Ranked by the size of each step: no output that moved has the three earlier steps a typical step is taken from." + } Headline outputs: each baseline item's total, and each reform's budgetary impact and target.` + : undefined + } + > + {!summary || !build ? ( +

Nothing to rank yet.

+ ) : summary.sameFile ? ( +

+ The latest build publishes the file of an earlier build, so no output moved. +

+ ) : summary.moved.length === 0 ? ( +

+ {summary.fromBuildId + ? "No output moved at the latest build." + : "No output has a step to the latest build: this engine holds no value for the build before it."} +

+ ) : ( +
    + {summary.moved.slice(0, 6).map((move, index) => ( +
  1. + +
  2. + ))} +
+ )} +
+ ); +} + +const STATE_TONES: Record = { + measured: "success", + gap: "warning", + retrying: "warning", + failed: "danger", + missing: "neutral", +}; + +function Chip({ children, title }: { children: ReactNode; title?: string }) { + return ( + + {children} + + ); +} + +/** A build's state on this engine and its marks, as chips. */ +export function BuildChips({ + build, + builds, + marks, + withState = true, +}: { + build: TimelineBuild; + builds: readonly TimelineBuild[]; + marks: readonly BuildMark[]; + withState?: boolean; +}) { + const first = build.sameFileAs ? builds.find((candidate) => candidate.buildId === build.sameFileAs) : null; + return ( + + {withState && ( + + {buildStateLabel(build)} + + )} + {build.current && Current} + {build.sameFileAs && Same file as {first ? dateShort(first.publishedAt) : "an earlier build"}} + {build.withdrawn && Withdrawn} + {marks.includes("new_build_engine") && {BUILD_MARK_LABELS.new_build_engine}} + + ); +} + +/** The builds of the series, in publish order. A card opens that build's step card. */ +export function BuildsStrip({ + builds, + marks, + names, + selectedIndex, + onSelect, +}: { + builds: readonly TimelineBuild[]; + marks: readonly BuildMark[][]; + names: ReadonlyMap; + selectedIndex: number | null; + onSelect: (index: number) => void; +}) { + return ( +
+
+

+ Builds in the series +

+

+ In publish order. A step joins two neighbours that both hold the value; a withdrawn build is never a neighbour. +

+
+
+
    + {builds.map((build, index) => ( +
  1. + +
  2. + ))} +
+
+
+ ); +} diff --git a/frontend/components/microcosm/release-history-step-card.tsx b/frontend/components/microcosm/release-history-step-card.tsx new file mode 100644 index 00000000..bc13c59b --- /dev/null +++ b/frontend/components/microcosm/release-history-step-card.tsx @@ -0,0 +1,287 @@ +"use client"; + +import Link from "next/link"; +import type { ReactNode } from "react"; + +import type { BuildFacts, StepFacts } from "@/lib/microcosm/release-history-builds"; +import { + dateLong, + dateTimeUtc, + formatChange, + formatPercent, + formatPoints, + formatValue, + shortHash, + versusOfficial, +} from "@/lib/microcosm/release-history-format"; +import type { StepMove, StepSummary } from "@/lib/microcosm/release-history-moved"; +import type { OutputEntry } from "@/lib/microcosm/release-history-outputs"; + +// The step card of the release history page (calibration-diagnostics#224): what the two builds +// of a step declare, side by side, and what the selected output did across it. Every fact comes +// from the timeline: listing facts, and what each build's point was fetched with. + +const NONE = "—"; + +function Changed({ changed }: { changed: boolean | null }) { + if (changed === null) return null; + return ( + + {changed ? "Changed" : "Unchanged"} + + ); +} + +function Commit({ facts }: { facts: BuildFacts }) { + if (!facts.codeCommit) return <>{NONE}; + const short = shortHash(facts.codeCommit); + return facts.commitUrl ? ( + + {short} + + ) : ( + {short} + ); +} + +function compatibility(facts: BuildFacts): string { + const range = facts.compatibleModels ? ` (${facts.compatibleModels})` : ""; + switch (facts.build.referenceModelCompatibility) { + case "inside": + return `Inside the range it declares${range}`; + case "outside": + return `Outside the range it declares${range}`; + case "undeclared": + return "It declares no range for this model"; + case "unreadable": + return "Its declared range could not be read"; + default: + return NONE; + } +} + +function columns(facts: BuildFacts): string { + const names = facts.build.unknownColumns; + if (names === null || names === undefined) return NONE; + return names.length === 0 ? "None" : `${names.length}: ${names.join(", ")}`; +} + +/** Each fact of the step: a label, and one cell per build. */ +function factRows(step: StepFacts): { label: string; cell: (facts: BuildFacts) => ReactNode; changed?: boolean | null }[] { + return [ + { label: "Published", cell: (facts) => dateTimeUtc(facts.build.publishedAt) }, + { label: "Built", cell: (facts) => dateTimeUtc(facts.builtAt) }, + { label: "Microcosm commit", cell: (facts) => }, + { label: "Built with model", cell: (facts) => facts.builtWithModel ?? NONE, changed: step.buildEngineChanged }, + { label: "Built with core", cell: (facts) => facts.builtWithCore ?? NONE }, + { + label: "Targets", + cell: (facts) => (facts.nTargets === null ? NONE : facts.nTargets.toLocaleString("en-GB")), + changed: step.targetSetChanged, + }, + { label: "Target registry", cell: (facts) => facts.targetRegistryVersion ?? NONE, changed: step.targetRegistryChanged }, + { label: "Household weight year", cell: (facts) => facts.householdWeightYear ?? NONE }, + { + label: "Data file", + cell: (facts) => ( + <> + {shortHash(facts.build.digest)} + {facts.build.sameFileAs && · the file of an earlier build} + + ), + }, + { label: "Reference model", cell: compatibility }, + { label: "Columns the model does not define", cell: columns }, + ]; +} + +function FactsTable({ step, names }: { step: StepFacts; names: ReadonlyMap }) { + const builds = step.from ? [step.from, step.to] : [step.to]; + const heading = (facts: BuildFacts) => ( + + {dateLong(facts.build.publishedAt)} + + {names.get(facts.build.buildId) ?? facts.build.build} + + + ); + return ( +
+ + + + + {builds.map(heading)} + + + + {factRows(step).map((row) => ( + + + {builds.map((facts) => ( + + ))} + + ))} + +
+ {step.from ? "The two builds" : "The build"} +
+ {row.label} + {step.from && } + + {facts.declared || ["Published", "Data file"].includes(row.label) ? row.cell(facts) : NONE} +
+
+ ); +} + +/** One line on how a move sits beside the output's own history and its official figure. */ +export function moveLine(move: StepMove): string { + const size = !Number.isFinite(move.signed) + ? "moved away from zero" + : move.measure === "points" ? formatPoints(move.signed) : formatPercent(move.signed); + const typical = move.typical === null + ? "fewer than three earlier steps" + : move.ratio === Number.POSITIVE_INFINITY + ? "it had not moved before" + : `${(move.ratio ?? 0).toFixed(1)}× its typical step`; + const official = move.official === null || move.official.direction === "same" + ? "" + : `, ${move.official.direction === "nearer" ? "nearer to" : "further from"} the official figure`; + return `${size} · ${typical}${official}`; +} + +function OutputAcrossStep({ + entry, + index, + currency, +}: { + entry: OutputEntry; + index: number; + currency: string | null; +}) { + const value = entry.values[index]; + const text = (shown: OutputEntry["values"][number]) => + shown.status === "withheld" ? "Withheld" : shown.value === null ? "No value" : formatValue(shown.value, entry.unit, currency, 2); + const versus = (shown: OutputEntry["values"][number]) => + entry.official !== null && shown.value !== null + ? ` (${formatPercent(versusOfficial(shown.value, entry.official))} against the official figure)` + : ""; + return ( +
+
{entry.fullLabel}
+
+ {text(value)} + {versus(value)} +
+
+ Step from the build before: {formatChange(value, entry.unit, currency)} +
+
+ ); +} + +export function ReleaseHistoryStepCard({ + step, + summary, + entry, + index, + currency, + country, + names, + onSelectOutput, + onClose, +}: { + step: StepFacts; + /** What every output of the selected period did at this build. */ + summary: StepSummary; + entry: OutputEntry | null; + index: number; + currency: string | null; + country: string; + names: ReadonlyMap; + onSelectOutput: (id: string) => void; + onClose: () => void; +}) { + const name = (facts: BuildFacts) => names.get(facts.build.buildId) ?? facts.build.build; + const fit = (facts: BuildFacts) => ({ + pathname: "/microcosm", + query: { country, release: facts.build.buildId }, + }); + const title = step.from && !step.noStepReason + ? `Step from ${dateLong(step.from.build.publishedAt)} to ${dateLong(step.to.build.publishedAt)}` + : `Build of ${dateLong(step.to.build.publishedAt)}`; + const undeclared = !step.to.declared && step.to.build.state === "measured"; + return ( +
+
+
+

{title}

+

{name(step.to)}

+
+ +
+ {step.noStepReason &&

{step.noStepReason}

} + {entry && } + {undeclared && ( +

+ This timeline was written before it carried what each build declares. The facts appear after the next run. +

+ )} + + {step.from && (step.columnsAdded.length > 0 || step.columnsRemoved.length > 0) && ( +

+ Columns the reference model does not define: + {step.columnsAdded.length > 0 && ` added ${step.columnsAdded.join(", ")}`} + {step.columnsAdded.length > 0 && step.columnsRemoved.length > 0 && ";"} + {step.columnsRemoved.length > 0 && ` removed ${step.columnsRemoved.join(", ")}`}. +

+ )} + {!step.noStepReason && ( +
+
Every output at this step
+

+ {summary.moved.length} moved, {summary.unchanged} did not move, {summary.withheld} withheld + {summary.noStep > 0 ? `, ${summary.noStep} with no step` : ""}. + {summary.sameFile && " This build publishes the file of an earlier build, so no output can have moved."} +

+ {summary.moved.length > 0 && ( +
    + {summary.moved.slice(0, 5).map((move) => ( +
  1. + +
  2. + ))} +
+ )} +
+ )} +
+ {step.compareUrl && ( + + Compare the two Microcosm commits on GitHub + + )} + {(step.from ? [step.from, step.to] : [step.to]).map((facts) => ( + + Calibration fit of {name(facts)} + + ))} +
+
+ ); +} diff --git a/frontend/components/microcosm/release-history-view.test.tsx b/frontend/components/microcosm/release-history-view.test.tsx new file mode 100644 index 00000000..7d3b92d8 --- /dev/null +++ b/frontend/components/microcosm/release-history-view.test.tsx @@ -0,0 +1,202 @@ +import { expect, test } from "bun:test"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; + +import { dateShort } from "@/lib/microcosm/release-history-format"; +import { readReleaseHistoryManifest } from "@/lib/microcosm/release-history-read"; +import { + releaseHistorySummary, + type ReleaseHistoryPanelView, + type ReleaseHistorySummary, +} from "@/lib/microcosm/release-history-summary"; +import { releaseHistoryUrlState, type ReleaseHistoryUrlState } from "@/lib/microcosm/release-history-url"; +import { sharedSyntheticReleaseHistory } from "@/lib/microcosm/test-support/release-history-synthetic-store"; +import { syntheticPanelView } from "@/lib/microcosm/test-support/release-history-synthetic-view"; +import { ReleaseHistoryActions, ReleaseHistoryPanel } from "./release-history-view"; + +// The page on the synthetic store, rendered to static markup: what a reader is told, in words. + +async function summaryOf(country: "uk" | "us"): Promise { + const { store } = await sharedSyntheticReleaseHistory(); + return releaseHistorySummary(country, await readReleaseHistoryManifest(store)); +} + +function state(patch: Partial = {}): ReleaseHistoryUrlState { + return { ...releaseHistoryUrlState(new URLSearchParams()), ...patch }; +} + +function text(markup: string): string { + return markup + .replace(/<[^>]+>/g, " ") + .replace(/&/g, "&").replace(/'/g, "'").replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">") + .replace(/\s+/g, " "); +} + +async function page( + country: "uk" | "us", + engine: "earlier" | "newer" | "other", + patch: Partial = {}, + change: (view: ReleaseHistoryPanelView) => ReleaseHistoryPanelView = (view) => view, +) { + const view = change(await syntheticPanelView(country, engine)); + const markup = renderToStaticMarkup( + createElement(ReleaseHistoryPanel, { summary: await summaryOf(country), view, state: state(patch), onState: () => {} }), + ); + return { view, markup, said: text(markup) }; +} + +const buildOn = (view: ReleaseHistoryPanelView, date: string) => + view.timeline.builds.find((build) => dateShort(build.publishedAt) === date)!; + +test("the default view names the engine, what it lacks, what moved, the builds and the first output", async () => { + const { said, markup } = await page("uk", "earlier"); + // After an engine bump the page shows the served panel and says a newer engine is filling. + expect(said).toContain("A newer engine is being measured. policyengine-uk 1.1.0 was pinned on 25 Nov 2026 and holds 7 of 10 files so far."); + expect(said).toContain("View policyengine-uk 1.1.0"); + // The builds this engine has no value for are named, by why. + expect(said).toContain("3 of 11 builds have no value on this engine."); + expect(said).toMatch(/Never run on this engine: 17 Nov \(20261117T020400Z-[0-9a-f]{8}\), 24 Nov \(20261124T020400Z-[0-9a-f]{8}\)/); + expect(said).toMatch(/The file was refused: 24 Oct \(/); + expect(said).toContain("New builds are measured automatically on the pinned engine only."); + // The series facts. + expect(said).toContain("policyengine-uk 1.0.0 · policyengine 6.16.1 · policyengine-core 3.33.3"); + expect(said).toContain("microcosm-uk-2024-25-national · published from 19 Oct 2026"); + expect(said).toContain("12 builds listed · 7 of 10 files measured · 2026-27"); + expect(said).toContain("A value that rests on fewer than 3 survey households is withheld, with any partner cell that would give it back."); + // What moved, the builds, and the first output of the spec. + expect(said).toContain("What moved at the latest build"); + expect(said).toMatch(/From 7 Nov \([^)]+\) to 10 Nov \([^)]+\), on this engine\./); + expect(said).toContain("Ranked by each output's step beside its own typical step"); + expect(said).toContain("Builds in the series"); + for (const chip of ["Measured", "File refused", "Not measured", "Withdrawn", "Same file as 21 Oct", "Current", "New build engine"]) { + expect(said).toContain(chip); + } + expect(said).toContain("Receipts Income tax 2026-27 · in GBP"); + expect(said).toContain("Each release as a % above or below the official figure, £"); + expect(said).toContain("0% = official £"); + expect(said).toContain("Official reference: £"); + // The table is there for every reader, closed until asked for. + expect(markup).toContain(" { + const { said } = await page("uk", "earlier", { output: "reform/basic_rate_plus_1p/budgetary_impact" }); + expect(said).toContain("Reform · Basic rate +1p Budgetary impact"); + expect(said).toContain("No official figure for this output, so it shows values."); + expect(said).toContain("Official reference: cited, with no value yet: HM Revenue & Customs"); + expect(said).not.toContain("0% = official"); + const absolute = await page("uk", "earlier", { scale: "absolute" }); + expect(absolute.said).toContain("Values, in GBP."); + expect(absolute.said).toContain("Official £"); +}); + +test("an output whose id spells gaining or losing is shown in neutral words only", async () => { + // The producer's ids for these four outputs are `households_gaining` and the like. The page + // labels them, and never prints the id. + for (const kind of ["households_gaining", "households_losing", "people_gaining", "people_losing"]) { + const { said } = await page("uk", "earlier", { output: `reform/basic_rate_plus_1p/${kind}`, moved: "all" }); + expect(said).toMatch(/(Households|People) with (higher|lower) net income \d{4}-\d{2} · a count/); + expect(said).not.toMatch(/gaining|losing|winner|loser/i); + } +}); + +test("a withheld cell is shown as withheld and no number of it reaches the page", async () => { + const output = "baseline/household_net_income_mean/decile_1"; + const { said, view } = await page("uk", "earlier", { output, scale: "absolute" }); + expect(said).toContain("withheld"); + expect(said).toContain("4 withheld"); + expect(said).toMatch(/Step from the build before\s+Withheld/); + + // A timeline that wrongly carried numbers beside a withheld status: none is rendered anywhere. + const leaked = await page("uk", "earlier", { output, scale: "absolute", step: buildOn(view, "2 Nov").buildId }, (clean) => { + const copy = structuredClone(clean); + const raw = copy.timeline.outputs.find((candidate) => candidate.output === output)!; + for (const value of raw.values) { + if (value.status !== "withheld") continue; + Object.assign(value, { value: 987654.321, change: 123456.789, relativeChange: 0.4242, changePoints: 42.42 }); + } + return copy; + }); + // However the page would write them: in full, grouped, compact, or as a percentage. + for (const number of ["987654", "987,654", "987.65", "123456", "123,457", "123.46", "42.42"]) { + expect(leaked.markup).not.toContain(number); + } + expect(leaked.said).toMatch(/Household net income mean, decile 1\s+Withheld/); +}); + +test("a step's card sets the two builds side by side, from the build before the withdrawn one", async () => { + const served = await syntheticPanelView("uk"); + const { said, markup } = await page("uk", "earlier", { step: buildOn(served, "2 Nov").buildId }); + expect(said).toContain("Step from 27 Oct 2026 to 2 Nov 2026"); + expect(said).toContain("Built with model Changed policyengine-uk 0.9.0 policyengine-uk 0.10.0"); + expect(said).toContain("Targets Changed 1,200 1,214"); + expect(said).toContain("Target registry Unchanged 2026.10 2026.10"); + expect(said).toContain("Outside the range it declares (policyengine-uk ==0.10.0)"); + expect(said).toContain("Columns the reference model does not define: added synthetic_new_column."); + expect(said).toMatch(/Every output at this step \d+ moved, \d+ did not move, \d+ withheld/); + expect(markup).toMatch(/href="https:\/\/github\.com\/PolicyEngine\/microcosm\/compare\/[0-9a-f]{40}\.\.\.[0-9a-f]{40}"/); + expect(said).toContain("Compare the two Microcosm commits on GitHub"); + expect(markup).toMatch(/href="\/microcosm\?country=uk&release=microcosm-uk-2024-25-national%2Fsynthetic-/); + // The selected column and card are marked for assistive technology. + expect(markup).toContain('aria-pressed="true"'); + + const withdrawn = await page("uk", "earlier", { step: buildOn(served, "29 Oct").buildId }); + expect(withdrawn.said).toContain("Build of 29 Oct 2026"); + expect(withdrawn.said).toContain("This build was withdrawn, so no step starts or ends at it."); + const afterGap = await page("uk", "earlier", { step: buildOn(served, "27 Oct").buildId }); + expect(afterGap.said).toContain("This engine holds no value for the build before it."); +}); + +test("on the pinned engine that is still filling, the page says so and names its failed and retrying builds", async () => { + const { said } = await page("uk", "newer"); + expect(said).toContain("This engine's panel is filling. policyengine-uk 1.1.0 holds 7 of 10 files. Until it is complete this page opens policyengine-uk 1.0.0."); + expect(said).toMatch(/A run failed and will be tried again: 24 Nov \(/); + expect(said).toMatch(/Out of attempts: 5 Nov \(/); + // The states are named for what happened to the run, on the chips and on the chart alike. + expect(said).toContain("Retrying"); + expect(said).not.toMatch(/\bFailed\b|\bGap\b/); + expect(said).not.toContain("Never run on this engine"); +}); + +test("an engine measured on request under another definition says both, and a complete panel says neither", async () => { + const other = await page("us", "other"); + expect(other.said).toContain("policyengine-us 0.9.0 was measured on request."); + expect(other.said).toContain("Another definition."); + expect(other.said).toContain("never pinned: measured on request"); + expect(other.said).toContain("4 of 6 builds have no value on this engine."); + const complete = await page("us", "earlier"); + expect(complete.said).not.toContain("measured on request"); + expect(complete.said).not.toContain("have no value on this engine"); + expect(complete.said).toContain("No value is withheld: this country's policy checks none."); + // No US output has an official figure in the references, so every chart shows values. + expect(complete.said).toContain("No official figure for this output, so it shows values."); +}); + +test("a URL that names an output or a step this panel does not hold opens the defaults", async () => { + const { said } = await page("us", "earlier", { output: "baseline/not_an_output", step: "line/not-a-build", period: 1999 }); + expect(said).toContain("Receipts Income tax 2026 · in USD"); + // No step card: neither a step's nor a single build's. + expect(said).not.toContain("The two builds"); + expect(said).not.toContain("Build of "); +}); + +test("the header offers each engine's panel and the table as a CSV", async () => { + const summary = await summaryOf("uk"); + const markup = renderToStaticMarkup( + createElement(ReleaseHistoryActions, { summary, panelId: summary.defaultPanelId!, onSelectPanel: () => {} }), + ); + expect(text(markup)).toContain("policyengine-uk 1.0.0 · 7 of 10 files"); + expect(text(markup)).toContain("policyengine-uk 1.1.0 · 7 of 10 files"); + expect(markup).toContain( + `href="/calibration/dashboard/api/microcosm/release-history/export?country=uk&panel=${summary.defaultPanelId}"`, + ); + expect(text(markup)).toContain("Download CSV"); +}); diff --git a/frontend/components/microcosm/release-history-view.tsx b/frontend/components/microcosm/release-history-view.tsx new file mode 100644 index 00000000..921115f5 --- /dev/null +++ b/frontend/components/microcosm/release-history-view.tsx @@ -0,0 +1,282 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useRef } from "react"; +import { useSearchParams } from "next/navigation"; +import { Button } from "@policyengine/ui-kit"; + +import { useCountry } from "@/components/layout/country-context"; +import { CountryNotConfiguredState } from "@/components/microcosm/country-not-configured"; +import { EmptyState } from "@/components/shared/empty-state"; +import { LoadingBlock } from "@/components/shared/LoadingBlock"; +import { PageHeader } from "@/components/shared/page-header"; +import { ToolbarSelect } from "@/components/shared/toolbar-select"; +import { countryNotConfiguredError } from "@/lib/api/client"; +import { + releaseHistoryExportUrl, + useReleaseHistoryPanel, + useReleaseHistorySummary, +} from "@/lib/api/hooks/use-release-history"; +import { + buildMarks, + buildsWithoutRun, + stepFacts, +} from "@/lib/microcosm/release-history-builds"; +import { shortBuildNames } from "@/lib/microcosm/release-history-format"; +import { latestMeasuredBuild, stepSummary } from "@/lib/microcosm/release-history-moved"; +import { + engineNotices, + engineOptions, + pageSelection, + selectedPanelId, + staleState, +} from "@/lib/microcosm/release-history-page"; +import type { + ReleaseHistoryPanelView, + ReleaseHistorySummary, +} from "@/lib/microcosm/release-history-summary"; +import { + releaseHistoryUrlState, + withReleaseHistoryState, + type ReleaseHistoryUrlState, +} from "@/lib/microcosm/release-history-url"; +import { countryRegistration } from "@policyengine/calibration-tree/countries"; + +import { OutputDetail, OutputNavigator } from "./release-history-output-detail"; +import { + BuildsStrip, + BuildsWithoutRunNotice, + EngineNotices, + SeriesFacts, + WhatMoved, +} from "./release-history-sections"; +import { ReleaseHistoryStepCard } from "./release-history-step-card"; + +// The release history page (calibration-diagnostics#224): every national data file a country +// publishes, measured on one fixed engine, so a move between two releases comes from the data +// and not the model. It reads the stored `timeline.json` of one panel, and keeps its state (the +// engine's panel, the output, the scale, the open step) in the URL. + +const DESCRIPTION = + "Every national data file this country publishes, measured on one fixed engine, so a move between two releases comes from the data and not the model."; + +function Header({ actions }: { actions?: React.ReactNode }) { + return ; +} + +/** One loaded panel: the notices, the facts, what moved, the builds and the outputs. */ +export function ReleaseHistoryPanel({ + summary, + view, + state, + onState, + settled = false, +}: { + summary: ReleaseHistorySummary; + view: ReleaseHistoryPanelView; + state: ReleaseHistoryUrlState; + /** Writes part of the page's state to the URL. */ + onState: (patch: Partial) => void; + /** + * Whether `view` is the panel the URL names, and not the one kept on screen while it loads. Only + * then is a value of the URL this panel cannot use taken out of the URL. + */ + settled?: boolean; +}) { + const { timeline, presentation } = view; + const builds = timeline.builds; + const { output, period, step: openStep, moved: scope } = state; + const selection = useMemo( + () => pageSelection(view, { output, period, step: openStep }), + [view, output, period, openStep], + ); + useEffect(() => { + if (!settled) return; + const stale = staleState(selection, { output, period, step: openStep }); + if (Object.keys(stale).length > 0) onState(stale); + }, [settled, selection, output, period, openStep, onState]); + const marks = useMemo(() => buildMarks(builds), [builds]); + const names = useMemo(() => shortBuildNames(builds), [builds]); + const without = useMemo(() => buildsWithoutRun(builds), [builds]); + const notices = engineNotices(summary, view.panelId); + const latest = latestMeasuredBuild(builds); + const moved = useMemo(() => { + if (latest === null) return null; + const ranked = scope === "all" ? selection.periodEntries : selection.periodEntries.filter((candidate) => candidate.headline); + return stepSummary(ranked, builds, latest); + }, [latest, builds, selection.periodEntries, scope]); + const { stepIndex, entry } = selection; + const step = stepIndex === null ? null : stepFacts(builds, stepIndex); + const atStep = useMemo( + () => (stepIndex === null ? null : stepSummary(selection.periodEntries, builds, stepIndex)), + [stepIndex, selection.periodEntries, builds], + ); + const selectStep = (index: number) => + onState({ step: stepIndex === index ? null : builds[index]?.buildId ?? null }); + // A row of "what moved" opens an output and its step further down the page: bring them into view. + const outputs = useRef(null); + const openMove = (movedOutput: string, buildId: string) => { + onState({ output: movedOutput, step: buildId }); + const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches; + outputs.current?.scrollIntoView({ behavior: still ? "auto" : "smooth", block: "start" }); + }; + return ( + <> + onState({ panel: panelId })} /> + + + onState({ moved: scope })} + onSelect={openMove} + /> + + {entry ? ( +
+ onState({ output })} + /> + onState({ scale })} + onPeriod={(period) => onState({ period })} + onSelectOutput={(output) => onState({ output })} + onSelectStep={selectStep} + > + {step && atStep && stepIndex !== null && ( + onState({ output })} + onClose={() => onState({ step: null })} + /> + )} + +
+ ) : ( + + )} + + ); +} + +/** The engine toggle and the CSV download, for the page header. */ +export function ReleaseHistoryActions({ + summary, + panelId, + onSelectPanel, +}: { + summary: ReleaseHistorySummary; + panelId: string; + onSelectPanel: (panelId: string) => void; +}) { + return ( + <> + + + + ); +} + +export function ReleaseHistoryView() { + const { country } = useCountry(); + const searchParams = useSearchParams(); + // Read from the URL on every render, so Back, Forward and a pasted link all open the same view. + const search = searchParams.toString(); + const state = useMemo(() => releaseHistoryUrlState(new URLSearchParams(search)), [search]); + const onState = useCallback((patch: Partial) => { + window.history.replaceState(null, "", withReleaseHistoryState(window.location.href, patch)); + }, []); + const summaryQuery = useReleaseHistorySummary(); + const summary = summaryQuery.data; + const panelId = summary?.available ? selectedPanelId(summary, state.panel) : null; + const panelQuery = useReleaseHistoryPanel(panelId, panelId !== null); + const label = countryRegistration(country).label; + // A panel the country does not have, as a link kept across a change of country names, leaves + // the URL once the country's panels are known. + const stalePanel = Boolean(summary?.available) && state.panel !== null && state.panel !== panelId; + useEffect(() => { + if (stalePanel) onState({ panel: null }); + }, [stalePanel, onState]); + + const notConfigured = countryNotConfiguredError(summaryQuery.error) ?? countryNotConfiguredError(panelQuery.error); + if (notConfigured) { + return ; + } + let body: React.ReactNode; + if (summaryQuery.error) { + body = ; + } else if (!summary) { + body = ; + } else if (!summary.available || panelId === null) { + body = ( + + ); + } else if (panelQuery.error && !panelQuery.data) { + body = ; + } else if (!panelQuery.data) { + body = ; + } else { + // While another engine's panel loads, the one on screen stays, dimmed. + body = ( +
+ +
+ ); + } + return ( +
+
onState({ panel: next })} /> + ) : undefined + } + /> + {body} +
+ ); +} diff --git a/frontend/lib/api/hooks/use-release-history.ts b/frontend/lib/api/hooks/use-release-history.ts new file mode 100644 index 00000000..c96de7c7 --- /dev/null +++ b/frontend/lib/api/hooks/use-release-history.ts @@ -0,0 +1,49 @@ +import { keepPreviousData, useQuery } from "@tanstack/react-query"; + +import { useCountry } from "@/components/layout/country-context"; +import { LATEST_RELEASE_STALE_TIME_MS } from "@/lib/api/cache-policy"; +import { withBasePath } from "@/lib/base-path"; +import type { + ReleaseHistoryPanelView, + ReleaseHistorySummary, +} from "@/lib/microcosm/release-history-summary"; + +import { apiGet } from "../client"; + +// The release history page's two reads (calibration-diagnostics#224). Both documents change at +// each run, so they are refetched after a minute like the other "latest" reads. + +/** The country's panels, one per reference engine, and the panel the page opens. */ +export function useReleaseHistorySummary() { + const { country } = useCountry(); + return useQuery({ + queryKey: ["microcosm", "release-history", country], + queryFn: () => apiGet("/microcosm/release-history", { country }), + staleTime: LATEST_RELEASE_STALE_TIME_MS, + }); +} + +/** + * One panel's timeline. While another engine's panel loads, the page keeps the one it shows, so + * the engine toggle never empties it. + */ +export function useReleaseHistoryPanel(panelId: string | null, enabled: boolean) { + const { country } = useCountry(); + return useQuery({ + queryKey: ["microcosm", "release-history-panel", country, panelId ?? "default"], + queryFn: () => + apiGet("/microcosm/release-history/timeline", { + country, + panel: panelId ?? undefined, + }), + staleTime: LATEST_RELEASE_STALE_TIME_MS, + enabled, + placeholderData: keepPreviousData, + }); +} + +/** Where a panel's table downloads from, as a CSV. */ +export function releaseHistoryExportUrl(country: string, panelId: string): string { + const params = new URLSearchParams({ country, panel: panelId }); + return withBasePath(`/api/microcosm/release-history/export?${params.toString()}`); +} diff --git a/frontend/lib/microcosm/release-history-builds.test.ts b/frontend/lib/microcosm/release-history-builds.test.ts index 9f0e6d98..20a331a0 100644 --- a/frontend/lib/microcosm/release-history-builds.test.ts +++ b/frontend/lib/microcosm/release-history-builds.test.ts @@ -67,9 +67,9 @@ test("the builds an engine has no run for are named by why, and a withdrawn buil test("a build's state reads in the page's words", () => { expect(buildStateLabel({ state: "measured", status: "ok" })).toBe("Measured"); expect(buildStateLabel({ state: "measured", status: "partial" })).toBe("Partial"); - expect(buildStateLabel({ state: "gap", status: "refused" })).toBe("Gap"); + expect(buildStateLabel({ state: "gap", status: "refused" })).toBe("File refused"); expect(buildStateLabel({ state: "retrying", status: null })).toBe("Retrying"); - expect(buildStateLabel({ state: "failed", status: null })).toBe("Failed"); + expect(buildStateLabel({ state: "failed", status: null })).toBe("Out of attempts"); expect(buildStateLabel({ state: "missing", status: null })).toBe("Not measured"); }); diff --git a/frontend/lib/microcosm/release-history-builds.ts b/frontend/lib/microcosm/release-history-builds.ts index 0e04f10e..fabdd92d 100644 --- a/frontend/lib/microcosm/release-history-builds.ts +++ b/frontend/lib/microcosm/release-history-builds.ts @@ -67,7 +67,7 @@ export function buildMarks(builds: readonly TimelineBuild[]): BuildMark[][] { /** * The builds on the axis this panel holds no value for, by why: never run on this engine, a run * that failed and will be tried again, one that ran out of attempts, or a file the producer - * refused (a gap on every engine). A withdrawn build is never measured, so it is not listed. + * refused (the store's "gap"). A withdrawn build is never measured, so it is not listed. */ export interface BuildsWithoutRun { neverRun: TimelineBuild[]; @@ -97,7 +97,9 @@ export function withoutRunCount(without: BuildsWithoutRun): number { /** One build's state on the panel, in the page's words. */ export function buildStateLabel(build: Pick): string { if (build.state === "measured") return build.status === "partial" ? "Partial" : "Measured"; - return { gap: "Gap", retrying: "Retrying", failed: "Failed", missing: "Not measured" }[build.state]; + // The store's states `gap` and `failed` are named for what happened: the producer refused the + // file, or the runs that tried to measure it ran out of attempts. Neither is a verdict on the build. + return { gap: "File refused", retrying: "Retrying", failed: "Out of attempts", missing: "Not measured" }[build.state]; } const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; diff --git a/frontend/lib/microcosm/release-history-chart.test.ts b/frontend/lib/microcosm/release-history-chart.test.ts index 99e55e6c..588d9914 100644 --- a/frontend/lib/microcosm/release-history-chart.test.ts +++ b/frontend/lib/microcosm/release-history-chart.test.ts @@ -49,7 +49,10 @@ test("the relative view places each value as a percentage of the official figure expect(Math.sign(first.versus - second.versus)).toBe(Math.sign(second.y - first.y)); // The latest value is the one labelled, as a percentage; the two newest builds have no run here. const latest = at(timeline, "10 Nov"); - expect(layout.latestLabel).toMatchObject({ x: layout.columns[latest].x, anchor: "middle" }); + // The next column is shaded, so the label ends at its own column's edge. + expect(layout.latestLabel).toMatchObject({ anchor: "end" }); + expect(layout.latestLabel!.x).toBeLessThanOrEqual(layout.columns[latest + 1].left); + expect(layout.latestLabel!.x).toBeGreaterThan(layout.columns[latest].x); expect(layout.latestLabel!.text).toMatch(/^[+−]\d+\.\d\d%$/); }); @@ -77,7 +80,7 @@ test("every build keeps its column: a build with no value is shaded and labelled const served = await ukChart("baseline/income_tax", "relative"); const band = (date: string) => served.layout.columns[at(served.timeline, date)]; expect(served.layout.columns).toHaveLength(served.timeline.builds.length); - expect(band("24 Oct")).toMatchObject({ band: "gap", point: null }); + expect(band("24 Oct")).toMatchObject({ band: "file refused", point: null }); expect(band("17 Nov")).toMatchObject({ band: "not measured", point: null }); expect(band("24 Nov")).toMatchObject({ band: "not measured", point: null, current: true }); expect(band("19 Oct")).toMatchObject({ band: null }); @@ -88,7 +91,7 @@ test("every build keeps its column: a build with no value is shaded and labelled const pinnedBand = (date: string) => pinned.layout.columns[at(pinned.timeline, date)]; // Never measured on the newer engine, which was pinned after the withdrawal. expect(pinnedBand("29 Oct")).toMatchObject({ band: "withdrawn", point: null }); - expect(pinnedBand("5 Nov")).toMatchObject({ band: "failed", point: null }); + expect(pinnedBand("5 Nov")).toMatchObject({ band: "out of attempts", point: null }); expect(pinnedBand("24 Nov")).toMatchObject({ band: "retrying", point: null }); expect(pinnedBand("17 Nov")).toMatchObject({ band: null }); // The axis is the same on both engines. @@ -148,7 +151,9 @@ test("why a column is empty follows the build's state and the cell's status", () // A measured build whose point has no such cell, as after a reform that failed. expect(columnBand(build, "missing")).toBe("no value"); expect(columnBand({ ...build, state: "missing" }, "unmeasured")).toBe("not measured"); - expect(columnBand({ ...build, state: "gap" }, "unmeasured")).toBe("gap"); + expect(columnBand({ ...build, state: "gap" }, "unmeasured")).toBe("file refused"); + expect(columnBand({ ...build, state: "failed" }, "unmeasured")).toBe("out of attempts"); + expect(columnBand({ ...build, state: "retrying" }, "unmeasured")).toBe("retrying"); expect(columnBand({ ...build, withdrawn: true }, "ok")).toBe("withdrawn"); }); @@ -188,6 +193,33 @@ test("one value still gets a scale around it", () => { expect(layout.latestLabel).toMatchObject({ text: "£100", anchor: "end" }); }); +test("the latest value's label sits clear of the line that reaches it", () => { + const rising = small(smallTimeline({ builds: [{}, {}], outputs: { "baseline/tax": ["currency", [100, 104]] } }), "absolute"); + const falling = small(smallTimeline({ builds: [{}, {}], outputs: { "baseline/tax": ["currency", [104, 100.5]] } }), "absolute"); + const point = (chart: typeof rising) => chart.layout.columns[1].point!.y; + // A line that climbs to the point leaves the room above it; one that comes down leaves the room below. + expect(rising.layout.latestLabel!.y).toBeLessThan(point(rising)); + expect(falling.layout.latestLabel!.y).toBeGreaterThan(point(falling)); + expect(falling.layout.latestLabel!.y).toBeLessThan(falling.layout.plot.bottom); +}); + +test("ticks close together are written with the decimals that tell them apart", () => { + const timeline = smallTimeline({ + builds: [{}, {}, {}], + outputs: { "baseline/tax": ["currency", [25_600_000_000, 25_640_000_000, 25_680_000_000]] }, + }); + const labels = small(timeline, "absolute").layout.ticks.map((tick) => tick.label); + expect(new Set(labels).size).toBe(labels.length); + expect(labels).toContain("£25.62bn"); + const rates = smallTimeline({ + builds: [{}, {}], + outputs: { "baseline/share": ["rate", [0.1801, 0.1803]] }, + }); + const rateLabels = small(rates, "absolute").layout.ticks.map((tick) => tick.label); + expect(new Set(rateLabels).size).toBe(rateLabels.length); + expect(rateLabels.every((label) => label.endsWith("%"))).toBe(true); +}); + test("axis values are round and cover the range", () => { expect(niceTicks(-3.2, 4.1)).toEqual({ ticks: [-4, -2, 0, 2, 4, 6], min: -4, max: 6 }); expect(niceTicks(0, 10)).toEqual({ ticks: [0, 2.5, 5, 7.5, 10], min: 0, max: 10 }); diff --git a/frontend/lib/microcosm/release-history-chart.ts b/frontend/lib/microcosm/release-history-chart.ts index 5e874b2c..15019abd 100644 --- a/frontend/lib/microcosm/release-history-chart.ts +++ b/frontend/lib/microcosm/release-history-chart.ts @@ -12,6 +12,7 @@ import type { BuildMark } from "./release-history-builds"; import { dateShort, + formatAxisValue, formatPercent, formatValue, versusOfficial, @@ -25,9 +26,9 @@ export type ColumnBand = | "withdrawn" | "withheld" | "not measured" - | "gap" + | "file refused" | "retrying" - | "failed" + | "out of attempts" | "no value"; export interface ChartColumn { @@ -68,12 +69,18 @@ export interface ChartLayout { } export const CHART_HEIGHT = 330; -const MARGIN = { top: 18, right: 18, bottom: 64, left: 72 }; +// The top margin leaves room for the latest value's label above a point at the top of the plot. +const MARGIN = { top: 26, right: 18, bottom: 64, left: 72 }; /** The least room a publish date needs under the axis. */ const DATE_LABEL_WIDTH = 46; /** Below this column width a band's label is turned on its side. */ const HORIZONTAL_BAND_LABEL_WIDTH = 78; +/** A position to a hundredth of a pixel: enough to draw with, and short in the markup. */ +function px(value: number): number { + return Math.round(value * 100) / 100; +} + /** Round axis values that cover the range, and the range they span. */ export function niceTicks(low: number, high: number, count = 4): { ticks: number[]; min: number; max: number } { let min = low; @@ -100,14 +107,36 @@ function tickDecimals(ticks: number[]): number { return [0, 1, 2, 3].find(exact) ?? 3; } +/** + * The ticks' labels: percentages in the relative view, values otherwise, with as few decimals as + * keep every label different from its neighbours. + */ +function axisLabels( + ticks: number[], + relative: boolean, + unit: OutputEntry["unit"], + currency: string | null, +): string[] { + if (relative) { + const decimals = tickDecimals(ticks); + return ticks.map((tick) => formatPercent(tick, decimals)); + } + let labels: string[] = []; + for (const decimals of [1, 2, 3, 4]) { + labels = ticks.map((tick) => formatAxisValue(tick, unit, currency, decimals)); + if (new Set(labels).size === labels.length) break; + } + return labels; +} + /** Why a build's column holds no point for this output; null when it holds one. */ export function columnBand(build: TimelineBuild, status: OutputEntry["values"][number]["status"]): ColumnBand | null { if (build.withdrawn) return "withdrawn"; if (status === "withheld") return "withheld"; if (status === "ok") return null; - if (build.state === "gap") return "gap"; + if (build.state === "gap") return "file refused"; if (build.state === "retrying") return "retrying"; - if (build.state === "failed") return "failed"; + if (build.state === "failed") return "out of attempts"; return build.state === "missing" ? "not measured" : "no value"; } @@ -145,7 +174,7 @@ export function chartLayout(options: { // What the chart places for a stored value: the value, or its % above or below the official figure. const placed = (value: number) => (relative && official !== null ? versusOfficial(value, official) : value); const step = (plot.right - plot.left) / Math.max(builds.length, 1); - const xs = builds.map((_, index) => plot.left + step * (index + 0.5)); + const xs = builds.map((_, index) => px(plot.left + step * (index + 0.5))); const values = builds.map((_, index) => entry.values[index]?.value ?? null); const known = values.filter((value): value is number => value !== null).map(placed); const empty = known.length === 0; @@ -156,10 +185,8 @@ export function chartLayout(options: { const yOf = (value: number) => range === null ? plot.bottom - : plot.bottom - ((value - range.min) / (range.max - range.min)) * (plot.bottom - plot.top); - const decimals = range ? tickDecimals(range.ticks) : 0; - const tickLabel = (tick: number) => - relative ? formatPercent(tick, decimals) : formatValue(tick, entry.unit, currency, 1); + : px(plot.bottom - ((value - range.min) / (range.max - range.min)) * (plot.bottom - plot.top)); + const tickLabels = range === null ? [] : axisLabels(range.ticks, relative, entry.unit, currency); const dates = dateLabels(builds, xs, step); const columns = builds.map((build, index): ChartColumn => { @@ -168,8 +195,8 @@ export function chartLayout(options: { index, buildId: build.buildId, x: xs[index], - left: xs[index] - step / 2, - width: step, + left: px(plot.left + step * index), + width: px(step), band: columnBand(build, entry.values[index]?.status ?? "unmeasured"), point: value === null || range === null ? null : { y: yOf(placed(value)), hollow: build.withdrawn }, current: build.current, @@ -195,13 +222,19 @@ export function chartLayout(options: { const point = columns[index].point; // A withdrawn build's value is drawn, hollow, and never labelled as the latest. if (value === null || point === null || point.hollow) continue; + // Above the point, unless the line comes down into it: then below, clear of the line. + const incoming = segments.find((segment) => segment.to === index); + const below = point.y + 20; + const comesDown = incoming !== undefined && incoming.y1 < incoming.y2; + // Beside a shaded column the label ends at its own column's edge, clear of that column's label. + const besideBand = columns[index + 1]?.band != null; latestLabel = { - x: columns[index].x, - y: point.y - 12, + x: besideBand ? px(columns[index].left + columns[index].width - 2) : columns[index].x, + y: comesDown && below <= plot.bottom - 4 ? below : point.y - 12, text: relative && official !== null ? formatPercent(versusOfficial(value, official), 2) : formatValue(value, entry.unit, currency), - anchor: index === columns.length - 1 ? "end" : "middle", + anchor: index === columns.length - 1 || besideBand ? "end" : "middle", }; } @@ -211,7 +244,7 @@ export function chartLayout(options: { plot, relative, blocked: options.scale === "relative" && official === null, - ticks: range ? range.ticks.map((tick) => ({ y: yOf(tick), label: tickLabel(tick) })) : [], + ticks: range ? range.ticks.map((tick, index) => ({ y: yOf(tick), label: tickLabels[index] })) : [], official: official === null || range === null ? null diff --git a/frontend/lib/microcosm/release-history-format.ts b/frontend/lib/microcosm/release-history-format.ts index c715fa99..54acf9cc 100644 --- a/frontend/lib/microcosm/release-history-format.ts +++ b/frontend/lib/microcosm/release-history-format.ts @@ -52,6 +52,21 @@ export function formatValue( return value < 0 ? `${MINUS}${text}` : text; } +/** + * A value on an axis, with the decimals the axis needs: unlike `formatValue`, a rate and a ratio + * take them too, so two ticks close together never read the same. + */ +export function formatAxisValue( + value: number, + unit: OutputUnit, + currency: string | null, + decimals: number, +): string { + if (unit === "currency" || unit === "count") return formatValue(value, unit, currency, decimals); + const abs = Math.abs(unit === "rate" ? value * 100 : value); + return `${value < 0 ? MINUS : ""}${abs.toFixed(decimals)}%`; +} + function signed(text: string, value: number): string { if (value < 0) return `${MINUS}${text}`; return value > 0 ? `+${text}` : text; diff --git a/frontend/lib/microcosm/release-history-moved.test.ts b/frontend/lib/microcosm/release-history-moved.test.ts index 5cc61cdd..a5043c9e 100644 --- a/frontend/lib/microcosm/release-history-moved.test.ts +++ b/frontend/lib/microcosm/release-history-moved.test.ts @@ -111,6 +111,28 @@ test("a build that republishes a file moves nothing, and is left out of every ty expect(typicalStep(entries[0], timeline.builds, 5)).toBeCloseTo(4); }); +test("a step of nothing is no move even from zero, and a step away from zero ranks first with no percentage", () => { + const timeline = smallTimeline({ + builds: [{}, {}, {}, {}, {}], + outputs: { + "baseline/nothing": ["currency", [0, 0, 0, 0, 0]], + "baseline/appears": ["currency", [0, 0, 0, 0, 12]], + "baseline/ordinary": ["currency", [100, 101, 102, 103, 104]], + }, + }); + const entries = outputEntries(timeline, PRESENTATION); + const summary = stepSummary(entries, timeline.builds, 4); + expect(summary).toMatchObject({ unchanged: 1, noStep: 0, withheld: 0 }); + expect(summary.moved.map((move) => move.entry.id)).toEqual(["baseline/appears", "baseline/ordinary"]); + expect(summary.moved[0]).toMatchObject({ signed: Number.POSITIVE_INFINITY, typical: 0, ratio: Number.POSITIVE_INFINITY }); + // An infinite step never enters a typical step. + const later = smallTimeline({ + builds: [{}, {}, {}, {}, {}, {}], + outputs: { "baseline/appears": ["currency", [0, 5, 5.05, 5.1, 5.151, 6]] }, + }); + expect(typicalStep(outputEntries(later, PRESENTATION)[0], later.builds, 5)).toBeCloseTo(1, 1); +}); + test("what moved speaks of the newest measured build on the axis", () => { const timeline = smallTimeline({ builds: [{}, {}, { withdrawn: true }, { unmeasured: true }], diff --git a/frontend/lib/microcosm/release-history-moved.ts b/frontend/lib/microcosm/release-history-moved.ts index f896c91c..1362c917 100644 --- a/frontend/lib/microcosm/release-history-moved.ts +++ b/frontend/lib/microcosm/release-history-moved.ts @@ -46,14 +46,22 @@ export interface StepSummary { rankedByTypical: boolean; } -/** An output's step to a build, in the measure its unit is told in; null when it has none. */ +/** + * An output's step to a build, in the measure its unit is told in; null when it has none. Money + * and counts are told in percent of the value before: a step of nothing is 0 whatever that value + * was, and a step away from a value of zero is infinite, for no percentage can tell it. + */ export function stepOf(entry: OutputEntry, buildIndex: number): { signed: number; measure: StepMove["measure"] } | null { const value = entry.values[buildIndex]; - if (!value || value.changeStatus !== "ok") return null; + if (!value || value.changeStatus !== "ok" || value.change === null) return null; if (stepsInPoints(entry.unit)) { return value.changePoints === null ? null : { signed: value.changePoints, measure: "points" }; } - return value.relativeChange === null ? null : { signed: value.relativeChange * 100, measure: "percent" }; + if (value.change === 0) return { signed: 0, measure: "percent" }; + return { + signed: value.relativeChange === null ? Math.sign(value.change) * Number.POSITIVE_INFINITY : value.relativeChange * 100, + measure: "percent", + }; } function median(sorted: number[]): number { @@ -74,7 +82,7 @@ export function typicalStep( for (let index = 0; index < buildIndex; index += 1) { if (builds[index].sameFileAs !== null) continue; const step = stepOf(entry, index); - if (step) sizes.push(Math.abs(step.signed)); + if (step && Number.isFinite(step.signed)) sizes.push(Math.abs(step.signed)); } return sizes.length < MIN_STEPS_FOR_TYPICAL ? null : median(sizes.sort((left, right) => left - right)); } diff --git a/frontend/lib/microcosm/release-history-page.test.ts b/frontend/lib/microcosm/release-history-page.test.ts new file mode 100644 index 00000000..29e4a80f --- /dev/null +++ b/frontend/lib/microcosm/release-history-page.test.ts @@ -0,0 +1,143 @@ +import { expect, test } from "bun:test"; + +import { + disclosureLine, + engineNotices, + engineOptions, + namedBuilds, + pageSelection, + selectedPanelId, + staleState, +} from "./release-history-page"; +import { readReleaseHistoryManifest } from "./release-history-read"; +import { releaseHistorySummary, type ReleaseHistorySummary } from "./release-history-summary"; +import { sharedSyntheticReleaseHistory } from "./test-support/release-history-synthetic-store"; +import { syntheticPanelView } from "./test-support/release-history-synthetic-view"; + +async function summaryOf(country: "uk" | "us") { + const { store, countries } = await sharedSyntheticReleaseHistory(); + return { + summary: releaseHistorySummary(country, await readReleaseHistoryManifest(store)), + panels: countries[country].panels, + }; +} + +test("the URL's panel is used when the country has it, and the default one otherwise", async () => { + const { summary, panels } = await summaryOf("uk"); + expect(selectedPanelId(summary, null)).toBe(panels.earlier); + expect(selectedPanelId(summary, panels.newer)).toBe(panels.newer); + // A panel of another country, as a link kept across a change of country would name. + expect(selectedPanelId(summary, (await summaryOf("us")).panels.earlier)).toBe(panels.earlier); + expect(selectedPanelId(summary, "not a panel")).toBe(panels.earlier); +}); + +test("the engine toggle lists each panel by its model and what it holds", async () => { + const uk = await summaryOf("uk"); + expect(engineOptions(uk.summary)).toEqual([ + { value: uk.panels.earlier, label: "policyengine-uk 1.0.0 · 7 of 10 files" }, + { value: uk.panels.newer, label: "policyengine-uk 1.1.0 · 7 of 10 files" }, + ]); + const us = await summaryOf("us"); + expect(engineOptions(us.summary).map((option) => option.label)).toEqual([ + "policyengine-us 1.0.0 · 5 of 5 files", + "policyengine-us 0.9.0 · 2 of 5 files · other definition", + ]); + // Two panels on one engine are told apart by their definition. + const twice: ReleaseHistorySummary = { + ...us.summary, + panels: us.summary.panels.map((panel) => ({ ...panel, engine: us.summary.panels[0].engine })), + }; + const labels = engineOptions(twice).map((option) => option.label); + expect(labels[0]).toMatch(/^policyengine-us 1\.0\.0 · 5 of 5 files · definition [0-9a-f]{7}$/); + expect(labels[1]).toMatch(/^policyengine-us 1\.0\.0 · 2 of 5 files · definition [0-9a-f]{7}$/); + expect(labels[0].slice(-7)).not.toBe(labels[1].slice(-7)); +}); + +test("the notices say which engine is on screen and where the other one is", async () => { + const uk = await summaryOf("uk"); + // The default view during an engine bump: the newer engine is filling. + expect(engineNotices(uk.summary, uk.panels.earlier)).toEqual([ + { + kind: "newer_engine_filling", + engine: "policyengine-uk 1.1.0", + pinnedAt: "2026-11-25T05:00:00Z", + coverage: "7 of 10 files", + panelId: uk.panels.newer, + }, + ]); + // The newer engine itself: still filling, with the way back. + expect(engineNotices(uk.summary, uk.panels.newer)).toEqual([ + { + kind: "viewing_filling_engine", + engine: "policyengine-uk 1.1.0", + coverage: "7 of 10 files", + defaultEngine: "policyengine-uk 1.0.0", + defaultPanelId: uk.panels.earlier, + }, + ]); + const us = await summaryOf("us"); + // A complete, pinned panel needs no notice. + expect(engineNotices(us.summary, us.panels.earlier)).toEqual([]); + expect(engineNotices(us.summary, us.panels.other).map((notice) => notice.kind)).toEqual([ + "viewing_other_engine", + "other_definition", + ]); + expect(engineNotices(us.summary, "not a panel")).toEqual([]); +}); + +test("the URL selects an output, a period and a step, and anything it cannot use is the default", async () => { + const view = await syntheticPanelView("uk"); + const first = pageSelection(view, { output: null, period: null, step: null }); + expect(first.period).toBe(2026); + expect(first.periods).toEqual([2026]); + expect(first.entry!.id).toBe("baseline/income_tax"); + expect(first.stepIndex).toBeNull(); + expect(first.periodEntries).toHaveLength(view.timeline.outputs.length); + + const chosen = pageSelection(view, { + output: "reform/vat_standard_rate_plus_1pp/budgetary_impact", + period: 2026, + step: view.timeline.builds[6].buildId, + }); + expect(chosen.entry!.fullLabel).toBe("VAT standard rate +1pp · Budgetary impact"); + expect(chosen.stepIndex).toBe(6); + + const stale = pageSelection(view, { output: "baseline/eitc", period: 1999, step: "another/build" }); + expect(stale).toMatchObject({ period: 2026, stepIndex: null }); + expect(stale.entry!.id).toBe("baseline/income_tax"); + + // What the panel cannot use leaves the URL; what it shows stays. + expect(staleState(stale, { output: "baseline/eitc", period: 1999, step: "another/build" })).toEqual({ + output: null, + period: null, + step: null, + }); + expect(staleState(chosen, { + output: "reform/vat_standard_rate_plus_1pp/budgetary_impact", + period: 2026, + step: view.timeline.builds[6].buildId, + })).toEqual({}); + expect(staleState(first, { output: null, period: null, step: null })).toEqual({}); + + // A timeline with no output selects nothing, and does not throw. + const empty = pageSelection({ ...view, timeline: { ...view.timeline, outputs: [] } }, { output: null, period: null, step: null }); + expect(empty).toMatchObject({ entry: null, periods: [], periodEntries: [] }); +}); + +test("the disclosure line states the country's policy, from its spec", () => { + expect(disclosureLine({ policy: "source_household_small_cells", minSourceHouseholds: 3 })).toBe( + "A value that rests on fewer than 3 survey households is withheld, with any partner cell that would give it back.", + ); + expect(disclosureLine({ policy: "source_household_small_cells", minSourceHouseholds: 10 })).toContain("fewer than 10 survey households"); + expect(disclosureLine({ policy: "none", minSourceHouseholds: 3 })).toBe("No value is withheld: this country's policy checks none."); + expect(disclosureLine({ policy: "keyed_noise", minSourceHouseholds: null })).toBe("Disclosure policy: keyed noise."); + expect(disclosureLine({ policy: null, minSourceHouseholds: null })).toBe("Disclosure policy not recorded."); +}); + +test("builds are named by date and short name", () => { + const builds = [ + { buildId: "line/a", publishedAt: "2026-11-17T02:04:00+00:00" }, + { buildId: "line/b", publishedAt: "2026-11-24T02:04:00+00:00" }, + ]; + expect(namedBuilds(builds, new Map([["line/a", "a"]]))).toBe("17 Nov (a), 24 Nov (line/b)"); +}); diff --git a/frontend/lib/microcosm/release-history-page.ts b/frontend/lib/microcosm/release-history-page.ts new file mode 100644 index 00000000..06e89944 --- /dev/null +++ b/frontend/lib/microcosm/release-history-page.ts @@ -0,0 +1,156 @@ +/** + * What the release history page shows for one URL (calibration-diagnostics#224): the engine + * options, the notices about the chosen engine, and the output, period and step the URL selects. + * Pure: the view renders what these return. A value of the URL the page cannot use falls back to + * its default here, so a stale link never fails. + */ +import { dateShort, engineLabel } from "./release-history-format"; +import { + outputEntries, + timelinePeriods, + type OutputEntry, +} from "./release-history-outputs"; +import type { + PanelPresentation, + ReleaseHistoryPanelSummary, + ReleaseHistoryPanelView, + ReleaseHistorySummary, +} from "./release-history-summary"; +import type { ReleaseHistoryUrlState } from "./release-history-url"; + +/** The panel a URL selects: the one it names when the country has it, else the default one. */ +export function selectedPanelId(summary: ReleaseHistorySummary, requested: string | null): string | null { + return summary.panels.some((panel) => panel.panelId === requested) ? requested : summary.defaultPanelId; +} + +function coverageText(panel: ReleaseHistoryPanelSummary): string { + return `${panel.coverage.measured} of ${panel.coverage.files} files`; +} + +/** + * One option per panel of the country, the default first: the engine's model and what the panel + * holds. Two panels on one engine are told apart by their definition. + */ +export function engineOptions(summary: ReleaseHistorySummary): { value: string; label: string }[] { + const engines = summary.panels.map((panel) => engineLabel(panel.engine.model)); + return summary.panels.map((panel, index) => { + const repeated = engines.filter((engine) => engine === engines[index]).length > 1; + const parts = [engines[index], coverageText(panel)]; + if (repeated) parts.push(`definition ${(panel.specSha256 ?? "unknown").slice(0, 7)}`); + else if (!panel.sameDefinitionAsDefault) parts.push("other definition"); + return { value: panel.panelId, label: parts.join(" · ") }; + }); +} + +/** + * What the page says about the engine on screen. + * + * - `newer_engine_filling`: the default (served) panel is shown while a newer engine's panel, + * the pinned one, fills. The page moves to it once it is complete. + * - `viewing_filling_engine`: the pinned panel is shown before it is complete. + * - `viewing_other_engine`: another engine's panel is shown, one measured on request. + * - `other_definition`: the panel was measured under another spec or producer version than the + * default one, so its outputs may differ. + */ +export type EngineNotice = + | { kind: "newer_engine_filling"; engine: string; pinnedAt: string | null; coverage: string; panelId: string } + | { kind: "viewing_filling_engine"; engine: string; coverage: string; defaultEngine: string; defaultPanelId: string } + | { kind: "viewing_other_engine"; engine: string; defaultEngine: string; defaultPanelId: string } + | { kind: "other_definition"; engine: string }; + +export function engineNotices(summary: ReleaseHistorySummary, panelId: string | null): EngineNotice[] { + const shown = summary.panels.find((panel) => panel.panelId === panelId); + const chosen = summary.panels.find((panel) => panel.panelId === summary.defaultPanelId); + if (!shown || !chosen) return []; + const notices: EngineNotice[] = []; + const pinned = summary.panels.find((panel) => panel.pinned); + if (shown.panelId === chosen.panelId) { + if (pinned && pinned.panelId !== chosen.panelId) { + notices.push({ + kind: "newer_engine_filling", + engine: engineLabel(pinned.engine.model), + pinnedAt: pinned.pinnedAt, + coverage: coverageText(pinned), + panelId: pinned.panelId, + }); + } + return notices; + } + const back = { defaultEngine: engineLabel(chosen.engine.model), defaultPanelId: chosen.panelId }; + if (shown.pinned) { + notices.push({ + kind: "viewing_filling_engine", + engine: engineLabel(shown.engine.model), + coverage: coverageText(shown), + ...back, + }); + } else { + notices.push({ kind: "viewing_other_engine", engine: engineLabel(shown.engine.model), ...back }); + } + if (!shown.sameDefinitionAsDefault) { + notices.push({ kind: "other_definition", engine: engineLabel(shown.engine.model) }); + } + return notices; +} + +/** What the URL selects on a loaded panel. */ +export interface PageSelection { + /** Every output of the panel, in the page's order, and those of the selected period. */ + entries: OutputEntry[]; + periods: number[]; + period: number; + periodEntries: OutputEntry[]; + /** The selected output; null only for a timeline with no output. */ + entry: OutputEntry | null; + /** The build whose step card is open, by its place in the timeline's builds. */ + stepIndex: number | null; +} + +export function pageSelection( + view: ReleaseHistoryPanelView, + state: Pick, +): PageSelection { + const entries = outputEntries(view.timeline, view.presentation); + const periods = timelinePeriods(entries); + const period = state.period !== null && periods.includes(state.period) ? state.period : periods[0] ?? 0; + const periodEntries = entries.filter((entry) => entry.period === period); + const entry = periodEntries.find((candidate) => candidate.id === state.output) ?? periodEntries[0] ?? null; + const stepIndex = view.timeline.builds.findIndex((build) => build.buildId === state.step); + return { entries, periods, period, periodEntries, entry, stepIndex: stepIndex === -1 ? null : stepIndex }; +} + +/** + * The parts of the URL's state the loaded panel cannot use, set back to their defaults: an + * output or a period it does not hold, a step at a build it does not list. Empty when the URL + * says only what the page shows, so a link copied from it opens the same view. + */ +export function staleState( + selection: PageSelection, + state: Pick, +): Partial { + const stale: Partial = {}; + if (state.output !== null && selection.entry?.id !== state.output) stale.output = null; + if (state.period !== null && selection.period !== state.period) stale.period = null; + if (state.step !== null && selection.stepIndex === null) stale.step = null; + return stale; +} + +/** One line on the country's disclosure policy, from the panel's spec. */ +export function disclosureLine(disclosure: PanelPresentation["disclosure"]): string { + if (disclosure.policy === "source_household_small_cells") { + const floor = disclosure.minSourceHouseholds ?? 3; + return `A value that rests on fewer than ${floor} survey households is withheld, with any partner cell that would give it back.`; + } + if (disclosure.policy === "none") return "No value is withheld: this country's policy checks none."; + return disclosure.policy ? `Disclosure policy: ${disclosure.policy.replace(/_/g, " ")}.` : "Disclosure policy not recorded."; +} + +/** "19 Oct (name)" for each build, for a sentence that names builds. */ +export function namedBuilds( + builds: ReadonlyArray<{ buildId: string; publishedAt: string }>, + shortNames: ReadonlyMap, +): string { + return builds + .map((build) => `${dateShort(build.publishedAt)} (${shortNames.get(build.buildId) ?? build.buildId})`) + .join(", "); +} diff --git a/frontend/lib/microcosm/test-support/release-history-synthetic-store.ts b/frontend/lib/microcosm/test-support/release-history-synthetic-store.ts index 53a5b2df..571b7d3d 100644 --- a/frontend/lib/microcosm/test-support/release-history-synthetic-store.ts +++ b/frontend/lib/microcosm/test-support/release-history-synthetic-store.ts @@ -77,7 +77,7 @@ interface SyntheticBuild { current?: boolean; /** The release repository lists it with no file to measure. */ refused?: boolean; - /** Its file carries no survey household ids: a stored refusal, a gap on every engine. */ + /** Its file carries no survey household ids: a stored refusal, the store's "gap". */ gap?: boolean; } From 4636cc1001e77386f770f7757988657dc4fbe3e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:13:32 +0000 Subject: [PATCH 5/6] Read the release history from Blob with the deployment's own credentials, passing none The page's routes passed `BLOB_READ_WRITE_TOKEN` to the Blob client when the environment held one. The dashboard's other Blob reads pass no credential (frontend/HOSTED_RUNTIME.md), so `@vercel/blob` uses the deployment's Vercel OIDC token with `BLOB_STORE_ID` when both are present and the token otherwise. An explicit token skipped that choice. - `releaseHistoryReadStore` now opens the Blob store with no token, whatever the environment holds, and gives the routes a store they cannot write through. The page needs no setting of its own for Blob. - A named local folder (`RELEASE_HISTORY_LOCAL_DIR`) is still read in place of Blob, which is then never opened. - `docs/release-history.md` and `frontend/HOSTED_RUNTIME.md` say so. Co-Authored-By: Claude Fable 5.2 --- docs/release-history.md | 6 ++- frontend/HOSTED_RUNTIME.md | 4 +- .../microcosm/release-history-source.test.ts | 40 ++++++++++++++++++- .../lib/microcosm/release-history-source.ts | 27 +++++++++++-- 4 files changed, 70 insertions(+), 7 deletions(-) diff --git a/docs/release-history.md b/docs/release-history.md index b05878ef..b3e4d60c 100644 --- a/docs/release-history.md +++ b/docs/release-history.md @@ -295,7 +295,11 @@ on a country code. A country the dashboard does not serve gets the not-configured state, and one with no measured file an empty state. Three routes read the store on the server, so the browser never receives a -Blob URL or a token. Each requires `?country=`. +Blob URL or a token. Each requires `?country=`. They read Blob as the +dashboard's other Blob reads do ([hosted runtime](../frontend/HOSTED_RUNTIME.md)): +with no credential passed, so `@vercel/blob` uses the deployment's Vercel OIDC +token with `BLOB_STORE_ID` when both are present, and `BLOB_READ_WRITE_TOKEN` +otherwise. The page has no setting of its own for Blob, and it never writes. - `GET /api/microcosm/release-history`: the country's panels from the manifest, one per reference engine that holds a measured file, with engine, diff --git a/frontend/HOSTED_RUNTIME.md b/frontend/HOSTED_RUNTIME.md index 4bf83d35..71824cff 100644 --- a/frontend/HOSTED_RUNTIME.md +++ b/frontend/HOSTED_RUNTIME.md @@ -22,7 +22,9 @@ The dashboard server also reads: deployment's Vercel OIDC token with `BLOB_STORE_ID` when both are present, and `BLOB_READ_WRITE_TOKEN` otherwise. The comparison route (`frontend/app/api/microcosm/comparison-tree/route.ts`) writes a missing comparison - artifact with `BLOB_READ_WRITE_TOKEN`. + artifact with `BLOB_READ_WRITE_TOKEN`. The release history page's routes read the + same store the same way, with no credential passed, and never write + (see [release history](../docs/release-history.md#the-page)). The Modal runtime uses Python 3.12 and the hashed `backend/requirements.lock`. Regenerate that lock from the repository root with `uv pip compile diff --git a/frontend/lib/microcosm/release-history-source.test.ts b/frontend/lib/microcosm/release-history-source.test.ts index c246b67d..d616a9bc 100644 --- a/frontend/lib/microcosm/release-history-source.test.ts +++ b/frontend/lib/microcosm/release-history-source.test.ts @@ -7,8 +7,15 @@ import { directoryStore, RELEASE_HISTORY_LOCAL_DIR_ENV, releaseHistoryLocalDirectory, + releaseHistoryReadStore, } from "./release-history-source"; -import { readJson, RELEASE_HISTORY_MANIFEST_PATH } from "./release-history-store"; +import { + encodeDocument, + memoryStore, + readJson, + RELEASE_HISTORY_MANIFEST_PATH, + type ReleaseHistoryStore, +} from "./release-history-store"; async function folder(): Promise { const root = await mkdtemp(join(tmpdir(), "release-history-source-")); @@ -50,3 +57,34 @@ test("the folder is read only when the environment names it", () => { expect(releaseHistoryLocalDirectory({ [RELEASE_HISTORY_LOCAL_DIR_ENV]: " " })).toBeNull(); expect(releaseHistoryLocalDirectory({ [RELEASE_HISTORY_LOCAL_DIR_ENV]: "/tmp/store" })).toBe("/tmp/store"); }); + +test("Blob is read with the deployment's own credentials: no token is passed, whatever the environment holds", async () => { + const blob = memoryStore(); + await blob.write(RELEASE_HISTORY_MANIFEST_PATH, encodeDocument({ formatVersion: 1 }), "create", false); + const calls: unknown[][] = []; + const blobStore = (...credentials: unknown[]): ReleaseHistoryStore => { + calls.push(credentials); + return blob; + }; + // A token in the environment is the Blob client's to pick, after OIDC with BLOB_STORE_ID. + for (const environment of [{}, { BLOB_READ_WRITE_TOKEN: "vercel_blob_rw_secret", BLOB_STORE_ID: "store_1" }]) { + const store = releaseHistoryReadStore(environment, blobStore); + expect(await readJson<{ formatVersion: number }>(store, RELEASE_HISTORY_MANIFEST_PATH)).toEqual({ formatVersion: 1 }); + expect(await store.list("release-history/")).toEqual([RELEASE_HISTORY_MANIFEST_PATH]); + // The page only reads: nothing is written through the store it is given. + await expect(store.write(RELEASE_HISTORY_MANIFEST_PATH, new Uint8Array(), "replace", false)).rejects.toThrow("never writes"); + } + expect(calls).toEqual([[], []]); + expect(await readJson<{ formatVersion: number }>(blob, RELEASE_HISTORY_MANIFEST_PATH)).toEqual({ formatVersion: 1 }); +}); + +test("a named local folder is read in place of Blob, which is then never opened", async () => { + const root = await folder(); + let opened = 0; + const store = releaseHistoryReadStore({ [RELEASE_HISTORY_LOCAL_DIR_ENV]: root, BLOB_READ_WRITE_TOKEN: "unused" }, () => { + opened += 1; + return memoryStore(); + }); + expect(await readJson<{ formatVersion: number }>(store, RELEASE_HISTORY_MANIFEST_PATH)).toEqual({ formatVersion: 1 }); + expect(opened).toBe(0); +}); diff --git a/frontend/lib/microcosm/release-history-source.ts b/frontend/lib/microcosm/release-history-source.ts index d30243d9..0f05f1ec 100644 --- a/frontend/lib/microcosm/release-history-source.ts +++ b/frontend/lib/microcosm/release-history-source.ts @@ -2,6 +2,11 @@ * Where the release history routes read from (calibration-diagnostics#224): the private Vercel * Blob store, or a local folder in the same layout. * + * Blob is read as the dashboard's other Blob reads are (frontend/HOSTED_RUNTIME.md): with no + * credential passed, so `@vercel/blob` uses the deployment's Vercel OIDC token with + * `BLOB_STORE_ID` when both are present, and `BLOB_READ_WRITE_TOKEN` otherwise. The page needs no + * setting of its own, and it never writes. + * * The folder is for development and for looking at a pulled panel: `scripts/release-history.ts * pull --out ` and the Python producer both write this layout. It is read only when * RELEASE_HISTORY_LOCAL_DIR names it, so a hosted deployment never reads its own filesystem. @@ -80,12 +85,26 @@ export function releaseHistoryLocalDirectory( return named ? path.resolve(named) : null; } -/** The store the page's routes read: the named local folder, otherwise private Blob. */ +/** A store's reads, with no way to write through it. */ +function readOnly(store: ReleaseHistoryStore): ReleaseHistoryStore { + return { + read: (storePath) => store.read(storePath), + list: (prefix) => store.list(prefix), + async write(storePath) { + throw new Error(`The dashboard never writes the release history: ${storePath} was not written.`); + }, + }; +} + +/** + * The store the page's routes read: the named local folder, otherwise private Blob with the + * deployment's own credentials. `blobStore` is called with no token, whatever the environment + * holds, so the Blob client picks the credential as it does for every other read of the dashboard. + */ export function releaseHistoryReadStore( environment: Record = process.env, + blobStore: () => ReleaseHistoryStore = vercelBlobStore, ): ReleaseHistoryStore { const directory = releaseHistoryLocalDirectory(environment); - return directory - ? directoryStore(directory) - : vercelBlobStore(environment.BLOB_READ_WRITE_TOKEN || undefined); + return directory ? directoryStore(directory) : readOnly(blobStore()); } From b66cb7e991824e48fd371437fb1a41362253bb0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:35:27 +0000 Subject: [PATCH 6/6] List the release history page in the sidebar, under Releases The entry goes with the `calibration` capability, which every country the dashboard serves holds: the country registry has no capability for the release history itself, and adding one is a change to @policyengine/calibration-tree in PolicyEngine/microcosm-collector. A country with nothing measured gets the page's empty state. No country code is branched on. The sidebar tests, the third-country conformance test and the docs follow. Co-Authored-By: Claude Fable 5.2 --- docs/release-history.md | 13 +++++--- .../app/microcosm/release-history/page.tsx | 6 ++-- frontend/components/layout/nav-items.test.ts | 32 ++++++++++++++++++- frontend/components/layout/nav-items.ts | 5 +++ .../third-country-conformance.test.ts | 2 +- 5 files changed, 48 insertions(+), 10 deletions(-) diff --git a/docs/release-history.md b/docs/release-history.md index b3e4d60c..61e43156 100644 --- a/docs/release-history.md +++ b/docs/release-history.md @@ -288,11 +288,14 @@ floors) belong to the page. ## The page `/microcosm/release-history?country=` draws one panel's `timeline.json`. -It is reachable by URL and has no navigation entry yet: that needs a -capability in `@policyengine/calibration-tree`'s `countries.ts`, a change in -PolicyEngine/microcosm-collector. Nothing in the page or its routes branches -on a country code. A country the dashboard does not serve gets the -not-configured state, and one with no measured file an empty state. +The sidebar lists it under Releases for every country with the `calibration` +capability, which is every country the dashboard serves. The country registry +has no capability for the release history itself: adding one is a change to +`@policyengine/calibration-tree`'s `countries.ts` in +PolicyEngine/microcosm-collector. Nothing in the page, its routes or its +sidebar entry branches on a country code. A country the dashboard does not +serve gets the not-configured state, and one with no measured file an empty +state. Three routes read the store on the server, so the browser never receives a Blob URL or a token. Each requires `?country=`. They read Blob as the diff --git a/frontend/app/microcosm/release-history/page.tsx b/frontend/app/microcosm/release-history/page.tsx index 2c890b63..15c8b255 100644 --- a/frontend/app/microcosm/release-history/page.tsx +++ b/frontend/app/microcosm/release-history/page.tsx @@ -7,9 +7,9 @@ import { LoadingBlock } from "@/components/shared/LoadingBlock"; export const metadata: Metadata = { title: "Release history" }; -// Reachable by URL (?country=); the navigation gains an entry once a country registers the -// capability in @policyengine/calibration-tree. A country the dashboard does not serve gets the -// shell's not-configured state, and one with no measured file an empty state. +// Listed in the sidebar under Releases for every country with the `calibration` capability +// (components/layout/nav-items.ts). A country the dashboard does not serve gets the shell's +// not-configured state, and one with no measured file an empty state. export default function ReleaseHistoryPage() { return ( diff --git a/frontend/components/layout/nav-items.test.ts b/frontend/components/layout/nav-items.test.ts index e1aef082..69739424 100644 --- a/frontend/components/layout/nav-items.test.ts +++ b/frontend/components/layout/nav-items.test.ts @@ -84,6 +84,9 @@ test("every navigation item is gated by a capability, never by a country code", const items = NAV_GROUPS.flatMap((group) => group.items); expect(items.every((item) => item.capability != null)).toBe(true); expect(items.find((item) => item.href === "/microcosm/staging")?.capability).toBe("staging"); + expect(items.find((item) => item.href === "/microcosm/release-history")?.capability).toBe( + "calibration", + ); expect(items.find((item) => item.href === "/microcosm/model-coverage")?.capability).toBe( "model_coverage", ); @@ -101,11 +104,13 @@ test("Belgium navigation keeps country-ready pages and hides pages it lacks capa expect(items.map((item) => item.href)).toEqual([ "/microcosm", "/microcosm/datasets", + "/microcosm/release-history", ]); expect(items.every((item) => hasCapability("be", item.capability!))).toBe(true); expect(items.map((item) => navItemHref(item, "be"))).toEqual([ "/microcosm?country=be", "/microcosm/datasets?country=be", + "/microcosm/release-history?country=be", ]); }); @@ -117,8 +122,32 @@ test("US navigation lists every page", () => { test("artifact-narrowed capabilities hide pages the release does not serve", () => { const groups = navGroupsForCountry("us", ["calibration", "targets"]); - expect(groups.map((group) => group.label)).toEqual(["Dataset accuracy"]); + expect(groups.map((group) => group.label)).toEqual(["Dataset accuracy", "Releases"]); expect(groups[0].items.map((item) => item.href)).toEqual(["/microcosm"]); + // Staging candidates goes with `staging`; the release history stays with `calibration`. + expect(groups[1].items.map((item) => item.href)).toEqual(["/microcosm/release-history"]); + expect(navGroupsForCountry("us", ["targets"])).toEqual([]); +}); + +test("lists the release history under Releases for every selectable country", () => { + for (const country of selectableCountries()) { + const releases = navGroupsForCountry(country).find((group) => group.label === "Releases"); + const item = releases?.items.find((candidate) => candidate.label === "Release history"); + expect(item).toEqual({ + href: "/microcosm/release-history", + label: "Release history", + capability: "calibration", + }); + expect(navItemHref(item!, country)).toBe(`/microcosm/release-history?country=${country}`); + expect(navLinkAttributes(item!)).toEqual({}); + } +}); + +test("the release history path activates its own entry and no other", () => { + const items = NAV_GROUPS.flatMap((group) => group.items); + expect( + items.filter((item) => isActive("/microcosm/release-history", item)).map((item) => item.label), + ).toEqual(["Release history"]); }); test("shows Cross-dataset navigation for every selectable country", () => { @@ -136,6 +165,7 @@ test("names the page the reader is on for the phone-width nav bar", () => { expect(activeNavItem("/microcosm/staging", uk)?.label).toBe("Staging candidates"); expect(activeNavItem("/microcosm", uk)?.label).toBe("Calibration fit"); expect(activeNavItem("/microcosm/datasets", uk)?.label).toBe("Cross-dataset"); + expect(activeNavItem("/microcosm/release-history", uk)?.label).toBe("Release history"); // Drill-downs no item claims, and pages the country does not serve, have no label. expect(activeNavItem("/microcosm/targets", uk)).toBeUndefined(); expect(activeNavItem("/microcosm/staging", navGroupsForCountry("be"))).toBeUndefined(); diff --git a/frontend/components/layout/nav-items.ts b/frontend/components/layout/nav-items.ts index 67117a34..4201a39d 100644 --- a/frontend/components/layout/nav-items.ts +++ b/frontend/components/layout/nav-items.ts @@ -45,6 +45,11 @@ export const NAV_GROUPS: { label: string; items: NavItem[] }[] = [ label: "Releases", items: [ { href: "/microcosm/staging", label: "Staging candidates", capability: "staging" }, + // The country registry has no capability for the release history itself + // yet, so the entry goes with `calibration`: every country that publishes + // a release holds it, and the page says so when a country has nothing + // measured (calibration-diagnostics#224). + { href: "/microcosm/release-history", label: "Release history", capability: "calibration" }, ], }, { diff --git a/frontend/lib/microcosm/third-country-conformance.test.ts b/frontend/lib/microcosm/third-country-conformance.test.ts index 701ef724..3cc29cf5 100644 --- a/frontend/lib/microcosm/third-country-conformance.test.ts +++ b/frontend/lib/microcosm/third-country-conformance.test.ts @@ -209,7 +209,7 @@ describe("synthetic third-country conformance", () => { navGroupsForCountry(COUNTRY) .flatMap((group) => group.items) .map((item) => item.href), - ).toEqual(["/microcosm"]); + ).toEqual(["/microcosm", "/microcosm/release-history"]); }); test( "zz overview data can carry artifact-provided intro copy: the summary omits a typed presentation contract",