Skip to content
118 changes: 114 additions & 4 deletions docs/release-history.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -263,8 +268,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
Expand All @@ -275,6 +285,106 @@ 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=<code>` draws one panel's `timeline.json`.
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
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,
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=<id>`: 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=<id>`: 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 <folder>` 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
Expand Down
4 changes: 3 additions & 1 deletion frontend/HOSTED_RUNTIME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions frontend/app/api/microcosm/country-not-configured.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ const COUNTRY_ROUTES: Record<string, () => Promise<RouteModule>> = {
"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"),
Expand All @@ -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",
Expand Down
42 changes: 42 additions & 0 deletions frontend/app/api/microcosm/release-history/export/route.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
43 changes: 43 additions & 0 deletions frontend/app/api/microcosm/release-history/export/route.ts
Original file line number Diff line number Diff line change
@@ -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();
96 changes: 96 additions & 0 deletions frontend/app/api/microcosm/release-history/route.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});
36 changes: 36 additions & 0 deletions frontend/app/api/microcosm/release-history/route.ts
Original file line number Diff line number Diff line change
@@ -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();
Loading
Loading