diff --git a/docs/calibration-tree-artifacts.md b/docs/calibration-tree-artifacts.md index 9eb70e01..87476586 100644 --- a/docs/calibration-tree-artifacts.md +++ b/docs/calibration-tree-artifacts.md @@ -140,12 +140,15 @@ removed targets read only the source side that exists. release repository update -> POST /api/hf-webhook -> one GitHub workflow_dispatch per webhook delivery - -> enumerate the union of release directories and immutable repository tags + -> read releases.json at the head of main; with it, enumerate the builds it + lists; without it, the union of release directories and immutable + repository tags -> resolve every eligible release to an exact Hugging Face commit -> audit the existing Blob build for each release -> skip complete builds without downloading their diagnostics -> build and upload only missing builds or missing files - -> update latestReleaseBuildArtifactId from the country's upstream pointer + -> update latestReleaseBuildArtifactId from releases.json's current build + of its default release, or, without releases.json, the upstream pointer ``` A release directory or tag without calibration diagnostics is reported as @@ -195,6 +198,90 @@ for inspection only, such as the UK dense local-area line, has no copy on - The release picker adds every published cut beside the folders on `main` and hides a line folder unless the dashboard's latest release still points at it. +These readers apply to a dataset repository with no `releases.json` (next +section). The UK repository stays this way until Microcosm's switch commit +writes `releases.json` and deletes its pointer files; the dashboard then reads +it from `releases.json` with no change of its own. + +#### Build folders and `releases.json` + +A dataset repository with a root `releases.json` publishes every build in its +own folder, never changed after publishing, and that record names every build +and each release's current build: + +```text +releases.json +releases///release_manifest.json +releases///calibration_diagnostics.json +releases///... +``` + +`releases.json` follows microcosm-emitter's +`microcosm_emitter_interface.releases` (microcosm-emitter#24), whose release +writer is the only program that changes it. `release-record.ts` reads it with +the same rules: at most 4 MiB, exact keys, `schema_version` 1, safe release +and build names, each `current` listed and not withdrawn, and `default` +listed. (JavaScript reads a `schema_version` of `1.0` as 1, which the writer +refuses; the writer itself writes `1`.) For such a repository the dashboard +reads `releases.json` and nothing else: no tags, no `latest*.json` pointer +files and no listing of `releases/`. + +Every reader finds the layout the same way, whatever the country: it asks +Hugging Face for `releases.json` (the tree publisher at the commit it +publishes, the release picker and the Staging page at the configured +revision). No country registration names the layout. + +- Only Hugging Face's 404 for the file means the repository has no + `releases.json`, and then the tags and pointer files are read. A 404 whose + error code (`X-Error-Code`) is `RepoNotFound` or `RevisionNotFound`, any + other failure, and a record the writer's rules refuse are errors: the + release picker answers 502 for that country, reconciliation publishes + nothing and leaves the latest release as it was, and a local-area Staging + candidate has no comparison baseline. No reader falls back to tags or + pointer files. + +- A build's release id is its folder, `/`. Its manifest entry + records no separate `releaseDirectory`, and readers fetch + `releases///` at the entry's commit. +- Reconciliation reads `releases.json` at the head of `main` and publishes + every listed build whose folder holds `calibration_diagnostics.json` and + whose `release_manifest.json` names the same `release` and `build` in its + top-level fields. The build is pinned to the newest commit behind its + folder's files (the commit that wrote the folder) and dated by its + `published_at`, so a build copied into its folder later keeps its + original date. A build whose folder or release manifest cannot be read is + reported as `failed`, and the other builds are still reconciled. + A build the manifest already holds is not looked up again. +- The latest release is the current build of the record's default release. + While the record names none, or that build cannot be published, + reconciliation publishes the other listed builds and fails without moving + the latest release, naming the reason. +- `--latest` and `--release /` publish one listed build. The + promotion check that follows compares the build with the record's current + build by name, and reads that build's folder only when they match; if the + folder cannot be read then, the build stays published and the next + reconciliation moves the latest release. +- Entries published from tags or release folders stay in the manifest and + stay readable by their ids; reconciliation no longer repairs them, and the + picker no longer lists them. The one exception is the dashboard's latest + release: until reconciliation makes the record's current build the latest + release, the latest release is still such an entry, and the picker keeps + it listed as the default dataset. The deployment's pre-promotion check + requires the latest release to be listed. +- The release picker lists every build `releases.json` names, dated by + `published_at`, with its release's role (the default release is the + default dataset; Microcosm's roles are `national` and `local_area`) and its + `withdrawn` flag. A build is selectable for comparison once its tree is + published. A withdrawn build stays listed and selectable, labelled + "Withdrawn". +- The Staging page compares a local-area candidate with the newest published + build of a `local_area` release that is not withdrawn. +- Every release id the dashboard accepts may be a build folder, + `/`, including the Staging target-change view's; the + "View on Hugging Face" link opens the folder at the build's pinned commit, + since a build folder has no tag. +- The timestamp migration leaves build-folder entries alone. + ### Finalized staging builds ```text diff --git a/docs/spec-driven-countries.md b/docs/spec-driven-countries.md index 5917db7e..6d00989c 100644 --- a/docs/spec-driven-countries.md +++ b/docs/spec-driven-countries.md @@ -8,7 +8,12 @@ Face commit and reads `releases//calibration_diagnostics.json`: the release's own folder, or its line's folder for a Microcosm cut tag (see [the release lines note](calibration-tree-artifacts.md#microcosm-release-lines)). The country's current release comes from `latest.json` unless the registration -names a per-line pointer in `pointer_path` (the UK: `latest-national.json`). +names another pointer file in `pointer_path`. A dataset repository with a root +`releases.json` reads neither: each build is in `releases///`, +and `releases.json` alone names the builds and the current one (see +[the build folders note](calibration-tree-artifacts.md#build-folders-and-releasesjson)). +The readers look for that file in every repository; the registration does not +name the layout. `build_manifest.json`, `release_manifest.json`, and `demographics.json` are optional enrichments. The diagnostics artifact owns fit values and target metadata; the build manifest owns diff --git a/frontend/app/api/microcosm/releases/route.test.ts b/frontend/app/api/microcosm/releases/route.test.ts index 7d80a54d..4e25aa79 100644 --- a/frontend/app/api/microcosm/releases/route.test.ts +++ b/frontend/app/api/microcosm/releases/route.test.ts @@ -1,7 +1,12 @@ import { expect, test } from "bun:test"; -import { emptyCalibrationTreeManifest } from "@policyengine/calibration-tree/calibration-tree-manifest"; +import { + emptyCalibrationTreeManifest, + withCalibrationTreeManifestEntry, + type CalibrationTreeManifest, +} from "@policyengine/calibration-tree/calibration-tree-manifest"; import type { ReleaseEntry } from "@policyengine/calibration-tree/latest-artifact"; +import { parseReleasesRecord } from "@policyengine/calibration-tree/release-record"; import { createMicrocosmReleasesHandler } from "./route"; // Synthetic Microcosm line (microcosm#823): a folder on main and its cuts. @@ -27,8 +32,10 @@ const FOLDERS = [ release(LINE, LINE), ]; +// A repository without releases.json: its folders on main and its tags. function handler(options: { manifestFails?: boolean } = {}) { return createMicrocosmReleasesHandler({ + loadReleasesRecord: async () => null, loadReleases: async () => FOLDERS, loadPointerReleaseId: async () => ({ release_id: CUT, @@ -78,6 +85,136 @@ test("without the dashboard manifest the inventory keeps the folder listing", as ); }); +// A repository with releases.json (microcosm-emitter#24): it lists every +// build, named by its folder. +const CURRENT_BUILD = `${LINE}/uk-frs-calibration-attempt-20261019T083323Z-6cba5d71`; +const UNPUBLISHED_BUILD = `${LINE}/uk-frs-calibration-attempt-20261020T000000Z-11111111`; +const DENSE_BUILD = "microcosm-uk-2024-25-dense/uk-local-candidate-f100-s42-20261019T000432Z-ee5c2dbe"; +const RECORD = parseReleasesRecord({ + schema_version: 1, + default: LINE, + releases: { + [LINE]: { + role: "national", + current: CURRENT_BUILD.split("/")[1], + builds: { + [CURRENT_BUILD.split("/")[1]]: { published_at: "2026-10-19T08:33:23+00:00", withdrawn: false }, + [UNPUBLISHED_BUILD.split("/")[1]]: { published_at: "2026-10-20T00:00:00+00:00", withdrawn: false }, + }, + }, + "microcosm-uk-2024-25-dense": { + role: "local_area", + current: DENSE_BUILD.split("/")[1], + builds: { + [DENSE_BUILD.split("/")[1]]: { published_at: "2026-10-19T00:04:32+00:00", withdrawn: false }, + }, + }, + }, +}); + +// The dashboard manifest holds the trees of the current and dense builds. +function publishedTrees(): CalibrationTreeManifest { + return [CURRENT_BUILD, DENSE_BUILD].reduce( + (manifest, releaseId, index) => withCalibrationTreeManifestEntry(manifest, "uk", { + buildArtifactId: String(index + 1).repeat(64), + kind: "release", + sourceId: releaseId, + label: releaseId, + releaseId, + stagingRunId: null, + hfRepo: "policyengine/populace-uk-private", + hfCommitSha: String(index + 1).repeat(40), + treeSchemaVersion: 6, + indexSha256: "e".repeat(64), + indexBytes: 10, + createdAt: null, + updatedAt: null, + }, releaseId === CURRENT_BUILD), + emptyCalibrationTreeManifest(), + ); +} + +function buildFolderHandler(options: { manifestFails?: boolean } = {}) { + const calls: string[] = []; + const refuse = (name: string) => async () => { + calls.push(name); + throw new Error(`${name} is not read for a repository with releases.json`); + }; + return { + calls, + handle: createMicrocosmReleasesHandler({ + loadReleasesRecord: async () => { + calls.push("loadReleasesRecord"); + return RECORD; + }, + loadReleases: refuse("loadReleases"), + loadPublishedCutReleases: refuse("loadPublishedCutReleases"), + loadPointerReleaseId: async () => ({ + release_id: CURRENT_BUILD, + updated_at: "2026-10-19T08:33:23.000Z", + }), + readManifest: async () => { + if (options.manifestFails) throw new Error("Blob unavailable"); + return { manifest: publishedTrees(), etag: '"manifest"' }; + }, + }), + }; +} + +test("for a repository with releases.json, the inventory is the builds it lists", async () => { + const { calls, handle } = buildFolderHandler(); + const response = await handle( + new Request("https://dashboard.example/api/microcosm/releases?country=uk"), + ); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body.default_release_id).toBe(CURRENT_BUILD); + expect(body.latest_release_id).toBe(CURRENT_BUILD); + expect(body.all_releases.map((entry: ReleaseEntry) => entry.release_id)).toEqual([ + UNPUBLISHED_BUILD, + CURRENT_BUILD, + DENSE_BUILD, + ]); + // Only builds with a published calibration tree can be compared. + expect(body.releases.map((entry: ReleaseEntry) => entry.release_id)).toEqual([ + CURRENT_BUILD, + DENSE_BUILD, + ]); + expect(body.releases[1]).toMatchObject({ dataset_role: "local_area", is_local_area: true }); + // No release-folder listing, tags or pointer files. + expect(calls).toEqual(["loadReleasesRecord"]); +}); + +test("for a repository with releases.json, the inventory fails without the dashboard manifest", async () => { + const { handle } = buildFolderHandler({ manifestFails: true }); + const response = await handle( + new Request("https://dashboard.example/api/microcosm/releases?country=uk"), + ); + expect(response.status).toBe(502); +}); + +test("a releases.json that cannot be read or is refused fails the inventory, with no fallback to tags", async () => { + const calls: string[] = []; + const response = await createMicrocosmReleasesHandler({ + loadReleasesRecord: async () => { + throw new Error("releases.json is not a readable JSON document."); + }, + loadReleases: async () => { + calls.push("loadReleases"); + return FOLDERS; + }, + loadPublishedCutReleases: async () => { + calls.push("loadPublishedCutReleases"); + return []; + }, + loadPointerReleaseId: async () => ({ release_id: CUT, updated_at: null }), + readManifest: async () => ({ manifest: emptyCalibrationTreeManifest(), etag: '"manifest"' }), + })(new Request("https://dashboard.example/api/microcosm/releases?country=uk")); + expect(response.status).toBe(502); + expect((await response.json()).detail).toBe("releases.json is not a readable JSON document."); + expect(calls).toEqual([]); +}); + test("the manifest reader receives the folder listing, so releases published only as a tag are listed", async () => { const folderRelease = release("populace-us-2024-folder-20260915", "20260915"); const tagOnlyRelease = release( @@ -86,6 +223,7 @@ test("the manifest reader receives the folder listing, so releases published onl ); const foldersSeenByManifestReader: unknown[] = []; const response = await createMicrocosmReleasesHandler({ + loadReleasesRecord: async () => null, loadReleases: async () => [folderRelease], loadPointerReleaseId: async () => ({ release_id: folderRelease.release_id, diff --git a/frontend/app/api/microcosm/releases/route.ts b/frontend/app/api/microcosm/releases/route.ts index 5ea622e2..ff7d257b 100644 --- a/frontend/app/api/microcosm/releases/route.ts +++ b/frontend/app/api/microcosm/releases/route.ts @@ -2,17 +2,23 @@ import { NextResponse } from "next/server"; import { requestedCountry } from "@/lib/api/request-country"; import { readCalibrationTreeManifest } from "@policyengine/calibration-tree/calibration-tree-blob"; +import type { MicrocosmCountry } from "@policyengine/calibration-tree/countries"; import { loadPointerReleaseId, loadPublishedCutReleases, loadReleases, + loadReleasesRecord, mergeReleaseInventory, + recordedReleaseInventory, scrub, + type ReleaseEntry, } from "@policyengine/calibration-tree/latest-artifact"; +import type { ReleasesRecord } from "@policyengine/calibration-tree/release-record"; export const revalidate = 60; interface MicrocosmReleasesRouteDependencies { + loadReleasesRecord: typeof loadReleasesRecord; loadReleases: typeof loadReleases; loadPointerReleaseId: typeof loadPointerReleaseId; readManifest: typeof readCalibrationTreeManifest; @@ -21,32 +27,61 @@ interface MicrocosmReleasesRouteDependencies { export function createMicrocosmReleasesHandler( dependencies: MicrocosmReleasesRouteDependencies = { + loadReleasesRecord, loadReleases, loadPointerReleaseId, readManifest: readCalibrationTreeManifest, loadPublishedCutReleases, }, ) { + // A repository with releases.json lists the builds it names and nothing + // else; which of them are calibrated comes from the dashboard manifest, so + // the listing needs it. + async function recordedInventory(country: MicrocosmCountry, record: ReleasesRecord) { + const { manifest } = await dependencies.readManifest(); + return recordedReleaseInventory(record, country, manifest); + } + + // A repository without releases.json lists the folders on main beside its + // published tagged builds. + async function folderInventory( + country: MicrocosmCountry, + latestReleaseId: Promise, + ): Promise { + const [folders, manifest, latest] = await Promise.all([ + dependencies.loadReleases(revalidate, country), + dependencies.readManifest() + .then(({ manifest }) => manifest) + .catch(() => null), + latestReleaseId, + ]); + // Per-attempt tags and releases published only as a tag are named only + // by the dashboard manifest; without it the picker keeps the folder + // listing. + const cuts = manifest + ? await dependencies + .loadPublishedCutReleases(revalidate, country, manifest, folders) + .catch(() => []) + : []; + return mergeReleaseInventory(folders, cuts, latest); + } + return async function GET(request: Request) { const country = requestedCountry(new URL(request.url).searchParams); if (country instanceof Response) return country; try { - const [folders, pointer, manifest] = await Promise.all([ - dependencies.loadReleases(revalidate, country), - dependencies.loadPointerReleaseId(revalidate, country).catch(() => ({ release_id: "", updated_at: null })), - dependencies.readManifest() - .then(({ manifest }) => manifest) - .catch(() => null), - ]); - // Per-attempt tags and releases published only as a tag are named only - // by the dashboard manifest; without it the picker keeps the folder - // listing. - const cuts = manifest - ? await dependencies - .loadPublishedCutReleases(revalidate, country, manifest, folders) - .catch(() => []) - : []; - const releases = mergeReleaseInventory(folders, cuts, pointer.release_id || null); + // The dashboard's latest release, from its manifest. + const pointerRead = dependencies.loadPointerReleaseId(revalidate, country) + .catch(() => ({ release_id: "", updated_at: null })); + // releases.json decides which listing applies. One that cannot be read + // or is refused fails the request: tags and pointer files are never + // read in its place. + const inventory = dependencies.loadReleasesRecord(revalidate, country).then((record) => + record + ? recordedInventory(country, record) + : folderInventory(country, pointerRead.then((read) => read.release_id || null)) + ); + const [pointer, releases] = await Promise.all([pointerRead, inventory]); return NextResponse.json( scrub({ latest_release_id: pointer.release_id, diff --git a/frontend/components/microcosm/microcosm-overview-view.tsx b/frontend/components/microcosm/microcosm-overview-view.tsx index 56bf1b78..2a4e6d3b 100644 --- a/frontend/components/microcosm/microcosm-overview-view.tsx +++ b/frontend/components/microcosm/microcosm-overview-view.tsx @@ -123,7 +123,7 @@ export function MicrocosmReleaseHeader({ ) : null; const publicationUrl = data - ? microcosmPublicationUrl(data.source_repo, data.release_id) + ? microcosmPublicationUrl(data.source_repo, data.release_id, data.revision) : null; const overviewIntro = data ? microcosmOverviewIntro(country, calibration?.presentation) diff --git a/frontend/components/shared/format.test.ts b/frontend/components/shared/format.test.ts index 12bcbdc5..8bd46ca2 100644 --- a/frontend/components/shared/format.test.ts +++ b/frontend/components/shared/format.test.ts @@ -67,3 +67,13 @@ test("Microcosm cut labels name their line and attempt", () => { releaseLabel("populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z", "20260619T023711Z"), ).toBe("2026-06-19 02:37Z · populace"); }); + +test("build-folder labels name the release and the build", () => { + const build = "microcosm-uk-2024-25-national/uk-frs-calibration-attempt-20261019T083323Z-6cba5d71"; + expect(releaseLabel(build, "20261019T083323Z")).toBe( + "2026-10-19 08:33Z · 2024-25-national · uk-frs-calibration-attempt-20261019T083323Z-6cba5d71", + ); + expect(releaseLabel(build)).toBe( + "2024-25-national · uk-frs-calibration-attempt-20261019T083323Z-6cba5d71", + ); +}); diff --git a/frontend/components/shared/format.ts b/frontend/components/shared/format.ts index d573e7bb..a363792e 100644 --- a/frontend/components/shared/format.ts +++ b/frontend/components/shared/format.ts @@ -1,6 +1,7 @@ import { formatNumber } from "@policyengine/ui-kit"; import { parseReleaseCutTag } from "@policyengine/calibration-tree/release-cut"; +import { parseBuildFolderId } from "@policyengine/calibration-tree/release-record"; // Tax/benefit acronyms shown uppercase rather than as words. const ACRONYMS = new Set([ @@ -55,10 +56,20 @@ export function shortReleaseId(releaseId: string, length = 6): string { return releaseId.replace(/^populace-us-\d{4}-/, "").split("-")[0].slice(0, length); } -// A readable label for a release: "2026-06-14 · f32c2e5". A Microcosm cut -// (microcosm#823) names its line and attempt instead: -// "2026-10-19 08:33Z · 2024-25-national · 6cba5d71". +// A readable label for a release: "2026-06-14 · f32c2e5". A build in its own +// folder (`/`) names its release and its whole build, dated +// by its publication: "2026-10-19 08:33Z · 2024-25-national · ". A +// tagged Microcosm build (microcosm#823) names its release and the attempt +// suffix of its tag instead: "2026-10-19 08:33Z · 2024-25-national · 6cba5d71". export function releaseLabel(releaseId: string, date?: string | null): string { + const buildFolder = parseBuildFolderId(releaseId); + if (buildFolder) { + // Deprecated upstream identifier: Microcosm release IDs may still use the + // former Populace prefix. + const release = buildFolder.release.replace(/^(?:microcosm|populace)-[a-z]{2}-/, ""); + const formatted = formatReleaseDate(date); + return [formatted, release, buildFolder.build].filter(Boolean).join(" · "); + } const cut = parseReleaseCutTag(releaseId); if (cut) { // Deprecated upstream identifier: Microcosm release IDs may still use the diff --git a/frontend/lib/api/hooks/use-microcosm.test.ts b/frontend/lib/api/hooks/use-microcosm.test.ts index 2b0928a3..ced2f563 100644 --- a/frontend/lib/api/hooks/use-microcosm.test.ts +++ b/frontend/lib/api/hooks/use-microcosm.test.ts @@ -8,6 +8,7 @@ import { microcosmComparisonTreeIndexQueryOptions, microcosmStagingCalibrationTreeQueryOptions, microcosmStagingTargetChangeSourceParameters, + releaseSelectOptions, } from "./use-microcosm"; test("calibration tree part requests start without waiting for earlier parts", async () => { @@ -93,3 +94,50 @@ test("live candidates compare with the selected immutable staging build", () => microcosmStagingTargetChangeSourceParameters("latest-release"), ).toEqual({ release: "latest-release" }); }); + +test("the release picker keeps a withdrawn build selectable and labels it Withdrawn", () => { + const release = "microcosm-uk-2024-25-national"; + const entry = (build: string, withdrawn: boolean) => ({ + release_id: `${release}/${build}`, + date: "20261019T083323Z", + files: [], + has_calibration: true, + release, + build, + withdrawn, + }); + const withdrawn = entry("uk-frs-calibration-attempt-20261014T214443Z-d12ff9b3", true); + const current = entry("uk-frs-calibration-attempt-20261019T083323Z-6cba5d71", false); + const options = releaseSelectOptions({ + latest_release_id: current.release_id, + updated_at: null, + releases: [current, withdrawn], + all_releases: [current, withdrawn], + }); + const label = (id: string) => options.find((option) => option.value === id)?.label ?? ""; + expect(label(withdrawn.release_id)).toEndWith(" · Withdrawn"); + expect(label(current.release_id)).not.toContain("Withdrawn"); +}); + +test("the picker's Latest option is labelled Withdrawn when the latest release is a withdrawn build", () => { + const release = "microcosm-uk-2024-25-national"; + const build = "uk-frs-calibration-attempt-20261014T214443Z-d12ff9b3"; + const latest = { + release_id: `${release}/${build}`, + date: "20261014T214443Z", + files: [], + has_calibration: true, + release, + build, + withdrawn: true, + }; + const [latestOption] = releaseSelectOptions({ + latest_release_id: latest.release_id, + updated_at: null, + releases: [latest], + all_releases: [latest], + }); + expect(latestOption.value).toBe(""); + expect(latestOption.label).toStartWith("Latest · "); + expect(latestOption.label).toEndWith(" · Withdrawn"); +}); diff --git a/frontend/lib/api/hooks/use-microcosm.ts b/frontend/lib/api/hooks/use-microcosm.ts index 7b377af3..a4c38cfc 100644 --- a/frontend/lib/api/hooks/use-microcosm.ts +++ b/frontend/lib/api/hooks/use-microcosm.ts @@ -369,6 +369,11 @@ export interface MicrocosmReleaseEntry { is_local_area?: boolean; // A Microcosm cut's line folder; absent when the folder is release_id. release_directory?: string; + // A build in its own folder (release_id is `/`): its + // release and build, and whether releases.json marks it withdrawn. + release?: string; + build?: string; + withdrawn?: boolean; } export interface MicrocosmReleasesResponse { @@ -973,6 +978,12 @@ export function releaseRoleSuffix(entry: MicrocosmReleaseEntry): string { return ""; } +// A build releases.json marks withdrawn stays listed and selectable, labelled +// so that nobody takes it for a build in use. +export function releaseWithdrawnSuffix(entry: MicrocosmReleaseEntry): string { + return entry.withdrawn ? " · Withdrawn" : ""; +} + // The empty selection follows the dashboard manifest; explicit ids remain // historical release selections. export function releaseSelectOptions( @@ -986,12 +997,13 @@ export function releaseSelectOptions( { value: "", label: selectedDefault - ? `${defaultLabel} · ${releaseLabel(selectedDefault.release_id, selectedDefault.date)}` + ? `${defaultLabel} · ${releaseLabel(selectedDefault.release_id, selectedDefault.date)}` + + releaseWithdrawnSuffix(selectedDefault) : defaultLabel, }, ...releases.map((r) => ({ value: r.release_id, - label: `${releaseLabel(r.release_id, r.date)}${releaseRoleSuffix(r)}`, + label: `${releaseLabel(r.release_id, r.date)}${releaseRoleSuffix(r)}${releaseWithdrawnSuffix(r)}`, })), ]; } diff --git a/frontend/lib/microcosm/source-attribution.test.ts b/frontend/lib/microcosm/source-attribution.test.ts index 1f6fc037..534ead0b 100644 --- a/frontend/lib/microcosm/source-attribution.test.ts +++ b/frontend/lib/microcosm/source-attribution.test.ts @@ -16,6 +16,31 @@ test("links a Microcosm release to its exact Hugging Face tag", () => { ); }); +test("links a build in its own folder to that folder at its pinned commit", () => { + // A build folder has no tag of its own: `/tree/%2F` would + // name a revision that does not exist. + const commitSha = "0123456789abcdef0123456789abcdef01234567"; + const buildFolder = + "microcosm-uk-2024-25-national/uk-frs-calibration-attempt-20261019T083323Z-6cba5d71"; + expect( + microcosmPublicationUrl("policyengine/populace-uk-private", buildFolder, commitSha), + ).toBe( + "https://huggingface.co/datasets/policyengine/populace-uk-private/tree/" + + `${commitSha}/releases/${buildFolder}`, + ); + // A tagged release still opens at its tag. + expect( + microcosmPublicationUrl( + "policyengine/populace-uk-private", + "microcosm-uk-2024-25-national-20261019T083323Z-6cba5d71", + commitSha, + ), + ).toBe( + "https://huggingface.co/datasets/policyengine/populace-uk-private/tree/" + + "microcosm-uk-2024-25-national-20261019T083323Z-6cba5d71", + ); +}); + test("links Microcosm to the public US Hugging Face dataset", () => { expect(microcosmSourceAttribution("us", "policyengine/populace-us")).toEqual({ label: "Microcosm", diff --git a/frontend/lib/microcosm/source-attribution.ts b/frontend/lib/microcosm/source-attribution.ts index d8d9761b..3f252820 100644 --- a/frontend/lib/microcosm/source-attribution.ts +++ b/frontend/lib/microcosm/source-attribution.ts @@ -3,6 +3,7 @@ import { type MicrocosmCountry, type RepositoryVisibility, } from "@policyengine/calibration-tree/countries"; +import { parseBuildFolderId } from "@policyengine/calibration-tree/release-record"; export interface MicrocosmSourceAttribution { label: string; @@ -16,11 +17,21 @@ function huggingFaceRepoPath(sourceRepo: string): string { .join("/"); } +// A release opens at its tag. A build in its own folder (`/`) +// has no tag, so it opens as its folder at the commit it was read from. export function microcosmPublicationUrl( sourceRepo: string, releaseId: string, + revision?: string | null, ): string { const repoPath = huggingFaceRepoPath(sourceRepo); + const buildFolder = parseBuildFolderId(releaseId); + if (buildFolder) { + return ( + `https://huggingface.co/datasets/${repoPath}/tree/${encodeURIComponent(revision || "main")}` + + `/releases/${encodeURIComponent(buildFolder.release)}/${encodeURIComponent(buildFolder.build)}` + ); + } return `https://huggingface.co/datasets/${repoPath}/tree/${encodeURIComponent(releaseId)}`; } diff --git a/frontend/packages/calibration-tree/package.json b/frontend/packages/calibration-tree/package.json index bbafc764..349e0155 100644 --- a/frontend/packages/calibration-tree/package.json +++ b/frontend/packages/calibration-tree/package.json @@ -27,6 +27,7 @@ "./publish-calibration-tree": "./src/publish-calibration-tree.ts", "./reforms": "./src/reforms.ts", "./release-cut": "./src/release-cut.ts", + "./release-record": "./src/release-record.ts", "./source-label": "./src/source-label.ts", "./source-labels": "./src/source-labels.ts", "./staging-artifact": "./src/staging-artifact.ts", diff --git a/frontend/packages/calibration-tree/src/calibration-release-locator.test.ts b/frontend/packages/calibration-tree/src/calibration-release-locator.test.ts index 09c46901..42a695a7 100644 --- a/frontend/packages/calibration-tree/src/calibration-release-locator.test.ts +++ b/frontend/packages/calibration-tree/src/calibration-release-locator.test.ts @@ -2,6 +2,8 @@ import { afterEach, expect, test } from "bun:test"; import { calibrationReleaseFromManifest, + requestedReleaseId, + resolveHfBuildFolderSha, resolveHfCommitPublishedAt, resolveHfRepositoryCommitPublishedAt, resolveHfReleaseDirectorySha, @@ -75,6 +77,63 @@ test("a release cut is located by its tag and read from its line folder", () => expect(calibrationReleaseFromManifest(manifest, "uk").releaseId).toBe(cut); }); +test("a build in its own folder is located and read by that folder", () => { + const build = "microcosm-zz-2024-national/zz-calibration-attempt-20261019T083323Z-0a1b2c3d"; + const manifest = withCalibrationTreeManifestEntry( + emptyCalibrationTreeManifest(), + "uk", + { + buildArtifactId: "b".repeat(64), + kind: "release", + sourceId: build, + label: build, + releaseId: build, + stagingRunId: null, + hfRepo: "policyengine/populace-uk-private", + hfCommitSha: "2".repeat(40), + treeSchemaVersion: 6, + indexSha256: "c".repeat(64), + indexBytes: 20, + createdAt: "2026-10-19T08:33:23.000Z", + updatedAt: "2026-10-19T08:33:23.000Z", + }, + true, + ); + expect(calibrationReleaseFromManifest(manifest, "uk", build)).toMatchObject({ + releaseId: build, + releaseDirectory: build, + hfCommitSha: "2".repeat(40), + }); +}); + +test("a requested release may name a build folder, never a path that leaves releases/", () => { + expect(requestedReleaseId("")).toBe("latest"); + expect(requestedReleaseId("latest")).toBe("latest"); + expect(requestedReleaseId("microcosm-uk-2024-25-national")).toBe("microcosm-uk-2024-25-national"); + expect(requestedReleaseId("microcosm-uk-2024-25-national/uk-frs-calibration-attempt-x")) + .toBe("microcosm-uk-2024-25-national/uk-frs-calibration-attempt-x"); + for (const value of ["../latest", "a/..", "a/b/c", "a//b", "/a", "a b"]) { + expect(() => requestedReleaseId(value), value).toThrow("Invalid release id."); + } +}); + +test("a build folder's commit is the newest commit behind its files, read at the given revision", async () => { + const revision = "5".repeat(40); + const requested: string[] = []; + globalThis.fetch = (async (input: string | URL | Request) => { + requested.push(String(input)); + return Response.json([ + { type: "file", path: "releases/r/b/calibration_diagnostics.json", lastCommit: { id: "1".repeat(40), date: "2026-10-19T08:00:00Z" } }, + { type: "file", path: "releases/r/b/microcosm_uk_2024_25.h5", lastCommit: { id: "2".repeat(40), date: "2026-10-19T09:00:00Z" } }, + ]); + }) as typeof fetch; + await expect(resolveHfBuildFolderSha("uk", "r/b", revision)).resolves.toBe("2".repeat(40)); + expect(requested).toEqual([ + `https://huggingface.co/api/datasets/policyengine/populace-uk-private/tree/${revision}/releases/r/b?recursive=false&expand=true`, + ]); + await expect(resolveHfBuildFolderSha("uk", "r", revision)).rejects.toThrow("Invalid build folder."); +}); + test("historical release tags resolve to exact Hugging Face commits", async () => { globalThis.fetch = (async (input: string | URL | Request) => { expect(String(input)).toContain("/revision/microcosm-us-history"); diff --git a/frontend/packages/calibration-tree/src/calibration-release-locator.ts b/frontend/packages/calibration-tree/src/calibration-release-locator.ts index e27982aa..91ec0418 100644 --- a/frontend/packages/calibration-tree/src/calibration-release-locator.ts +++ b/frontend/packages/calibration-tree/src/calibration-release-locator.ts @@ -8,11 +8,16 @@ import { countryRegistration, type MicrocosmCountry, } from "./countries"; +import { isBuildFolderId, parseBuildFolderId } from "./release-record"; export interface CalibrationReleaseLocation { buildArtifactId: string; releaseId: string; - /** The `releases/` folder holding the files: releaseId unless a cut tag. */ + /** + * The `releases/` folder holding the files: releaseId, which for a build + * in its own folder is `/`, unless releaseId is a tag read + * from its release's folder. + */ releaseDirectory: string; hfCommitSha: string; updatedAt: string | null; @@ -136,7 +141,68 @@ export async function resolveHfReleaseDirectorySha( ); } - const entries = await response.json() as Array<{ + return newestCommitOfCalibratedFolder( + await response.json(), + prefix, + `release ${release}`, + country, + ); +} + +/** + * The commit that wrote a build folder, `releases///`, as + * the folder is at `revision` (an exact commit, so the folder and the + * `releases.json` read beside it come from one snapshot). A build folder is + * never changed after publishing, so the newest commit behind its files is + * the one that wrote it, and every file is read there. + */ +export async function resolveHfBuildFolderSha( + country: MicrocosmCountry, + folderId: string, + revision: string, + revalidate = 0, +): Promise { + const folder = parseBuildFolderId(folderId); + if (!folder) throw new Error("Invalid build folder."); + const safeRevision = safeReleaseId(revision, "Hugging Face revision"); + const repo = repository(country); + const response = await fetch( + `https://huggingface.co/api/datasets/${repo}/tree/${encodeURIComponent(safeRevision)}` + + `/releases/${encodeURIComponent(folder.release)}/${encodeURIComponent(folder.build)}` + + "?recursive=false&expand=true", + { + headers: hfHeaders(), + signal: AbortSignal.timeout(30_000), + ...(revalidate <= 0 + ? { cache: "no-store" as const } + : { next: { revalidate } }), + }, + ); + if (response.status === 404) { + throw new CalibrationReleaseNotFoundError( + `Hugging Face build folder releases/${folderId}/ was not found for ${country}.`, + ); + } + if (!response.ok) { + throw new Error(`Hugging Face build folder lookup failed with ${response.status}.`); + } + return newestCommitOfCalibratedFolder( + await response.json(), + `releases/${folderId}/`, + `build folder releases/${folderId}/`, + country, + ); +} + +// The newest commit behind a folder listing's files (an expanded Hugging +// Face tree response), refusing a folder without calibration diagnostics. +function newestCommitOfCalibratedFolder( + listing: unknown, + prefix: string, + subject: string, + country: MicrocosmCountry, +): string { + const entries = listing as Array<{ path?: unknown; type?: unknown; lastCommit?: { id?: unknown; date?: unknown }; @@ -154,7 +220,7 @@ export async function resolveHfReleaseDirectorySha( (entry) => entry.path === `${prefix}calibration_diagnostics.json`, )) { throw new CalibrationReleaseNotFoundError( - `Hugging Face release ${release} has no calibration diagnostics for ${country}.`, + `Hugging Face ${subject} has no calibration diagnostics for ${country}.`, ); } @@ -167,7 +233,7 @@ export async function resolveHfReleaseDirectorySha( : Number.NaN; if (!/^[0-9a-f]{40,64}$/.test(id) || !Number.isFinite(date)) { throw new Error( - `Hugging Face returned invalid commit metadata for release ${release}.`, + `Hugging Face returned invalid commit metadata for ${subject}.`, ); } return { id, date }; @@ -175,7 +241,7 @@ export async function resolveHfReleaseDirectorySha( commits.sort((left, right) => right.date - left.date); if (!commits[0]) { throw new CalibrationReleaseNotFoundError( - `Hugging Face release ${release} has no source files for ${country}.`, + `Hugging Face ${subject} has no source files for ${country}.`, ); } return commits[0].id; @@ -245,14 +311,22 @@ export async function resolveHfCommitPublishedAt( return resolveHfRepositoryCommitPublishedAt(repository(country), sha, revalidate); } +/** + * A requested release: "latest" (also for an empty request), a release id + * (a release folder or a tag), or a build folder, `/`. + */ +export function requestedReleaseId(requestedRelease: string): string { + if (!requestedRelease || requestedRelease === "latest") return "latest"; + if (isBuildFolderId(requestedRelease)) return requestedRelease; + return safeReleaseId(requestedRelease); +} + export async function resolveCalibrationRelease( country: MicrocosmCountry, requestedRelease: string, _revalidate = 3600, ): Promise { - const releaseId = requestedRelease && requestedRelease !== "latest" - ? safeReleaseId(requestedRelease) - : "latest"; + const releaseId = requestedReleaseId(requestedRelease); const { manifest } = await readCalibrationTreeManifest(); return calibrationReleaseFromManifest(manifest, country, releaseId); } diff --git a/frontend/packages/calibration-tree/src/countries.test.ts b/frontend/packages/calibration-tree/src/countries.test.ts index cfdfecb4..4ebb4376 100644 --- a/frontend/packages/calibration-tree/src/countries.test.ts +++ b/frontend/packages/calibration-tree/src/countries.test.ts @@ -264,3 +264,12 @@ test("only the UK resolves its current release through a line pointer", () => { if (pointer != null) expect(pointer).toMatch(/^latest-[a-z]+(-k[1-9][0-9]*)?\.json$/); } }); + +test("no registration says how its releases are published: every reader looks for releases.json", () => { + // A dataset repository with releases.json is read from it and its build + // folders; one without is read from its tags and pointer files. So a + // repository's switch to releases.json needs no change to its registration. + for (const country of COUNTRIES) { + expect(Object.hasOwn(countryRegistration(country), "release_layout"), country).toBe(false); + } +}); diff --git a/frontend/packages/calibration-tree/src/countries.ts b/frontend/packages/calibration-tree/src/countries.ts index 9c826d3a..2c66c266 100644 --- a/frontend/packages/calibration-tree/src/countries.ts +++ b/frontend/packages/calibration-tree/src/countries.ts @@ -41,7 +41,10 @@ export interface CountryRegistration { // The repository-root pointer naming the country's current release: // `latest.json` unless the country promotes its default line through a // per-line pointer (`latest-.json`, microcosm#823) whose payload also - // names the immutable cut tag the release is read at. + // names the immutable tag the release is read at (`cut_tag`). Read only + // while the dataset repository has no `releases.json`; a repository with + // one is read from it and its build folders alone, whatever the + // registration says (release-record.ts). pointer_path?: string; // Country display name ("United States"). label: string; @@ -117,7 +120,9 @@ export const COUNTRY_REGISTRY = { capabilities: [...CALIBRATION_CAPABILITIES, "staging"], // microcosm#823: the UK default line is the 2024-25 national dataset, // promoted through its own pointer; `latest.json` stays on the June 2023 - // release and is never moved. + // release and is never moved. Unread once the repository has + // releases.json: Microcosm's switch writes it and deletes the pointer + // files in one commit. pointer_path: "latest-national.json", staging: { repo: "policyengine/populace-uk-staging", diff --git a/frontend/packages/calibration-tree/src/latest-artifact.test.ts b/frontend/packages/calibration-tree/src/latest-artifact.test.ts index 7becf0f0..b39814a0 100644 --- a/frontend/packages/calibration-tree/src/latest-artifact.test.ts +++ b/frontend/packages/calibration-tree/src/latest-artifact.test.ts @@ -12,6 +12,7 @@ import beReleaseManifestFixture from "./fixtures/be-release/release_manifest.jso import { buildCalibration, buildComparison, + calibrationAsReleased, calibrationLossKind, classifyApiError, diagnosticsDimensions, @@ -27,6 +28,7 @@ import { latestMicrocosmTargetInvestigation, loadPointerReleaseId, loadPublishedCutReleases, + loadRecordedReleases, loadRelease, loadReleases, mergeReleaseInventory, @@ -49,9 +51,11 @@ import { import { emptyCalibrationTreeManifest, withCalibrationTreeManifestEntry, + type CalibrationTreeManifest, type CalibrationTreeManifestEntry, } from "./calibration-tree-manifest"; import { buildCalibrationTree } from "./calibration-tree"; +import { missingReleasesRecord, missingRevision } from "./test-support/releases-record-responses"; test("keeps Microcosm deployment configuration on its published Populace env contract", () => { expect([ @@ -3281,6 +3285,57 @@ test("published cuts take their role from their own release manifest at their co } }); +// A repository whose releases.json is removed again (a reverted switch) is +// read from its tags and folders, but the dashboard manifest keeps the entries +// the build-folder readers published, named `/`. Those readers +// list only tags and folders, so such an entry must not stop them. Ids and +// commits are synthetic. +test("a build-folder entry in the manifest does not stop the tagged builds being listed", async () => { + const nationalTag = `${LINE}-20261019T083323Z-0b0b0b0b`; + const buildFolder = `${LINE}/uk-frs-calibration-attempt-20261020T091500Z-1d1d1d1d`; + const manifestEntry = ( + releaseId: string, + releaseDirectory: string | undefined, + commit: string, + artifactDigit: string, + ): CalibrationTreeManifestEntry => ({ + buildArtifactId: artifactDigit.repeat(64), + kind: "release", + sourceId: releaseId, + label: releaseId, + releaseId, + ...(releaseDirectory ? { releaseDirectory } : {}), + stagingRunId: null, + hfRepo: "policyengine/populace-uk-private", + hfCommitSha: commit, + treeSchemaVersion: 6, + indexSha256: "e".repeat(64), + indexBytes: 10, + createdAt: "2026-10-20T09:15:00.000Z", + updatedAt: null, + }); + let manifest = emptyCalibrationTreeManifest(); + for (const build of [ + manifestEntry(nationalTag, LINE, "1".repeat(40), "a"), + // A build in its own folder records no separate releaseDirectory. + manifestEntry(buildFolder, undefined, "6".repeat(40), "b"), + ]) { + manifest = withCalibrationTreeManifestEntry(manifest, "uk", build); + } + const originalFetch = globalThis.fetch; + // No release manifest is readable: each entry keeps its default role. + globalThis.fetch = (async (_input: string | URL | Request) => + new Response(null, { status: 503 })) as typeof fetch; + try { + const tagged = await loadPublishedCutReleases(0, "uk", manifest, [folderRelease(LINE, LINE)]); + expect(tagged.map((release) => [release.release_id, release.release_directory])).toEqual([ + [nationalTag, LINE], + ]); + } finally { + globalThis.fetch = originalFetch; + } +}); + // Microcosm can publish a release as a tag alone (`--no-latest --tag-only`): // `releases//` exists at the tag's commit and never on main, so // the folder listing cannot name it. A folder on main without calibration @@ -3478,3 +3533,322 @@ test("a cut's investigation packet cites its line folder at the cut's commit", ( }, }); }); + +// Build folders (microcosm-emitter#24): every build in +// releases///, and releases.json as the only record of +// which builds exist and which is current. All values are synthetic. +const NATIONAL_OLDER = "uk-frs-calibration-attempt-20261014T214443Z-d12ff9b3"; +const NATIONAL_CURRENT = "uk-frs-calibration-attempt-20261019T083323Z-6cba5d71"; +const DENSE_BUILD = "uk-local-candidate-f100-s42-20261019T000432Z-ee5c2dbe"; +const RECORDED_RELEASES = { + schema_version: 1, + default: LINE, + releases: { + [LINE]: { + role: "national", + current: NATIONAL_CURRENT, + builds: { + [NATIONAL_OLDER]: { published_at: "2026-10-14T21:44:43+00:00", withdrawn: true }, + [NATIONAL_CURRENT]: { published_at: "2026-10-19T08:33:23+00:00", withdrawn: false }, + }, + }, + [DENSE_LINE]: { + role: "local_area", + current: null, + builds: { + [DENSE_BUILD]: { published_at: "2026-10-19T07:53:18+00:00", withdrawn: false }, + }, + }, + }, +}; + +function publishedBuildManifest(releaseIds: string[]) { + return releaseIds.reduce( + (manifest, releaseId, index) => withCalibrationTreeManifestEntry(manifest, "uk", { + buildArtifactId: String(index + 1).repeat(64), + kind: "release", + sourceId: releaseId, + label: releaseId, + releaseId, + stagingRunId: null, + hfRepo: microcosmRepo("uk"), + hfCommitSha: String(index + 1).repeat(40), + treeSchemaVersion: 6, + indexSha256: "e".repeat(64), + indexBytes: 10, + createdAt: null, + updatedAt: null, + }), + emptyCalibrationTreeManifest(), + ); +} + +async function withRecordedReleases( + record: unknown, + run: (requested: string[]) => Promise, + recordResponse: () => Response = () => Response.json(record), +): Promise { + const originalFetch = globalThis.fetch; + const requested: string[] = []; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input); + requested.push(url); + if (url === hfResolveUrl("releases.json", "uk")) return recordResponse(); + throw new Error(`Unexpected URL ${url}`); + }) as typeof fetch; + try { + return await run(requested); + } finally { + globalThis.fetch = originalFetch; + } +} + +// The picker inventory of a repository that has releases.json. +async function recordedInventory(manifest: CalibrationTreeManifest) { + const releases = await loadRecordedReleases(0, "uk", manifest); + if (!releases) throw new Error("The fixture repository's releases.json was not read."); + return releases; +} + +test("the release picker lists every build releases.json lists, named by its folder, with its release's role and publication time", async () => { + const manifest = publishedBuildManifest([ + `${LINE}/${NATIONAL_OLDER}`, + `${LINE}/${NATIONAL_CURRENT}`, + `${DENSE_LINE}/${DENSE_BUILD}`, + ]); + const releases = await withRecordedReleases(RECORDED_RELEASES, () => + loadRecordedReleases(0, "uk", manifest), + ); + expect(releases).toEqual([ + { + release_id: `${LINE}/${NATIONAL_CURRENT}`, + date: "20261019T083323Z", + files: [], + has_calibration: true, + dataset_role: "national", + is_default: true, + is_local_area: false, + release: LINE, + build: NATIONAL_CURRENT, + withdrawn: false, + }, + { + release_id: `${DENSE_LINE}/${DENSE_BUILD}`, + date: "20261019T075318Z", + files: [], + has_calibration: true, + dataset_role: "local_area", + is_default: false, + is_local_area: true, + release: DENSE_LINE, + build: DENSE_BUILD, + withdrawn: false, + }, + { + release_id: `${LINE}/${NATIONAL_OLDER}`, + date: "20261014T214443Z", + files: [], + has_calibration: true, + dataset_role: "national", + is_default: true, + is_local_area: false, + release: LINE, + build: NATIONAL_OLDER, + // Listed and selectable; the picker labels it "Withdrawn". + withdrawn: true, + }, + ]); +}); + +test("a listed build counts as calibrated only once its calibration tree is in the dashboard manifest", async () => { + const releases = await withRecordedReleases(RECORDED_RELEASES, () => + recordedInventory(publishedBuildManifest([`${LINE}/${NATIONAL_CURRENT}`])), + ); + expect(Object.fromEntries(releases.map((release) => [release.release_id, release.has_calibration]))) + .toEqual({ + [`${LINE}/${NATIONAL_CURRENT}`]: true, + [`${DENSE_LINE}/${DENSE_BUILD}`]: false, + [`${LINE}/${NATIONAL_OLDER}`]: false, + }); +}); + +test("the release picker reads releases.json and nothing else from the dataset repository", async () => { + const requested = await withRecordedReleases(RECORDED_RELEASES, async (requested) => { + await loadRecordedReleases(0, "uk", emptyCalibrationTreeManifest()); + return requested; + }); + expect(requested).toEqual([hfResolveUrl("releases.json", "uk")]); +}); + +test("the dashboard's latest release stays listed until reconciliation moves it to releases.json's current build", async () => { + // Microcosm's migration has written releases.json, but the dashboard + // manifest's latest release is still the tagged build published before + // the switch. The deployment's pre-promotion check requires the latest + // release to be listed and calibrated. + const taggedBuild = `${LINE}-20261019T083323Z-6cba5d71`; + const taggedEntry: CalibrationTreeManifestEntry = { + buildArtifactId: "9".repeat(64), + kind: "release", + sourceId: taggedBuild, + label: taggedBuild, + releaseId: taggedBuild, + releaseDirectory: LINE, + stagingRunId: null, + hfRepo: microcosmRepo("uk"), + hfCommitSha: "9".repeat(40), + treeSchemaVersion: 6, + indexSha256: "e".repeat(64), + indexBytes: 10, + createdAt: "2026-10-19T10:21:22.000Z", + updatedAt: "2026-10-19T10:21:22.000Z", + }; + const recordedCurrent = `${LINE}/${NATIONAL_CURRENT}`; + const beforeReconciliation = withCalibrationTreeManifestEntry( + publishedBuildManifest([recordedCurrent]), + "uk", + taggedEntry, + true, + ); + const releases = await withRecordedReleases(RECORDED_RELEASES, () => + recordedInventory(beforeReconciliation), + ); + expect(releases.map((release) => release.release_id)).toEqual([ + taggedBuild, + recordedCurrent, + `${DENSE_LINE}/${DENSE_BUILD}`, + `${LINE}/${NATIONAL_OLDER}`, + ]); + expect(releases[0]).toEqual({ + release_id: taggedBuild, + date: "20261019T102122Z", + files: [], + has_calibration: true, + dataset_role: null, + is_default: true, + is_local_area: false, + release_directory: LINE, + }); + + // Once the latest release is a build releases.json lists, only the + // recorded builds are listed. + const recordedCurrentEntry = beforeReconciliation.countries.uk?.builds.find( + (build) => build.releaseId === recordedCurrent, + ); + if (!recordedCurrentEntry) throw new Error("The recorded build is missing from the fixture."); + const afterReconciliation = withCalibrationTreeManifestEntry( + beforeReconciliation, + "uk", + recordedCurrentEntry, + true, + ); + const reconciled = await withRecordedReleases(RECORDED_RELEASES, () => + recordedInventory(afterReconciliation), + ); + expect(reconciled.map((release) => release.release_id)).toEqual([ + recordedCurrent, + `${DENSE_LINE}/${DENSE_BUILD}`, + `${LINE}/${NATIONAL_OLDER}`, + ]); +}); + +test("the release picker reads no record from a repository without releases.json", async () => { + const requested = await withRecordedReleases(null, async (requested) => { + await expect(loadRecordedReleases(0, "uk", emptyCalibrationTreeManifest())).resolves.toBeNull(); + return requested; + }, missingReleasesRecord); + // The route then lists the release folders and tagged builds instead. + expect(requested).toEqual([hfResolveUrl("releases.json", "uk")]); +}); + +test("for the release picker, a 404 that says the revision is missing is an error, not a repository without releases.json", async () => { + await withRecordedReleases(null, async () => { + await expect(loadRecordedReleases(0, "uk", emptyCalibrationTreeManifest())).rejects.toThrow("404"); + }, missingRevision); +}); + +// The writer's ReleasesRecord.parse refuses a record over MAX_RECORD_BYTES +// (4 MiB), the size check_change keeps every record within. +test("the release picker refuses a releases.json larger than the release writer accepts", async () => { + // Trailing whitespace keeps the record otherwise valid. + const oversized = JSON.stringify(RECORDED_RELEASES) + " ".repeat(4 * 1024 * 1024); + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: string | URL | Request) => { + if (String(input) === hfResolveUrl("releases.json", "uk")) return new Response(oversized); + throw new Error(`Unexpected URL ${String(input)}`); + }) as typeof fetch; + try { + await expect(loadRecordedReleases(0, "uk", emptyCalibrationTreeManifest())) + .rejects.toThrow("releases.json is larger than 4194304 bytes."); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("the release picker refuses a releases.json the release writer would refuse", async () => { + const withdrawnCurrent = structuredClone(RECORDED_RELEASES); + withdrawnCurrent.releases[LINE].builds[NATIONAL_CURRENT].withdrawn = true; + await withRecordedReleases(withdrawnCurrent, async () => { + await expect(loadRecordedReleases(0, "uk", emptyCalibrationTreeManifest())) + .rejects.toThrow("is withdrawn"); + }); +}); + +function nationalDiagnostics(releaseId: string) { + return { + schema_version: 8, + release_id: releaseId, + targets: [{ + name: "provider.target@2025", + target_name: "provider.target", + source: "Citation", + target: 100, + initial_estimate: 90, + final_estimate: 100, + hierarchy: { + provider: { id: "provider", label: "Provider label" }, + category: { id: "provider.category", label: "Category label", provider_id: "provider" }, + geography: { id: "K02000001", label: "United Kingdom", level: "country" }, + dimensions: [], + target: { id: "provider.target", label: "Target label" }, + }, + }], + }; +} + +test("a build keeps its folder as its release id when its diagnostics name only its release", () => { + const id = `${LINE}/${NATIONAL_CURRENT}`; + const calibration = calibrationAsReleased( + buildCalibration(nationalDiagnostics(LINE), id, null, {}, {}, {}, "uk"), + id, + id, + ); + expect(calibration.release_id).toBe(id); + expect(calibration.release_directory).toBe(id); + + // A release folder keeps the id its diagnostics carry, as before. + const folder = buildCalibration(nationalDiagnostics("x"), "x", null, {}, {}, {}, "uk"); + expect(calibrationAsReleased(folder, "x", "x")).toBe(folder); +}); + +test("a build's investigation packet cites its own folder at its pinned commit", () => { + const id = `${LINE}/${NATIONAL_CURRENT}`; + const sha = "2".repeat(40); + const cal = calibrationAsReleased( + buildCalibration(nationalDiagnostics(LINE), id, null, {}, {}, {}, "uk", "huggingface_immutable", null, sha), + id, + id, + ); + const packet = latestMicrocosmTargetInvestigation( + `https://dashboard.example/api/microcosm/target-investigation?target=${encodeURIComponent(String(cal.rows[0].name))}`, + cal, + ); + expect(packet).toMatchObject({ + available: true, + release_id: id, + source_artifact: { + hf_revision: sha, + calibration_diagnostics_path: `releases/${id}/calibration_diagnostics.json`, + release_manifest_path: `releases/${id}/release_manifest.json`, + }, + }); +}); diff --git a/frontend/packages/calibration-tree/src/latest-artifact.ts b/frontend/packages/calibration-tree/src/latest-artifact.ts index 04d4d1cf..fc001725 100644 --- a/frontend/packages/calibration-tree/src/latest-artifact.ts +++ b/frontend/packages/calibration-tree/src/latest-artifact.ts @@ -64,6 +64,14 @@ import { } from "./calibration-tree-manifest"; import { levelQualifiedGeographyLabels } from "./geography-labels"; import { parseReleaseCutTag } from "./release-cut"; +import { + RELEASES_RECORD_PATH, + isBuildFolderId, + isReleaseDirectory, + recordedBuilds, + releasesRecordFromResponse, + type ReleasesRecord, +} from "./release-record"; // The registry is the registration point; these re-exports keep the server // modules and routes that import country helpers from here working. @@ -134,6 +142,13 @@ export function assertSafeReleaseId(id: string, label = "release"): string { return id; } +// A release id, or a build in its own folder (`/`), which is +// how a repository with releases.json names each build. Each segment +// passes the same allowlist, and nothing longer is accepted. +export function assertSafeReleaseOrBuildFolderId(id: string, label = "release"): string { + return isBuildFolderId(id) ? id : assertSafeReleaseId(id, label); +} + // Route catch → HTTP: a bad id is the caller's fault (400); a country without // a configured release is an explicit not-configured state (404); anything // else is an upstream/HF failure (502). Keeps status semantics consistent @@ -1999,9 +2014,10 @@ export interface Calibration { description: string | null; diagnostics_status: DiagnosticsStatus; release_id: string; - // The `releases/` folder the files were read from, set only when it is not - // release_id: a Microcosm cut is released as its tag but stored under its - // line's folder (microcosm#823). + // The `releases/` folder the files were read from, set for a tagged + // Microcosm build (released as its tag but stored under its release's + // folder, microcosm#823) and for a build in its own folder (where it equals + // release_id); absent for a release folder. release_directory?: string; updated_at: string | null; schema_version: unknown; @@ -2448,6 +2464,12 @@ export interface ReleaseEntry { is_local_area: boolean; // A Microcosm cut's line folder; absent when the folder is release_id. release_directory?: string; + // A build in its own folder (release_id is `/`): its + // release and build as releases.json names them, and whether releases.json + // marks it withdrawn. Absent for release folders and tags. + release?: string; + build?: string; + withdrawn?: boolean; } // Trailing timestamp/date in a build id → a real timestamp for ordering. Ids @@ -2643,6 +2665,9 @@ export async function loadReleases( // A release whose calibrated folder is on main is listed from that folder, as // the publisher reads it. Roles are read from the release's own // release_manifest.json at its pinned commit, best-effort like the listing's. +// A build in its own folder (`/`) is listed only from +// releases.json (recordedReleaseInventory), so such entries stay readable by +// id but are never listed here. export async function loadPublishedCutReleases( revalidate: number, country: MicrocosmCountry, @@ -2657,6 +2682,7 @@ export async function loadPublishedCutReleases( (build) => build.kind === "release" && build.releaseId != null && + !isBuildFolderId(build.releaseId) && (releaseDirectoryOf(build) !== build.releaseId || !calibratedFolders.has(build.releaseId)), ); @@ -2722,6 +2748,118 @@ export function mergeReleaseInventory( ].sort((left, right) => releaseSortKey(right.date) - releaseSortKey(left.date)); } +// The picker's compact UTC form, YYYYMMDDTHHMMSSZ, of a recorded date-time; +// a value that is not one is kept as written. +function compactUtcTimestamp(value: string): string { + const instant = Date.parse(value); + if (!Number.isFinite(instant)) return value; + return new Date(instant).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); +} + +/** + * The country's releases.json at its configured revision, checked as the + * release writer checks it, or null when the repository has none (it then + * publishes through tags and pointer files) or the release is a local file. + * An unreadable or refused record throws: see releasesRecordFromResponse. + */ +export async function loadReleasesRecord( + revalidate: number, + country: MicrocosmCountry, +): Promise { + if (await loadLocalCalibrationRelease(country)) return null; + return releasesRecordFromResponse( + await hfFetch(hfResolveUrl(RELEASES_RECORD_PATH, country), revalidate), + ); +} + +/** + * The release inventory of a repository with releases.json: every build the + * record lists, named by its folder (`/`), dated by the + * record's `published_at` and classified by its release's role (the record's + * default release is the default dataset). A build is calibrated (selectable + * for comparison) once the dashboard manifest holds its tree. Withdrawn + * builds are listed with their flag, and the picker labels them. The + * dashboard's latest release is listed too while releases.json does not + * name it (see dashboardLatestRelease). + */ +export function recordedReleaseInventory( + record: ReleasesRecord, + country: MicrocosmCountry, + manifest: CalibrationTreeManifest, +): ReleaseEntry[] { + const published = new Set( + (manifest.countries[country]?.builds ?? []).flatMap((build) => + build.kind === "release" && build.releaseId ? [build.releaseId] : [] + ), + ); + const recorded = recordedBuilds(record).map((build): ReleaseEntry => ({ + release_id: build.id, + date: compactUtcTimestamp(build.publishedAt), + files: [], + has_calibration: published.has(build.id), + ...releaseRole({ dataset_role: build.role, is_default: build.inDefaultRelease }), + release: build.release, + build: build.build, + withdrawn: build.withdrawn, + })); + const recordedIds = new Set(recorded.map((entry) => entry.release_id)); + const latest = dashboardLatestRelease(manifest, country); + return [ + ...recorded, + ...(latest && !recordedIds.has(latest.release_id) ? [latest] : []), + ].sort((left, right) => releaseSortKey(right.date) - releaseSortKey(left.date)); +} + +/** + * The release inventory from releases.json (recordedReleaseInventory), or + * null when the repository has no releases.json, so the caller lists its + * release folders and tagged builds instead. releases.json is the only file + * read from the dataset repository. + */ +export async function loadRecordedReleases( + revalidate: number, + country: MicrocosmCountry, + manifest: CalibrationTreeManifest, +): Promise { + const record = await loadReleasesRecord(revalidate, country); + return record ? recordedReleaseInventory(record, country, manifest) : null; +} + +/** + * The release the dashboard manifest marks latest, as a picker entry. Under + * build folders it is releases.json's current build once reconciliation has + * run; until then it is the entry published before the switch (a tagged + * build or a release folder), which releases.json does not name. Keeping it + * listed keeps the page's selected release selectable, which the + * deployment's pre-promotion check requires. Read from the dashboard + * manifest only; it is classified as the default dataset, as the latest + * release is. + */ +function dashboardLatestRelease( + manifest: CalibrationTreeManifest, + country: MicrocosmCountry, +): ReleaseEntry | null { + const countryManifest = manifest.countries[country]; + const latest = countryManifest?.builds.find( + (build) => + build.buildArtifactId === countryManifest.latestReleaseBuildArtifactId && + build.kind === "release", + ); + if (!latest?.releaseId) return null; + return { + release_id: latest.releaseId, + date: latest.createdAt ? compactUtcTimestamp(latest.createdAt) : releaseDate(latest.releaseId), + files: [], + has_calibration: true, + dataset_role: null, + is_default: true, + is_local_area: false, + ...(latest.releaseDirectory && latest.releaseDirectory !== latest.releaseId + ? { release_directory: latest.releaseDirectory } + : {}), + }; +} + export async function loadPointerReleaseId( revalidate: number, country: MicrocosmCountry = "us", @@ -2796,7 +2934,12 @@ async function loadReleaseUncached( revalidate, ); const id = location.releaseId; - const directory = assertSafeReleaseId(location.releaseDirectory, "release directory"); + // A release folder or a build folder (`/`); interpolated + // into authenticated Hugging Face URLs. + const directory = location.releaseDirectory; + if (!isReleaseDirectory(directory) || directory === "latest") { + throw new InvalidReleaseIdError("Invalid release directory id"); + } const updatedAt = location.updatedAt; const prefix = `releases/${directory}`; const [diagnosticsArtifact, buildManifest, releaseManifest, demographics, publishedAt] = await Promise.all([ @@ -2831,11 +2974,25 @@ async function loadReleaseUncached( diagnosticsArtifact.sha256, location.hfCommitSha, ); - // A cut keeps its tag as the release id the picker, the latest pointer and - // this summary share, even if its diagnostics name the line instead. - return directory === id + return calibrationAsReleased(calibration, id, directory); +} + +/** + * A release build as the picker and the dashboard manifest name it. A tag + * keeps its tag, and a build folder keeps `/`, as the release + * id the picker, the latest release and this summary share, even when its + * diagnostics name its folder or its release instead; both record the folder + * they were read from, so their sources are cited at the pinned commit. A + * release folder keeps the id its diagnostics carry, as before. + */ +export function calibrationAsReleased( + calibration: Calibration, + releaseId: string, + releaseDirectory: string, +): Calibration { + return releaseDirectory === releaseId && !isBuildFolderId(releaseId) ? calibration - : { ...calibration, release_id: id, release_directory: directory }; + : { ...calibration, release_id: releaseId, release_directory: releaseDirectory }; } function targetDiagnosticsMetadata(rows: TargetRow[]): TargetDiagnosticsMetadata { diff --git a/frontend/packages/calibration-tree/src/publish-calibration-tree-build-folders.test.ts b/frontend/packages/calibration-tree/src/publish-calibration-tree-build-folders.test.ts new file mode 100644 index 00000000..aaa96abd --- /dev/null +++ b/frontend/packages/calibration-tree/src/publish-calibration-tree-build-folders.test.ts @@ -0,0 +1,722 @@ +import { afterEach, expect, spyOn, test } from "bun:test"; + +import { + migrateReleaseTimestamps, + parsePublisherOptions, + readRecordedCurrentBuild, + reconcileReleaseBuilds, + runPublisher, +} from "./publish-calibration-tree"; +import { + emptyCalibrationTreeManifest, + withCalibrationTreeManifestEntry, + type CalibrationTreeManifest, + type CalibrationTreeManifestEntry, +} from "./calibration-tree-manifest"; +import type { CalibrationTreeBundle } from "./calibration-tree-bundle"; +import type { MicrocosmCountry } from "./countries"; +import { missingReleasesRecord, missingRevision } from "./test-support/releases-record-responses"; + +// A dataset repository that publishes each build in its own folder, +// releases///, with releases.json as the only record of +// which build is current (microcosm-emitter#24). Microcosm's switch commit +// writes this layout; nothing does yet, so every value here is synthetic. +// The readers find the layout by finding releases.json, whatever the country. +const UK_REPO = "policyengine/populace-uk-private"; +const BE_REPO = "policyengine/populace-be-private"; +const API = `https://huggingface.co/api/datasets/${UK_REPO}`; +const RESOLVE = `https://huggingface.co/datasets/${UK_REPO}/resolve`; +const NATIONAL = "microcosm-uk-2024-25-national"; +const DENSE = "microcosm-uk-2024-25-dense"; +const NATIONAL_OLDER = "uk-frs-calibration-attempt-20261014T214443Z-d12ff9b3"; +const NATIONAL_CURRENT = "uk-frs-calibration-attempt-20261019T083323Z-6cba5d71"; +const DENSE_BUILD = "uk-local-candidate-f100-s42-20261019T000432Z-ee5c2dbe"; +// Listed, but its folder's release manifest names another build. +const MISLABELLED_BUILD = "uk-frs-calibration-attempt-20261001T000000Z-99999999"; +// Listed, but its folder holds no calibration diagnostics. +const UNCALIBRATED_BUILD = "uk-frs-calibration-attempt-20261002T000000Z-88888888"; +const MAIN_SHA = "5".repeat(40); + +const folder = (release: string, build: string) => `${release}/${build}`; + +// The commit that wrote each build folder. The migration copies builds that +// were published earlier, so a folder's commit date is not when its build +// was published; releases.json records that. +const FOLDER_COMMITS: Record = { + [folder(NATIONAL, NATIONAL_OLDER)]: { sha: "1".repeat(40), date: "2026-10-25T09:00:00.000Z" }, + [folder(NATIONAL, NATIONAL_CURRENT)]: { sha: "2".repeat(40), date: "2026-10-25T09:00:00.000Z" }, + [folder(DENSE, DENSE_BUILD)]: { sha: "3".repeat(40), date: "2026-10-25T09:05:00.000Z" }, + [folder(NATIONAL, MISLABELLED_BUILD)]: { sha: "4".repeat(40), date: "2026-10-25T09:00:00.000Z" }, + [folder(NATIONAL, UNCALIBRATED_BUILD)]: { sha: "6".repeat(40), date: "2026-10-25T09:00:00.000Z" }, +}; + +const SCHEMA_8_DIAGNOSTICS = { + schema_version: 8, + targets: [{ + name: "provider.target@2025", + target_name: "provider.target", + source: "Citation", + target: 100, + initial_estimate: 90, + final_estimate: 100, + hierarchy: { + provider: { id: "provider", label: "Provider label" }, + category: { id: "provider.category", label: "Category label", provider_id: "provider" }, + geography: { id: "K02000001", label: "United Kingdom", level: "country" }, + dimensions: [], + target: { id: "provider.target", label: "Target label" }, + }, + }], +}; + +function releasesRecord(): Record { + const build = (publishedAt: string) => ({ published_at: publishedAt, withdrawn: false }); + return { + schema_version: 1, + default: NATIONAL, + releases: { + [NATIONAL]: { + role: "national", + current: NATIONAL_CURRENT, + builds: { + [NATIONAL_OLDER]: build("2026-10-14T21:44:43+00:00"), + [NATIONAL_CURRENT]: build("2026-10-19T08:33:23+00:00"), + [MISLABELLED_BUILD]: build("2026-10-01T00:00:00+00:00"), + [UNCALIBRATED_BUILD]: build("2026-10-02T00:00:00+00:00"), + }, + }, + [DENSE]: { + role: "local_area", + current: null, + builds: { [DENSE_BUILD]: build("2026-10-19T07:53:18+00:00") }, + }, + }, + }; +} + +interface RepositoryOptions { + /** The repository's releases.json; null when it has none. */ + record?: Record | null; + /** Hugging Face's answer for releases.json, in place of the record. */ + recordResponse?: () => Response; + diagnosticsFor?: (folderId: string) => Record; + /** A build folder whose listing Hugging Face answers with a server error. */ + unreadableFolder?: string; + /** + * A build folder whose listing never answers: the request settles only + * when its abort signal fires. Records the timeout the request asked for + * (see withShortTimeouts). + */ + stalledFolder?: { folderId: string; requestedTimeouts: Array }; + /** The dataset repository; the UK's by default. */ + repo?: string; + /** A build folder whose listing answers its first request, then 503. */ + folderReadableOnce?: string; +} + +function buildFolderRepository(requested: string[], options: RepositoryOptions = {}) { + const record = options.record === undefined ? releasesRecord() : options.record; + const diagnosticsFor = options.diagnosticsFor ?? (() => SCHEMA_8_DIAGNOSTICS); + const repo = options.repo ?? UK_REPO; + const api = `https://huggingface.co/api/datasets/${repo}`; + const resolve = `https://huggingface.co/datasets/${repo}/resolve`; + let readableOnceListings = 0; + return (async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input); + requested.push(url); + if (url === `${api}/revision/main`) return Response.json({ sha: MAIN_SHA }); + if (url === `${resolve}/${MAIN_SHA}/releases.json`) { + if (options.recordResponse) return options.recordResponse(); + return record == null ? missingReleasesRecord() : Response.json(record); + } + for (const [folderId, commit] of Object.entries(FOLDER_COMMITS)) { + const [release, build] = folderId.split("/"); + const prefix = `releases/${folderId}`; + if (url === `${api}/tree/${MAIN_SHA}/releases/${release}/${build}?recursive=false&expand=true`) { + if (folderId === options.unreadableFolder) return new Response(null, { status: 503 }); + if (folderId === options.folderReadableOnce && readableOnceListings++ > 0) { + return new Response(null, { status: 503 }); + } + if (folderId === options.stalledFolder?.folderId) { + const signal = init?.signal; + options.stalledFolder.requestedTimeouts.push( + (signal as TimedSignal | undefined)?.requestedTimeout ?? null, + ); + if (!signal) throw new Error("The build folder listing was requested without a timeout."); + return new Promise((_, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + } + const names = build === UNCALIBRATED_BUILD + ? ["release_manifest.json", "microcosm_uk_2024_25.h5"] + : ["release_manifest.json", "calibration_diagnostics.json", "microcosm_uk_2024_25.h5"]; + return Response.json(names.map((name) => ({ + type: "file", + path: `${prefix}/${name}`, + lastCommit: { id: commit.sha, date: commit.date }, + }))); + } + if (url === `${resolve}/${commit.sha}/${prefix}/release_manifest.json`) { + return Response.json({ + release, + build: build === MISLABELLED_BUILD ? NATIONAL_CURRENT : build, + artifacts: {}, + }); + } + if (url === `${resolve}/${commit.sha}/${prefix}/calibration_diagnostics.json`) { + return Response.json(diagnosticsFor(folderId)); + } + if ( + url === `${resolve}/${commit.sha}/${prefix}/build_manifest.json` || + url === `${resolve}/${commit.sha}/${prefix}/demographics.json` + ) { + return new Response(null, { status: 404 }); + } + } + throw new Error(`Unexpected URL ${url}`); + }) as typeof fetch; +} + +// A timeout signal that remembers the duration the code asked for. +type TimedSignal = AbortSignal & { requestedTimeout?: number }; + +// Every AbortSignal.timeout(...) fires after a few milliseconds instead, so a +// stalled request settles at once; each signal records the duration asked for. +async function withShortTimeouts(run: () => Promise): Promise { + const originalTimeout = AbortSignal.timeout.bind(AbortSignal); + const timeouts = spyOn(AbortSignal, "timeout").mockImplementation((milliseconds: number) => { + const signal: TimedSignal = originalTimeout(5); + signal.requestedTimeout = milliseconds; + return signal; + }); + try { + return await run(); + } finally { + timeouts.mockRestore(); + } +} + +function memoryStore(initial: CalibrationTreeManifest, country: MicrocosmCountry = "uk") { + let manifest = initial; + const uploads: CalibrationTreeBundle[] = []; + const writes: Array<{ entry: CalibrationTreeManifestEntry; makeLatest?: boolean }> = []; + return { + uploads, + writes, + current: () => manifest, + readManifest: async () => manifest, + listBlobs: async () => new Map(), + audit: async () => ({ complete: true, repairable: true, reasons: [], index: null }), + updateManifest: async (entry: CalibrationTreeManifestEntry, makeLatest?: boolean) => { + writes.push({ entry, makeLatest }); + manifest = withCalibrationTreeManifestEntry(manifest, country, entry, makeLatest); + return manifest; + }, + uploadBundle: async (bundle: CalibrationTreeBundle) => { + uploads.push(bundle); + const stored = (file: CalibrationTreeBundle["files"][number]) => ({ + pathname: file.path, + sha256: file.sha256, + bytes: file.rawBytes, + created: true, + }); + return { + files: bundle.files.map(stored), + index: stored(bundle.files.find((file) => file.part === "index")!), + }; + }, + }; +} + +// Entries the publisher wrote before the build folders: a release folder's +// build and a tagged build of the national release, read from its folder. +const TAGGED_BUILD = `${NATIONAL}-20261019T083323Z-6cba5d71`; +function earlierEntries(): CalibrationTreeManifestEntry[] { + const entry = ( + digit: string, + releaseId: string, + releaseDirectory?: string, + ): CalibrationTreeManifestEntry => ({ + buildArtifactId: digit.repeat(64), + kind: "release", + sourceId: releaseId, + label: releaseId, + releaseId, + ...(releaseDirectory ? { releaseDirectory } : {}), + stagingRunId: null, + hfRepo: UK_REPO, + hfCommitSha: digit.repeat(40), + treeSchemaVersion: 6, + indexSha256: "e".repeat(64), + indexBytes: 10, + createdAt: "2026-10-19T10:21:22.000Z", + updatedAt: "2026-10-19T10:21:22.000Z", + }); + return [entry("a", "populace-uk-2023-test-20260619T023711Z"), entry("b", TAGGED_BUILD, NATIONAL)]; +} + +function manifestWithEarlierEntries(): CalibrationTreeManifest { + const [june, tagged] = earlierEntries(); + return withCalibrationTreeManifestEntry( + withCalibrationTreeManifestEntry(emptyCalibrationTreeManifest(), "uk", june), + "uk", + tagged, + true, + ); +} + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +test("release reconciliation publishes every build releases.json lists, from its own folder at the commit that wrote it", async () => { + const store = memoryStore(emptyCalibrationTreeManifest()); + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested); + + const report = await reconcileReleaseBuilds("uk", "blob-token", false, store); + + expect(Object.fromEntries(report.outcomes.map((outcome) => [outcome.sourceId, outcome.status]))) + .toEqual({ + [folder(DENSE, DENSE_BUILD)]: "published", + [folder(NATIONAL, NATIONAL_OLDER)]: "published", + [folder(NATIONAL, NATIONAL_CURRENT)]: "published", + [folder(NATIONAL, MISLABELLED_BUILD)]: "ineligible", + [folder(NATIONAL, UNCALIBRATED_BUILD)]: "ineligible", + }); + const current = store.current().countries.uk!.builds + .find((build) => build.releaseId === folder(NATIONAL, NATIONAL_CURRENT))!; + // The build's folder is its release id; there is no separate directory. + expect(current).toMatchObject({ + sourceId: folder(NATIONAL, NATIONAL_CURRENT), + label: folder(NATIONAL, NATIONAL_CURRENT), + hfCommitSha: FOLDER_COMMITS[folder(NATIONAL, NATIONAL_CURRENT)].sha, + }); + expect(current.releaseDirectory).toBeUndefined(); + expect(requested).toContain( + `${RESOLVE}/${FOLDER_COMMITS[folder(DENSE, DENSE_BUILD)].sha}/releases/${DENSE}/${DENSE_BUILD}/calibration_diagnostics.json`, + ); +}); + +test("a build whose folder cannot be read is reported as failed, and the other listed builds are still reconciled", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + globalThis.fetch = buildFolderRepository([], { unreadableFolder: folder(NATIONAL, NATIONAL_OLDER) }); + + const reconciliation = reconcileReleaseBuilds("uk", "blob-token", false, store); + await expect(reconciliation).resolves.toBeDefined(); + const report = await reconciliation; + + const failed = report.outcomes.find((outcome) => outcome.sourceId === folder(NATIONAL, NATIONAL_OLDER)); + expect(failed).toMatchObject({ status: "failed", buildArtifactId: null }); + expect(failed?.reason).toContain("503"); + expect(Object.fromEntries(report.outcomes.map((outcome) => [outcome.sourceId, outcome.status]))) + .toMatchObject({ + [folder(DENSE, DENSE_BUILD)]: "published", + [folder(NATIONAL, NATIONAL_CURRENT)]: "published", + }); + // The failed build is not the current one, so the latest release still moves. + expect(report.latestReleaseFailure).toBeUndefined(); + const manifest = store.current().countries.uk!; + expect(manifest.latestReleaseBuildArtifactId).toBe( + manifest.builds.find((build) => build.releaseId === folder(NATIONAL, NATIONAL_CURRENT))!.buildArtifactId, + ); +}); + +test("a build folder listing that never answers times out after 30 seconds and fails only its own build", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + const requestedTimeouts: Array = []; + globalThis.fetch = buildFolderRepository([], { + stalledFolder: { folderId: folder(NATIONAL, NATIONAL_OLDER), requestedTimeouts }, + }); + + const report = await withShortTimeouts(() => reconcileReleaseBuilds("uk", "blob-token", false, store)); + + expect(requestedTimeouts).toEqual([30_000]); + const stalled = report.outcomes.find((outcome) => outcome.sourceId === folder(NATIONAL, NATIONAL_OLDER)); + expect(stalled?.status).toBe("failed"); + expect(stalled?.reason ?? "").toMatch(/timed out/i); + expect(Object.fromEntries(report.outcomes.map((outcome) => [outcome.sourceId, outcome.status]))) + .toMatchObject({ + [folder(DENSE, DENSE_BUILD)]: "published", + [folder(NATIONAL, NATIONAL_CURRENT)]: "published", + }); + expect(report.latestReleaseFailure).toBeUndefined(); +}); + +test("a build is dated by the publication time releases.json records, not by the commit that wrote its folder", async () => { + const store = memoryStore(emptyCalibrationTreeManifest()); + globalThis.fetch = buildFolderRepository([]); + + await reconcileReleaseBuilds("uk", "blob-token", false, store); + + const older = store.current().countries.uk!.builds + .find((build) => build.releaseId === folder(NATIONAL, NATIONAL_OLDER))!; + expect(older.createdAt).toBe("2026-10-14T21:44:43.000Z"); + expect(older.updatedAt).toBe("2026-10-14T21:44:43.000Z"); +}); + +test("the latest release becomes the current build of the record's default release", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + globalThis.fetch = buildFolderRepository([]); + + await reconcileReleaseBuilds("uk", "blob-token", false, store); + + const manifest = store.current().countries.uk!; + const current = manifest.builds.find( + (build) => build.releaseId === folder(NATIONAL, NATIONAL_CURRENT), + )!; + expect(manifest.latestReleaseBuildArtifactId).toBe(current.buildArtifactId); +}); + +test("reconciliation reads nothing but releases.json and the build folders it lists", async () => { + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested); + + await reconcileReleaseBuilds( + "uk", + "blob-token", + false, + memoryStore(emptyCalibrationTreeManifest()) + ); + + // No tag list, no pointer file, no listing of releases/ itself. + expect(requested.some((url) => url === `${API}/refs`)).toBe(false); + expect(requested.some((url) => /\/latest[^/]*\.json$/.test(url))).toBe(false); + expect(requested.some((url) => url.includes("/tree/main/releases"))).toBe(false); + for (const url of requested) { + expect( + url === `${API}/revision/main` || + url === `${RESOLVE}/${MAIN_SHA}/releases.json` || + /\/releases\/[^/]+\/[^/?]+(\/[^/]+)?(\?recursive=false&expand=true)?$/.test(url) || + /\/commits\//.test(url), + url, + ).toBe(true); + } +}); + +test("entries published before the build folders stay in the dashboard manifest unchanged", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + globalThis.fetch = buildFolderRepository([]); + + const report = await reconcileReleaseBuilds("uk", "blob-token", false, store); + + const builds = store.current().countries.uk!.builds; + for (const earlier of earlierEntries()) { + expect(builds.find((build) => build.buildArtifactId === earlier.buildArtifactId)).toEqual(earlier); + expect(report.outcomes.some((outcome) => outcome.sourceId === earlier.releaseId)).toBe(false); + } +}); + +test("a second reconciliation finds every listed build complete without listing their folders again", async () => { + const store = memoryStore(emptyCalibrationTreeManifest()); + globalThis.fetch = buildFolderRepository([]); + await reconcileReleaseBuilds("uk", "blob-token", false, store); + + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested); + const again = await reconcileReleaseBuilds("uk", "blob-token", false, store); + + expect(again.outcomes.filter((outcome) => outcome.status !== "ineligible") + .every((outcome) => outcome.status === "complete")).toBe(true); + expect(store.uploads).toHaveLength(3); + for (const published of [NATIONAL_OLDER, NATIONAL_CURRENT]) { + expect(requested.some((url) => url.includes(`/releases/${NATIONAL}/${published}?`))).toBe(false); + } +}); + +test("a listed build is not published when its folder has no calibration diagnostics or its release manifest names another build", async () => { + globalThis.fetch = buildFolderRepository([]); + + const report = await reconcileReleaseBuilds( + "uk", + "blob-token", + false, + memoryStore(emptyCalibrationTreeManifest()) + ); + + const reason = (build: string) => + report.outcomes.find((outcome) => outcome.sourceId === folder(NATIONAL, build))?.reason ?? ""; + expect(reason(UNCALIBRATED_BUILD)).toContain("calibration diagnostics"); + expect(reason(MISLABELLED_BUILD)).toContain( + `does not name release ${NATIONAL} and build ${MISLABELLED_BUILD}`, + ); +}); + +test("a build's comparison metadata names the build, not the release its diagnostics name", async () => { + const store = memoryStore(emptyCalibrationTreeManifest()); + globalThis.fetch = buildFolderRepository([], { + diagnosticsFor: (folderId) => ({ ...SCHEMA_8_DIAGNOSTICS, release_id: folderId.split("/")[0] }), + }); + + await reconcileReleaseBuilds("uk", "blob-token", false, store); + + expect(store.uploads).toHaveLength(3); + for (const bundle of store.uploads) { + expect(bundle.index.build.releaseId).not.toBeNull(); + expect(bundle.index.targetComparison.releaseId).toBe(bundle.index.build.releaseId ?? ""); + } +}); + +test("reconciliation refuses a releases.json the release writer would refuse, before publishing anything", async () => { + const record = releasesRecord(); + const national = (record.releases as Record>)[NATIONAL]; + (national.builds as Record>)[NATIONAL_CURRENT].withdrawn = true; + const store = memoryStore(emptyCalibrationTreeManifest()); + globalThis.fetch = buildFolderRepository([], { record }); + + await expect(reconcileReleaseBuilds("uk", "blob-token", false, store)) + .rejects.toThrow("is withdrawn"); + expect(store.uploads).toHaveLength(0); + expect(store.writes).toHaveLength(0); +}); + +// The writer's ReleasesRecord.parse refuses a record over MAX_RECORD_BYTES +// (4 MiB), the size check_change keeps every record within. +test("reconciliation refuses a releases.json larger than the release writer accepts, before publishing anything", async () => { + // Trailing whitespace keeps the record otherwise valid. + const oversized = JSON.stringify(releasesRecord()) + " ".repeat(4 * 1024 * 1024); + const repository = buildFolderRepository([]); + const store = memoryStore(emptyCalibrationTreeManifest()); + globalThis.fetch = (async (input: string | URL | Request) => + String(input) === `${RESOLVE}/${MAIN_SHA}/releases.json` + ? new Response(oversized) + : repository(input)) as typeof fetch; + + await expect(reconcileReleaseBuilds("uk", "blob-token", false, store)) + .rejects.toThrow("releases.json is larger than 4194304 bytes."); + expect(store.uploads).toHaveLength(0); + expect(store.writes).toHaveLength(0); +}); + +test("without a current build of the default release, reconciliation publishes the listed builds and fails without moving the latest release", async () => { + const record = releasesRecord(); + (record.releases as Record>)[NATIONAL].current = null; + const store = memoryStore(manifestWithEarlierEntries()); + const latestBefore = store.current().countries.uk!.latestReleaseBuildArtifactId; + globalThis.fetch = buildFolderRepository([], { record }); + + // Reconciliation reports why the latest release was not selected, and the + // publisher then exits with an error (reconciliationFailureMessage). + const report = await reconcileReleaseBuilds("uk", "blob-token", false, store); + expect(report.latestReleaseFailure).toContain("names no current build of its default release"); + expect(store.uploads).toHaveLength(3); + expect(store.current().countries.uk!.latestReleaseBuildArtifactId).toBe(latestBefore); +}); + +test("the current build is read from releases.json at the given commit and pinned to the commit that wrote its folder", async () => { + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested); + + await expect(readRecordedCurrentBuild("uk", MAIN_SHA)).resolves.toEqual({ + releaseId: folder(NATIONAL, NATIONAL_CURRENT), + releaseDirectory: folder(NATIONAL, NATIONAL_CURRENT), + hfCommitSha: FOLDER_COMMITS[folder(NATIONAL, NATIONAL_CURRENT)].sha, + publishedAt: "2026-10-19T08:33:23.000Z", + }); + expect(requested).not.toContain(`${API}/revision/main`); +}); + +test("the publisher takes a build folder as the release to publish", () => { + expect(parsePublisherOptions([ + "--country", + "uk", + "--release", + folder(NATIONAL, NATIONAL_CURRENT), + ])).toEqual({ + country: "uk", + mode: "release", + releaseId: folder(NATIONAL, NATIONAL_CURRENT), + }); + for (const value of [`${NATIONAL}/${NATIONAL_CURRENT}/extra`, `${NATIONAL}/..`, `../${NATIONAL}`]) { + expect(() => parsePublisherOptions(["--release", value]), value).toThrow( + "valid immutable release id", + ); + } +}); + +async function withBlobToken(run: () => Promise): Promise { + const priorBlobToken = process.env.BLOB_READ_WRITE_TOKEN; + process.env.BLOB_READ_WRITE_TOKEN = "blob-token"; + try { + return await run(); + } finally { + if (priorBlobToken == null) delete process.env.BLOB_READ_WRITE_TOKEN; + else process.env.BLOB_READ_WRITE_TOKEN = priorBlobToken; + } +} + +// The single-build modes print their result; the tests read the store. +async function quietly(run: () => Promise): Promise { + const printed = spyOn(console, "log").mockImplementation(() => {}); + try { + return await run(); + } finally { + printed.mockRestore(); + } +} + +test("--latest publishes the current build of the default release and makes it the latest", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + globalThis.fetch = buildFolderRepository([]); + + await withBlobToken(() => quietly(() => runPublisher({ country: "uk", mode: "latest" }, { store }))); + + const current = folder(NATIONAL, NATIONAL_CURRENT); + expect(store.writes.map((write) => [write.entry.releaseId, write.makeLatest ?? false])) + .toEqual([[current, false], [current, true]]); + expect(store.writes[0].entry).toMatchObject({ + hfCommitSha: FOLDER_COMMITS[current].sha, + createdAt: "2026-10-19T08:33:23.000Z", + }); +}); + +test("--release of another build publishes it without making it the latest or reading the current build's folder", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + const latestBefore = store.current().countries.uk!.latestReleaseBuildArtifactId; + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested); + + await withBlobToken(() => quietly(() => + runPublisher({ country: "uk", mode: "release", releaseId: folder(NATIONAL, NATIONAL_OLDER) }, { store }) + )); + + expect(store.writes.map((write) => [write.entry.releaseId, write.makeLatest ?? false])) + .toEqual([[folder(NATIONAL, NATIONAL_OLDER), false]]); + expect(store.current().countries.uk!.latestReleaseBuildArtifactId).toBe(latestBefore); + // The promotion check compares names from releases.json: the current + // build's folder is never listed for it. + expect(requested.some((url) => url.includes(`/releases/${NATIONAL}/${NATIONAL_CURRENT}`))).toBe(false); +}); + +test("--release of the current build still succeeds when its folder cannot be read again for the promotion check", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + const latestBefore = store.current().countries.uk!.latestReleaseBuildArtifactId; + globalThis.fetch = buildFolderRepository([], { folderReadableOnce: folder(NATIONAL, NATIONAL_CURRENT) }); + const warned = spyOn(console, "warn").mockImplementation(() => {}); + + try { + const publication = withBlobToken(() => quietly(() => + runPublisher({ country: "uk", mode: "release", releaseId: folder(NATIONAL, NATIONAL_CURRENT) }, { store }) + )); + await expect(publication).resolves.toBeUndefined(); + // The build is registered; reconciliation moves the latest release later. + expect(store.writes.map((write) => [write.entry.releaseId, write.makeLatest ?? false])) + .toEqual([[folder(NATIONAL, NATIONAL_CURRENT), false]]); + expect(store.current().countries.uk!.latestReleaseBuildArtifactId).toBe(latestBefore); + expect(warned.mock.calls.map((call) => call.map(String).join(" ")).join("\n")) + .toContain("latest release was not moved"); + } finally { + warned.mockRestore(); + } +}); + +test("when the current build's folder cannot be read, the latest-release failure names the read failure", async () => { + const store = memoryStore(manifestWithEarlierEntries()); + const latestBefore = store.current().countries.uk!.latestReleaseBuildArtifactId; + globalThis.fetch = buildFolderRepository([], { unreadableFolder: folder(NATIONAL, NATIONAL_CURRENT) }); + + const report = await reconcileReleaseBuilds("uk", "blob-token", false, store); + + expect(report.outcomes.find((outcome) => outcome.sourceId === folder(NATIONAL, NATIONAL_CURRENT))?.status) + .toBe("failed"); + expect(report.latestReleaseFailure ?? "").toContain(`Latest release ${folder(NATIONAL, NATIONAL_CURRENT)}`); + expect(report.latestReleaseFailure ?? "").toContain("Hugging Face build folder lookup failed with 503."); + expect(store.current().countries.uk!.latestReleaseBuildArtifactId).toBe(latestBefore); +}); + +test("when the current build is ineligible, the latest-release failure says why", async () => { + const record = releasesRecord(); + (record.releases as Record>)[NATIONAL].current = UNCALIBRATED_BUILD; + const store = memoryStore(manifestWithEarlierEntries()); + globalThis.fetch = buildFolderRepository([], { record }); + + const report = await reconcileReleaseBuilds("uk", "blob-token", false, store); + + expect(report.latestReleaseFailure ?? "").toContain( + `${folder(NATIONAL, UNCALIBRATED_BUILD)} cannot be published: releases/${folder(NATIONAL, UNCALIBRATED_BUILD)}/ has no calibration diagnostics.`, + ); + expect(report.latestReleaseFailure ?? "").not.toContain("@ is not completely published"); +}); + +test("a single-build publication refuses a build releases.json does not list, before reading any build file", async () => { + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested); + + await withBlobToken(async () => { + await expect(runPublisher( + { country: "uk", mode: "release", releaseId: folder(NATIONAL, "uk-frs-calibration-attempt-unlisted") }, + )).rejects.toThrow("does not list build"); + }); + expect(requested.some((url) => url.includes("/tree/"))).toBe(false); +}); + +test("a single-build publication takes a build folder only from a repository with releases.json, and a tag only from one without", async () => { + const withoutRecord: string[] = []; + const withRecord: string[] = []; + + await withBlobToken(async () => { + globalThis.fetch = buildFolderRepository(withoutRecord, { record: null }); + await expect(runPublisher( + { country: "uk", mode: "release", releaseId: folder(NATIONAL, NATIONAL_CURRENT) }, + )).rejects.toThrow("has no releases.json"); + globalThis.fetch = buildFolderRepository(withRecord); + await expect(runPublisher( + { country: "uk", mode: "release", releaseId: TAGGED_BUILD }, + )).rejects.toThrow("has releases.json; --release takes /"); + }); + // Each refusal follows the one read that tells the layouts apart. + for (const requested of [withoutRecord, withRecord]) { + expect(requested).toEqual([`${API}/revision/main`, `${RESOLVE}/${MAIN_SHA}/releases.json`]); + } +}); + +test("a repository with releases.json is reconciled from it, whichever country it belongs to", async () => { + const store = memoryStore(emptyCalibrationTreeManifest(), "be"); + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested, { repo: BE_REPO }); + + const reconciliation = reconcileReleaseBuilds("be", "blob-token", false, store); + await expect(reconciliation).resolves.toBeDefined(); + const report = await reconciliation; + + expect(Object.fromEntries(report.outcomes.map((outcome) => [outcome.sourceId, outcome.status]))) + .toMatchObject({ + [folder(NATIONAL, NATIONAL_CURRENT)]: "published", + [folder(DENSE, DENSE_BUILD)]: "published", + }); + const manifest = store.current().countries.be!; + expect(manifest.latestReleaseBuildArtifactId).toBe( + manifest.builds.find((build) => build.releaseId === folder(NATIONAL, NATIONAL_CURRENT))!.buildArtifactId, + ); + expect(requested.some((url) => url.endsWith("/refs"))).toBe(false); +}); + +test("a 404 that says the revision is missing is an error, not a repository without releases.json", async () => { + const requested: string[] = []; + globalThis.fetch = buildFolderRepository(requested, { repo: BE_REPO, recordResponse: missingRevision }); + + await expect(reconcileReleaseBuilds("be", "blob-token", false, memoryStore(emptyCalibrationTreeManifest(), "be"))) + .rejects.toThrow("404"); + // Neither tags nor pointer files are read in its place. + expect(requested.some((url) => url.endsWith("/refs"))).toBe(false); + expect(requested.some((url) => /\/latest[^/]*\.json$/.test(url))).toBe(false); +}); + +test("the timestamp migration leaves build-folder entries dated as releases.json dated them", async () => { + const store = memoryStore(emptyCalibrationTreeManifest()); + globalThis.fetch = buildFolderRepository([]); + await reconcileReleaseBuilds("uk", "blob-token", false, store); + const writesBefore = store.writes.length; + + const requested: string[] = []; + globalThis.fetch = (async (input: string | URL | Request): Promise => { + requested.push(String(input)); + throw new Error(`Unexpected URL ${String(input)}`); + }) as typeof fetch; + const report = await migrateReleaseTimestamps("uk", "blob-token", false, store); + + expect(report.outcomes).toEqual([]); + expect(requested).toEqual([]); + expect(store.writes).toHaveLength(writesBefore); +}); diff --git a/frontend/packages/calibration-tree/src/publish-calibration-tree-golden.test.ts b/frontend/packages/calibration-tree/src/publish-calibration-tree-golden.test.ts index ee44dd3e..5eafa829 100644 --- a/frontend/packages/calibration-tree/src/publish-calibration-tree-golden.test.ts +++ b/frontend/packages/calibration-tree/src/publish-calibration-tree-golden.test.ts @@ -19,6 +19,7 @@ import { type CalibrationTreeGoldenRecord, type GoldenReleaseInput, } from "./test-support/calibration-tree-golden-cases"; +import { missingReleasesRecord } from "./test-support/releases-record-responses"; import { reconcileReleaseBuilds, reconcileStagingBuilds, @@ -27,6 +28,9 @@ import { type ReconciliationReport, } from "@policyengine/calibration-tree/publish-calibration-tree"; +// The recorded releases are release folders: the repositories here have no +// releases.json, so they are read from their tags and pointer files. +// // A repair rebuilds a published release whose index went missing and refuses // any rebuilt index whose digest differs from the manifest entry. Seeding the // entry with the recorded build id and index digest therefore proves, through @@ -79,6 +83,7 @@ function huggingFaceReleaseRepository(release: GoldenReleaseInput): typeof fetch }), ], [`${api}/revision/main`, () => Response.json({ sha: MAIN_REVISION_SHA })], + [resolveUrl(MAIN_REVISION_SHA, "releases.json"), missingReleasesRecord], [`${api}/revision/${release.releaseId}`, () => Response.json({ sha: release.hfCommitSha })], ]); const pointerPath = countryPointerPath(release.country); @@ -170,6 +175,9 @@ function storeMissingIndex( updateManifest: async () => { throw new Error("A dry run must not write the manifest."); }, + uploadBundle: async () => { + throw new Error("A dry run must not upload a bundle."); + }, }; } @@ -281,6 +289,9 @@ function stagingRepositoryWithRefusedRepair(): { updateManifest: async () => { throw new Error("A dry run must not write the manifest."); }, + uploadBundle: async () => { + throw new Error("A dry run must not upload a bundle."); + }, }; return { revisionSha, store, staleEntry }; } diff --git a/frontend/packages/calibration-tree/src/publish-calibration-tree.test.ts b/frontend/packages/calibration-tree/src/publish-calibration-tree.test.ts index 7b99744f..6fc68466 100644 --- a/frontend/packages/calibration-tree/src/publish-calibration-tree.test.ts +++ b/frontend/packages/calibration-tree/src/publish-calibration-tree.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { CalibrationTreeArtifactSizeError, @@ -19,6 +19,7 @@ import { type CalibrationTreeManifestEntry, } from "./calibration-tree-manifest"; import type { CalibrationTreeBundle } from "./calibration-tree-bundle"; +import { missingReleasesRecord } from "./test-support/releases-record-responses"; import { schema9Diagnostics } from "./test-support/schema-9-diagnostics"; const originalFetch = globalThis.fetch; @@ -442,6 +443,8 @@ test("release reconciliation leaves a complete entry's metadata to the migration ]); } if (url.includes(`/api/datasets/${UK_REPO}/revision/main`)) return Response.json({ sha: UK_SHA }); + // The repository has no releases.json, so its tags and pointer files are read. + if (url.endsWith(`/resolve/${UK_SHA}/releases.json`)) return missingReleasesRecord(); if (url.includes(`/api/datasets/${UK_REPO}/revision/${UK_RELEASE}`)) { return new Response(null, { status: 404 }); } @@ -471,8 +474,10 @@ test("release reconciliation leaves a complete entry's metadata to the migration } }); -// A Microcosm line (microcosm#823): one constant folder, one immutable tag per -// cut. All values are synthetic. +// A Microcosm release (microcosm#823): one constant folder, one immutable tag +// per build. All values are synthetic. The repository has no releases.json, +// so it is read from its tags and pointer files, as the UK repository is +// until Microcosm's switch commit. const NATIONAL_LINE = "microcosm-uk-2024-25-national"; const DENSE_LINE = "microcosm-uk-2024-25-dense"; const NATIONAL_CUT = `${NATIONAL_LINE}-20261019T083323Z-0a1b2c3d`; @@ -647,6 +652,8 @@ function lineRepositoryFetch( return Response.json([{ id: commit, date: COMMIT_DATES[commit] }]); } if (url === `${api}/revision/main`) return Response.json({ sha: MAIN_SHA }); + // The repository has no releases.json, so its tags and pointer files are read. + if (url === `${resolve}/${MAIN_SHA}/releases.json`) return missingReleasesRecord(); if (url === `${resolve}/${MAIN_SHA}/latest-national.json`) { return Response.json({ schema_version: 1, @@ -769,6 +776,78 @@ const REFUSED_SCHEMA_8_DIAGNOSTICS = { const REFUSED_SCHEMA_8_ERROR = "Schema 8 category provider.category references inconsistent providers: provider and other."; +test("a repository without releases.json is reconciled from its tags and pointer files", async () => { + const requested: string[] = []; + globalThis.fetch = lineRepositoryFetch(requested); + const store = lineStoreWithJuneLatest(); + try { + const reconciliation = reconcileReleaseBuilds("uk", "blob-token", false, store); + await expect(reconciliation).resolves.toBeDefined(); + const report = await reconciliation; + expect(report.outcomes.find((outcome) => outcome.sourceId === NATIONAL_CUT)?.status).toBe("published"); + const api = `https://huggingface.co/api/datasets/${UK_REPO}`; + const resolve = `https://huggingface.co/datasets/${UK_REPO}/resolve`; + // releases.json is looked for once, at main's head, and then never again. + expect(requested.filter((url) => url.endsWith("/releases.json"))) + .toEqual([`${resolve}/${MAIN_SHA}/releases.json`]); + expect(requested).toContain(`${api}/refs`); + expect(requested).toContain(`${resolve}/${MAIN_SHA}/latest-national.json`); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("a repository without releases.json has main's head resolved once per reconciliation, and its pointer file read at that commit", async () => { + const requested: string[] = []; + globalThis.fetch = lineRepositoryFetch(requested); + try { + await reconcileReleaseBuilds("uk", "blob-token", false, lineStoreWithJuneLatest()); + const api = `https://huggingface.co/api/datasets/${UK_REPO}`; + const resolve = `https://huggingface.co/datasets/${UK_REPO}/resolve`; + expect(requested.filter((url) => url === `${api}/revision/main`)).toHaveLength(1); + expect(requested.filter((url) => url.endsWith("/latest-national.json"))) + .toEqual([`${resolve}/${MAIN_SHA}/latest-national.json`]); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("--latest without releases.json reads the pointer file at the commit where releases.json was looked for", async () => { + const api = `https://huggingface.co/api/datasets/${UK_REPO}`; + const resolve = `https://huggingface.co/datasets/${UK_REPO}/resolve`; + const laterSha = "9".repeat(40); + const requested: string[] = []; + const repository = lineRepositoryFetch([]); + let headLookups = 0; + // main moves on after the first lookup; the later commit has the same files. + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input); + requested.push(url); + if (url === `${api}/revision/main`) { + headLookups += 1; + return Response.json({ sha: headLookups === 1 ? MAIN_SHA : laterSha }); + } + return repository(url.replace(`/resolve/${laterSha}/`, `/resolve/${MAIN_SHA}/`)); + }) as typeof fetch; + const store = lineStoreWithJuneLatest(); + const priorBlobToken = process.env.BLOB_READ_WRITE_TOKEN; + process.env.BLOB_READ_WRITE_TOKEN = "blob-token"; + const printed = spyOn(console, "log").mockImplementation(() => {}); + try { + await runPublisher({ country: "uk", mode: "latest" }, { store }); + const firstRecordRead = requested.find((url) => url.endsWith("/releases.json")); + const firstPointerRead = requested.find((url) => url.endsWith("/latest-national.json")); + expect(firstRecordRead).toBe(`${resolve}/${MAIN_SHA}/releases.json`); + expect(firstPointerRead).toBe(`${resolve}/${MAIN_SHA}/latest-national.json`); + expect(store.writes.map((write) => write.entry.releaseId)).toContain(NATIONAL_CUT); + } finally { + printed.mockRestore(); + globalThis.fetch = originalFetch; + if (priorBlobToken == null) delete process.env.BLOB_READ_WRITE_TOKEN; + else process.env.BLOB_READ_WRITE_TOKEN = priorBlobToken; + } +}); + function lineStoreWithJuneLatest( options: { incompleteAfterUpload?: ReadonlySet } = {}, ) { diff --git a/frontend/packages/calibration-tree/src/publish-calibration-tree.ts b/frontend/packages/calibration-tree/src/publish-calibration-tree.ts index 54047541..6b56af2e 100644 --- a/frontend/packages/calibration-tree/src/publish-calibration-tree.ts +++ b/frontend/packages/calibration-tree/src/publish-calibration-tree.ts @@ -25,6 +25,7 @@ import { createHash } from "node:crypto"; import { CalibrationReleaseNotFoundError, isReleaseId, + resolveHfBuildFolderSha, resolveHfCommitPublishedAt, resolveHfReleaseDirectorySha, resolveHfRepositoryCommitPublishedAt, @@ -38,6 +39,18 @@ import { type MicrocosmCountry, } from "./countries"; import { parseReleaseCutTag } from "./release-cut"; +import { + RELEASE_MANIFEST_NAME, + RELEASES_RECORD_PATH, + currentDefaultBuild, + isBuildFolderId, + isReleaseDirectory, + recordedBuilds, + releaseManifestNamesBuild, + releasesRecordFromResponse, + type RecordedBuild, + type ReleasesRecord, +} from "./release-record"; import { buildCalibration, loadReleases, @@ -132,6 +145,17 @@ function releaseId(value: string | undefined): string { return result; } +// A release id (a release folder or a tag) or a build folder, +// `/`. Both are interpolated into authenticated Hugging Face +// URLs. +function releaseOrBuildFolderId(value: string | undefined): string { + const result = value?.trim() ?? ""; + if (!isReleaseDirectory(result) || result === "latest") { + throw new Error("A valid immutable release id is required."); + } + return result; +} + function exactCommitSha(value: string | undefined, label: string): string { const result = value?.trim().toLowerCase() ?? ""; if (!/^[0-9a-f]{40,64}$/.test(result)) { @@ -304,7 +328,7 @@ export function parsePublisherOptions(argv: string[]): PublisherOptions { return { country: countryValue, mode: "release", - releaseId: releaseId(values.get("--release")), + releaseId: releaseOrBuildFolderId(values.get("--release")), dryRun, ...(values.has("--sha") ? { hfCommitSha: exactCommitSha(values.get("--sha"), "--sha") } @@ -403,6 +427,12 @@ interface ReleaseCandidate { /** The `releases/` folder holding its files: releaseId unless a cut tag. */ releaseDirectory: string; hfCommitSha: string; + /** + * A build folder's publication time, as `releases.json` records it (null + * when that cannot be read as a date-time). Absent for release folders and + * tags, which are dated by their commit. + */ + publishedAt?: string | null; } interface ReleaseTag { @@ -697,6 +727,231 @@ async function enumerateReleaseCandidates( }; } +// -- Build folders and releases.json ---------------------------------------- +// +// A dataset repository with a root `releases.json` (microcosm-emitter#24) +// publishes each build in `releases///`, never changed after +// publishing, and lists every build and each release's current build in that +// record. Its builds are read from the record alone: no tags, no pointer +// files, no listing of `releases/`. A repository without `releases.json` is +// read from its tags and pointer files, as before. Which applies is read +// from the repository at the commit being published, never from the +// country's registration. A build's release id in the dashboard manifest is +// its folder, `/`. + +/** + * `releases.json` at an exact commit, checked as the release writer checks + * it, or null when the repository has none there. Hugging Face's 404 for the + * file is the only "none"; any other failure, and a record the writer would + * refuse, throws (releasesRecordFromResponse). + */ +async function readReleasesRecord( + country: MicrocosmCountry, + commitSha: string, +): Promise { + const response = await fetch(sourceUrl(country, commitSha, RELEASES_RECORD_PATH), { + headers: hfHeaders(), + cache: "no-store", + signal: AbortSignal.timeout(30_000), + }); + return releasesRecordFromResponse(response); +} + +function requireReleasesRecord( + country: MicrocosmCountry, + record: ReleasesRecord | null, +): ReleasesRecord { + if (!record) { + throw new Error(`${country}'s dataset repository has no ${RELEASES_RECORD_PATH}.`); + } + return record; +} + +// The record's `published_at`, as the dashboard manifest's RFC 3339 form. +function recordedPublicationTime(publishedAt: string): string | null { + const instant = Date.parse(publishedAt); + return Number.isFinite(instant) ? new Date(instant).toISOString() : null; +} + +/** + * Where a listed build's files are: its folder at the commit that wrote it. + * The build counts only when that folder holds calibration diagnostics and + * its release manifest names the same release and build, so a folder can + * never publish another build's files under its own name. + */ +async function resolveRecordedBuild( + country: MicrocosmCountry, + recorded: RecordedBuild, + revisionSha: string, +): Promise<{ candidate: ReleaseCandidate; reason?: never } | { candidate?: never; reason: string }> { + let commit: string; + try { + commit = await resolveHfBuildFolderSha(country, recorded.id, revisionSha, 0); + } catch (error) { + if (error instanceof CalibrationReleaseNotFoundError) { + return { reason: `releases/${recorded.id}/ has no calibration diagnostics.` }; + } + throw error; + } + const releaseManifest = await fetchJsonArtifact( + country, + commit, + `releases/${recorded.id}/${RELEASE_MANIFEST_NAME}`, + false, + ); + if (!releaseManifestNamesBuild(releaseManifest?.json, recorded.release, recorded.build)) { + return { + reason: + `releases/${recorded.id}/${RELEASE_MANIFEST_NAME} does not name release ` + + `${recorded.release} and build ${recorded.build}.`, + }; + } + return { + candidate: { + releaseId: recorded.id, + releaseDirectory: recorded.id, + hfCommitSha: commit, + publishedAt: recordedPublicationTime(recorded.publishedAt), + }, + }; +} + +// A build the dashboard manifest already holds keeps the commit and date it +// was published with; its folder is not listed again. +function publishedRecordedBuild( + manifest: CalibrationTreeManifest | undefined, + country: MicrocosmCountry, + id: string, +): ReleaseCandidate | null { + const existing = manifest ? manifestBuildForSource(manifest, country, "release", id) : null; + return existing + ? { + releaseId: id, + releaseDirectory: id, + hfCommitSha: existing.hfCommitSha, + publishedAt: existing.createdAt, + } + : null; +} + +async function enumerateRecordedBuildCandidates( + country: MicrocosmCountry, + manifest: CalibrationTreeManifest, + record: ReleasesRecord, + headSha: string, +): Promise<{ + candidates: ReleaseCandidate[]; + ineligible: ReconciliationOutcome[]; + failed: ReconciliationOutcome[]; +}> { + const candidates: ReleaseCandidate[] = []; + const ineligible: ReconciliationOutcome[] = []; + // A build whose folder or release manifest cannot be read fails on its + // own, as a release whose commit cannot be read does; the other listed + // builds are still reconciled. + const failed: ReconciliationOutcome[] = []; + for (const recorded of recordedBuilds(record)) { + const published = publishedRecordedBuild(manifest, country, recorded.id); + if (published) { + candidates.push(published); + continue; + } + let resolved: Awaited>; + try { + resolved = await resolveRecordedBuild(country, recorded, headSha); + } catch (error) { + failed.push({ + sourceId: recorded.id, + status: "failed", + buildArtifactId: null, + reason: error instanceof Error ? error.message : String(error), + }); + continue; + } + if (resolved.candidate) { + candidates.push(resolved.candidate); + } else { + ineligible.push({ + sourceId: recorded.id, + status: "ineligible", + buildArtifactId: null, + reason: resolved.reason, + }); + } + } + return { candidates, ineligible, failed }; +} + +async function selectRecordedBuild( + country: MicrocosmCountry, + record: ReleasesRecord, + id: string, + revisionSha: string, + manifest?: CalibrationTreeManifest, +): Promise> { + const recorded = recordedBuilds(record).find((build) => build.id === id); + if (!recorded) throw new Error(`${RELEASES_RECORD_PATH} does not list build ${id}.`); + let selected = publishedRecordedBuild(manifest, country, id); + if (!selected) { + const resolved = await resolveRecordedBuild(country, recorded, revisionSha); + if (!resolved.candidate) { + throw new Error(`Release ${id} cannot be published: ${resolved.reason}`); + } + selected = resolved.candidate; + } + return { ...selected, publishedAt: selected.publishedAt ?? null }; +} + +function requireCurrentDefaultBuild(record: ReleasesRecord) { + const current = currentDefaultBuild(record); + if (!current) { + throw new Error(`${RELEASES_RECORD_PATH} names no current build of its default release.`); + } + return current; +} + +/** + * The country's current build, as `releases.json` at `expectedSourceSha` + * (or at the head of the configured revision) names it: the current build + * of the record's default release, pinned to the commit that wrote its + * folder. A build `manifest` already holds keeps its published commit. + */ +export async function readRecordedCurrentBuild( + country: MicrocosmCountry, + expectedSourceSha?: string, + manifest?: CalibrationTreeManifest, +): Promise> { + const revisionSha = await publicationRevisionSha(country, expectedSourceSha); + const record = requireReleasesRecord(country, await readReleasesRecord(country, revisionSha)); + return recordedCurrentBuild(country, record, revisionSha, manifest); +} + +function recordedCurrentBuild( + country: MicrocosmCountry, + record: ReleasesRecord, + revisionSha: string, + manifest?: CalibrationTreeManifest, +): Promise> { + return selectRecordedBuild( + country, + record, + requireCurrentDefaultBuild(record).id, + revisionSha, + manifest, + ); +} + +// The exact commit a publication reads: the one given, or the head of the +// country's configured revision. +async function publicationRevisionSha( + country: MicrocosmCountry, + expectedSourceSha?: string, +): Promise { + return expectedSourceSha + ? exactCommitSha(expectedSourceSha, "Source revision") + : resolveHfRevisionSha(country, microcosmRevision(country), 0); +} + /** The folder a tag publishes from, for the single-release modes. */ async function releaseDirectoryForTag( country: MicrocosmCountry, @@ -792,7 +1047,7 @@ interface PublishReleaseOptions { dryRun?: boolean; expectedIndexSha256?: string; indexCreatedAt?: string | null; - uploadBundle?: CalibrationManifestStore["uploadBundle"]; + uploadBundle: CalibrationManifestStore["uploadBundle"]; } async function publishRelease(options: PublishReleaseOptions) { @@ -807,11 +1062,10 @@ async function publishRelease(options: PublishReleaseOptions) { dryRun = false, expectedIndexSha256, indexCreatedAt, - uploadBundle = (bundle: CalibrationTreeBundle) => - uploadCalibrationTreeBundle({ bundle, token: blobToken }), + uploadBundle, } = options; // The folder is interpolated into authenticated Hugging Face URLs. - const releaseDirectory = releaseId(options.releaseDirectory ?? id); + const releaseDirectory = releaseOrBuildFolderId(options.releaseDirectory ?? id); const resolvedSha = useExpectedShaExactly && expectedSha ? exactCommitSha(expectedSha, "Exact source revision") : await resolvePublicationSourceSha( @@ -877,10 +1131,13 @@ async function publishRelease(options: PublishReleaseOptions) { lossAttributionAvailable: calibration.target_loss_attribution.status !== "unavailable", comparison: { - // A tag's diagnostics name its folder; like the release reader, keep - // the tag so two builds of one release compare as different builds. + // A tag's diagnostics name its folder, and a build folder's may name + // its release; like the release reader, keep the tag or the build + // folder so two builds of one release compare as different builds. // A folder release keeps the id its diagnostics carry, as before. - releaseId: releaseDirectory === id ? calibration.release_id : id, + releaseId: releaseDirectory === id && !isBuildFolderId(id) + ? calibration.release_id + : id, calibrationProvenance: calibration.calibration_provenance, status: calibration.target_loss_attribution.status, aggregate: calibration.target_loss_attribution.aggregate, @@ -924,21 +1181,34 @@ async function promoteIfCurrent( country: MicrocosmCountry, candidate: Awaited>, entry: CalibrationTreeManifestEntry, - blobToken: string, + store: CalibrationManifestStore, ): Promise { - const latest = await readUpstreamLatest(country); - if ( - latest.releaseId !== candidate.bundle.index.build.releaseId || - latest.hfCommitSha !== candidate.bundle.index.build.hfCommitSha - ) { + const headSha = await publicationRevisionSha(country); + const record = await readReleasesRecord(country, headSha); + const published = candidate.bundle.index.build; + let latest: { releaseId: string; hfCommitSha: string }; + if (record) { + // Names first: another build's folder is never read for this check. + const current = currentDefaultBuild(record); + if (!current || current.id !== published.releaseId) return false; + try { + latest = await selectRecordedBuild(country, record, current.id, headSha); + } catch (error) { + // The build is registered; the next reconciliation moves the latest + // release once the current build's folder can be read. + console.warn( + `The latest release was not moved to ${current.id}: ` + + `${error instanceof Error ? error.message : String(error)}`, + ); + return false; + } + } else { + latest = await readUpstreamLatest(country, headSha); + } + if (latest.releaseId !== published.releaseId || latest.hfCommitSha !== published.hfCommitSha) { return false; } - await updateCalibrationTreeManifest({ - country, - token: blobToken, - entry, - makeLatest: true, - }); + await store.updateManifest(entry, true); return true; } @@ -982,8 +1252,12 @@ export interface CalibrationManifestStore { entry: CalibrationTreeManifestEntry, makeLatest?: boolean, ): Promise; - /** Uploads a built bundle; defaults to the Blob upload. */ - uploadBundle?( + /** + * Uploads a built bundle. Required: the store is the only route by which + * a publication writes to Blob, so a store in a test never falls back to + * the real upload. + */ + uploadBundle( bundle: CalibrationTreeBundle, ): ReturnType; } @@ -1010,12 +1284,11 @@ function blobCalibrationManifestStore( } async function registerReleaseBuild( - country: MicrocosmCountry, published: Awaited>, - blobToken: string, + store: CalibrationManifestStore, ): Promise { const entry = releaseManifestEntry(published); - await updateCalibrationTreeManifest({ country, entry, token: blobToken }); + await store.updateManifest(entry); return entry; } @@ -1029,7 +1302,7 @@ async function publishStagingSource(options: { source: ResolvedStagingSource; repository: { repo: string }; revisionSha: string; - uploadBundle: NonNullable; + uploadBundle: CalibrationManifestStore["uploadBundle"]; existing: CalibrationTreeManifestEntry | null; existingIndex: Awaited>["index"]; dryRun: boolean; @@ -1145,8 +1418,7 @@ export async function reconcileStagingBuilds( const finalized = runs.runs.filter((run) => FINAL_STAGING_STATUSES.has(run.status ?? ""), ); - const uploadBundle = store.uploadBundle ?? - ((bundle: CalibrationTreeBundle) => uploadCalibrationTreeBundle({ bundle, token: blobToken })); + const uploadBundle = store.uploadBundle; let manifest = await store.readManifest(); let blobs = await store.listBlobs(); const outcomes: ReconciliationOutcome[] = []; @@ -1247,7 +1519,17 @@ export async function reconcileReleaseBuilds( store: CalibrationManifestStore = blobCalibrationManifestStore(country, blobToken), ): Promise { let manifest = await store.readManifest(); - const inventory = await enumerateReleaseCandidates(country, manifest); + // releases.json at main's head decides the inventory. A repository with it + // reconciles every build it lists; entries published from tags or release + // folders stay in the manifest as they are, still readable, and are not + // reconciled again. A repository without it reconciles its release folders + // and tags. A record that cannot be read or is refused stops the run here, + // before anything is published or the latest release is moved. + const headSha = await publicationRevisionSha(country); + const record = await readReleasesRecord(country, headSha); + const inventory = record + ? await enumerateRecordedBuildCandidates(country, manifest, record, headSha) + : await enumerateReleaseCandidates(country, manifest); let blobs = await store.listBlobs(); const outcomes = [...inventory.ineligible, ...inventory.failed]; @@ -1309,7 +1591,8 @@ export async function reconcileReleaseBuilds( buildArtifactId: existing?.buildArtifactId, dryRun, expectedIndexSha256: existing?.indexSha256, - indexCreatedAt: existing ? existing.createdAt : undefined, + // A build folder is dated by releases.json; anything else by its commit. + indexCreatedAt: existing ? existing.createdAt : candidate.publishedAt, uploadBundle: store.uploadBundle, }); const entry = existing ?? releaseManifestEntry(published); @@ -1352,6 +1635,10 @@ export async function reconcileReleaseBuilds( failedReleaseIds, dryRun, store, + record + ? async () => + recordedLatest(record, inventory.candidates, [...inventory.ineligible, ...inventory.failed]) + : (current) => readUpstreamLatest(country, headSha, current), ); return { country, @@ -1363,12 +1650,14 @@ export async function reconcileReleaseBuilds( } /** - * Point the country's latest-release selection at the release its upstream - * pointer names, once that release is completely published. Returns why the - * selection could not be read or updated, or null. A release that failed in - * this reconciliation is never selected, so the selection keeps naming the - * build it named before. A dry run reads the pointer and reports a release - * that failed, but neither checks nor changes the selection otherwise. + * Point the country's latest-release selection at the release `readLatest` + * names (the upstream pointer's release, or releases.json's current build of + * its default release), once that release is completely published. Returns + * why the selection could not be read or updated, or null. A release that + * failed in this reconciliation is never selected, so the selection keeps + * naming the build it named before. A dry run reads the latest release and + * reports one that failed, but neither checks nor changes the selection + * otherwise. */ async function selectLatestRelease( country: MicrocosmCountry, @@ -1376,9 +1665,12 @@ async function selectLatestRelease( failedReleaseIds: ReadonlySet, dryRun: boolean, store: CalibrationManifestStore, + readLatest: ( + manifest: CalibrationTreeManifest, + ) => Promise<{ releaseId: string; hfCommitSha: string }>, ): Promise { try { - const latest = await readUpstreamLatest(country, undefined, manifest); + const latest = await readLatest(manifest); // Checked before the dry-run return, so a dry run reports a failed // latest release exactly as a run that writes does. if (failedReleaseIds.has(latest.releaseId)) { @@ -1403,6 +1695,30 @@ async function selectLatestRelease( } } +// The latest release for a repository with releases.json: the record's +// current build of its default release, at the commit reconciliation pinned +// it to. A current build that was not reconciled gives its reason: why it is +// ineligible, or why its folder or release manifest could not be read. +function recordedLatest( + record: ReleasesRecord, + candidates: readonly ReleaseCandidate[], + notReconciled: readonly ReconciliationOutcome[], +): { releaseId: string; hfCommitSha: string } { + const current = requireCurrentDefaultBuild(record); + const candidate = candidates.find((entry) => entry.releaseId === current.id); + if (!candidate) { + const outcome = notReconciled.find((entry) => entry.sourceId === current.id); + const reason = outcome?.reason ?? "releases.json lists it, but reconciliation found no candidate."; + throw new Error( + outcome?.status === "failed" + ? `Latest release ${current.id} failed to reconcile, so the latest-release selection ` + + `was not changed: ${reason}` + : `Latest release ${current.id} cannot be published: ${reason}`, + ); + } + return { releaseId: current.id, hfCommitSha: candidate.hfCommitSha }; +} + interface TimestampMigrationOutcome { buildArtifactId: string; releaseId: string; @@ -1445,6 +1761,10 @@ export async function migrateReleaseTimestamps( const outcomes: TimestampMigrationOutcome[] = []; for (const entry of manifest.countries[country]?.builds ?? []) { if (entry.kind !== "release" || !entry.releaseId) continue; + // A build folder is dated by releases.json, not by the commit that wrote + // the folder (a migrated build's folder is written after publication), + // and was never stored with the placeholder. + if (isBuildFolderId(entry.releaseId)) continue; const publishedAt = await resolveHfRepositoryCommitPublishedAt( entry.hfRepo, entry.hfCommitSha, @@ -1520,10 +1840,32 @@ export function reconciliationFailureMessage(report: ReconciliationReport): stri } export interface PublisherDependencies { - /** The manifest and Blob store the reconciliation and migration modes use. */ + /** The manifest and Blob store every release mode reads and writes. */ store?: CalibrationManifestStore; } +// `--latest` and `--release /` for a repository with +// releases.json: the build the record at `revisionSha` lists, pinned to the +// commit that wrote its folder. +async function requestedRecordedBuild( + country: MicrocosmCountry, + options: PublisherOptions, + record: ReleasesRecord, + revisionSha: string, +): Promise> { + if (options.mode === "latest") { + return recordedCurrentBuild(country, record, revisionSha); + } + const id = releaseOrBuildFolderId(options.releaseId); + if (!isBuildFolderId(id)) { + throw new Error( + `${country}'s dataset repository has ${RELEASES_RECORD_PATH}; --release takes ` + + `/, not ${id}.`, + ); + } + return selectRecordedBuild(country, record, id, revisionSha); +} + export async function runPublisher( options: PublisherOptions, dependencies: PublisherDependencies = {}, @@ -1576,28 +1918,51 @@ export async function runPublisher( return; } - const selection: ReleaseSelection = options.mode === "latest" - ? await readUpstreamLatest(options.country, options.hfCommitSha) - : await requestedReleaseSelection( - options.country, - releaseId(options.releaseId), - options.hfCommitSha, - ); - const published = await publishRelease({ - country: options.country, - id: selection.releaseId, - releaseDirectory: selection.releaseDirectory, - expectedSha: selection.hfCommitSha, - blobToken, - allowMissingReleaseTag: options.mode === "latest", - }); - const entry = await registerReleaseBuild(options.country, published, blobToken); - const promoted = await promoteIfCurrent( - options.country, - published, - entry, - blobToken, - ); + // releases.json at the commit being published decides how the release is + // read: from the record and its build folders, or, where the repository + // has none, from its tags and pointer files. + const revisionSha = await publicationRevisionSha(options.country, options.hfCommitSha); + const record = await readReleasesRecord(options.country, revisionSha); + if (!record && options.mode === "release" && isBuildFolderId(options.releaseId)) { + throw new Error( + `${options.country}'s dataset repository has no ${RELEASES_RECORD_PATH}, so ` + + `${options.releaseId} cannot name a build folder.`, + ); + } + let published: Awaited>; + if (record) { + const selection = await requestedRecordedBuild(options.country, options, record, revisionSha); + published = await publishRelease({ + country: options.country, + id: selection.releaseId, + releaseDirectory: selection.releaseDirectory, + expectedSha: selection.hfCommitSha, + blobToken, + useExpectedShaExactly: true, + indexCreatedAt: selection.publishedAt, + uploadBundle: store.uploadBundle, + }); + } else { + // The pointer file is read at the commit releases.json was looked for. + const selection: ReleaseSelection = options.mode === "latest" + ? await readUpstreamLatest(options.country, revisionSha) + : await requestedReleaseSelection( + options.country, + releaseId(options.releaseId), + options.hfCommitSha, + ); + published = await publishRelease({ + country: options.country, + id: selection.releaseId, + releaseDirectory: selection.releaseDirectory, + expectedSha: selection.hfCommitSha, + blobToken, + allowMissingReleaseTag: options.mode === "latest", + uploadBundle: store.uploadBundle, + }); + } + const entry = await registerReleaseBuild(published, store); + const promoted = await promoteIfCurrent(options.country, published, entry, store); console.log(JSON.stringify({ country: options.country, releaseId: published.bundle.index.build.releaseId, diff --git a/frontend/packages/calibration-tree/src/release-record.test.ts b/frontend/packages/calibration-tree/src/release-record.test.ts new file mode 100644 index 00000000..bdaff06d --- /dev/null +++ b/frontend/packages/calibration-tree/src/release-record.test.ts @@ -0,0 +1,283 @@ +import { expect, test } from "bun:test"; + +import { + ReleasesRecordError, + buildFolderId, + currentDefaultBuild, + isBuildFolderId, + isReleaseDirectory, + parseBuildFolderId, + parseReleasesRecord, + recordedBuilds, + releaseManifestNamesBuild, + releasesRecordFromResponse, +} from "./release-record"; + +// The record's documented example (microcosm-emitter#24's +// tests/interface/test_releases_record.py). All values are synthetic. +const NATIONAL = "microcosm-uk-2024-25-national"; +const DENSE = "microcosm-uk-2024-25-dense"; +const OLDER_BUILD = "uk-frs-calibration-attempt-20261014T214443Z-d12ff9b3"; +const NEWER_BUILD = "uk-frs-calibration-attempt-20261019T083323Z-6cba5d71"; +const DENSE_BUILD = "uk-local-candidate-f100-s42-20261019T000432Z-ee5c2dbe"; + +function documentedExample(): Record { + return { + schema_version: 1, + default: NATIONAL, + releases: { + [NATIONAL]: { + role: "national_default", + current: NEWER_BUILD, + builds: { + [OLDER_BUILD]: { published_at: "2026-10-14T21:44:43+00:00", withdrawn: false }, + [NEWER_BUILD]: { published_at: "2026-10-19T08:33:23+00:00", withdrawn: false }, + }, + }, + }, + }; +} + +function withDense(document: Record, current: string | null = null) { + const releases = document.releases as Record; + releases[DENSE] = { + role: "non_default_local_area", + current, + builds: { + [DENSE_BUILD]: { published_at: "2026-10-19T07:53:18+00:00", withdrawn: true }, + }, + }; + return document; +} + +function nationalRelease(document: Record): Record { + return (document.releases as Record>)[NATIONAL]; +} + +test("the documented releases.json example parses into its releases and builds", () => { + const record = parseReleasesRecord(documentedExample()); + expect(record.default).toBe(NATIONAL); + expect(record.releases[NATIONAL]).toEqual({ + role: "national_default", + current: NEWER_BUILD, + builds: { + [OLDER_BUILD]: { publishedAt: "2026-10-14T21:44:43+00:00", withdrawn: false }, + [NEWER_BUILD]: { publishedAt: "2026-10-19T08:33:23+00:00", withdrawn: false }, + }, + }); +}); + +test("the repository's current build is the current build of the default release", () => { + expect(currentDefaultBuild(parseReleasesRecord(documentedExample()))).toEqual({ + release: NATIONAL, + build: NEWER_BUILD, + id: `${NATIONAL}/${NEWER_BUILD}`, + }); +}); + +test("a release may have no current build, and a record may name no default release", () => { + const record = parseReleasesRecord(withDense(documentedExample())); + expect(record.releases[DENSE].current).toBeNull(); + + const noDefault = documentedExample(); + noDefault.default = null; + expect(currentDefaultBuild(parseReleasesRecord(noDefault))).toBeNull(); + + const noCurrent = documentedExample(); + nationalRelease(noCurrent).current = null; + expect(currentDefaultBuild(parseReleasesRecord(noCurrent))).toBeNull(); +}); + +test("every listed build is listed once, with its release's role and its own publication time", () => { + const builds = recordedBuilds(parseReleasesRecord(withDense(documentedExample()))); + expect(builds).toEqual([ + { + release: DENSE, + build: DENSE_BUILD, + id: `${DENSE}/${DENSE_BUILD}`, + role: "non_default_local_area", + publishedAt: "2026-10-19T07:53:18+00:00", + withdrawn: true, + current: false, + inDefaultRelease: false, + }, + { + release: NATIONAL, + build: OLDER_BUILD, + id: `${NATIONAL}/${OLDER_BUILD}`, + role: "national_default", + publishedAt: "2026-10-14T21:44:43+00:00", + withdrawn: false, + current: false, + inDefaultRelease: true, + }, + { + release: NATIONAL, + build: NEWER_BUILD, + id: `${NATIONAL}/${NEWER_BUILD}`, + role: "national_default", + publishedAt: "2026-10-19T08:33:23+00:00", + withdrawn: false, + current: true, + inDefaultRelease: true, + }, + ]); +}); + +test("a record whose current build is unlisted or withdrawn is refused", () => { + const unlisted = documentedExample(); + nationalRelease(unlisted).current = "uk-frs-calibration-attempt-20261101T000000Z-00000000"; + expect(() => parseReleasesRecord(unlisted)).toThrow(ReleasesRecordError); + expect(() => parseReleasesRecord(unlisted)).toThrow("is not listed"); + + const withdrawn = documentedExample(); + const builds = nationalRelease(withdrawn).builds as Record>; + builds[NEWER_BUILD].withdrawn = true; + expect(() => parseReleasesRecord(withdrawn)).toThrow("is withdrawn"); +}); + +test("a current build named like a built-in object property is refused unless it is listed", () => { + // The writer's check_record looks the name up among the listed builds only. + for (const builtInName of ["constructor", "toString", "valueOf", "hasOwnProperty", "__proto__"]) { + const document = documentedExample(); + nationalRelease(document).current = builtInName; + expect(() => parseReleasesRecord(document), builtInName).toThrow(ReleasesRecordError); + expect(() => parseReleasesRecord(document), builtInName).toThrow("is not listed"); + } + + const listed = documentedExample(); + const release = nationalRelease(listed); + release.builds = { + ...(release.builds as Record), + constructor: { published_at: "2026-10-20T00:00:00+00:00", withdrawn: false }, + }; + release.current = "constructor"; + expect(parseReleasesRecord(listed).releases[NATIONAL].current).toBe("constructor"); +}); + +test("a record whose default release is not listed is refused", () => { + const document = documentedExample(); + document.default = DENSE; + expect(() => parseReleasesRecord(document)).toThrow("is not listed"); +}); + +test("a record that is not the documented shape is refused", () => { + const cases: Array<[string, (document: Record) => unknown]> = [ + ["not an object", () => []], + ["an extra top-level key", (document) => ({ ...document, latest: NATIONAL })], + ["a missing top-level key", ({ default: _default, ...rest }) => rest], + ["another schema version", (document) => ({ ...document, schema_version: 2 })], + ["an unsafe release name", (document) => ({ + ...document, + default: null, + releases: { "../other": nationalRelease(document) }, + })], + ["an invalid release role", (document) => { + nationalRelease(document).role = "National Default"; + return document; + }], + ["a release without its role", (document) => { + delete nationalRelease(document).role; + return document; + }], + ["an unsafe build name", (document) => { + const release = nationalRelease(document); + release.current = null; + release.builds = { "a/b": { published_at: "2026-10-19T08:33:23+00:00", withdrawn: false } }; + return document; + }], + ["a build without its publication time", (document) => { + const builds = nationalRelease(document).builds as Record>; + builds[OLDER_BUILD] = { withdrawn: false }; + return document; + }], + ["a build whose withdrawn flag is not a boolean", (document) => { + const builds = nationalRelease(document).builds as Record>; + builds[OLDER_BUILD] = { published_at: "2026-10-14T21:44:43+00:00", withdrawn: "no" }; + return document; + }], + ["a current build that is not a name", (document) => { + nationalRelease(document).current = 7; + return document; + }], + ]; + for (const [label, change] of cases) { + expect(() => parseReleasesRecord(change(documentedExample())), label).toThrow( + ReleasesRecordError, + ); + } +}); + +test("a build is identified by its folder under releases/, release then build", () => { + expect(buildFolderId(NATIONAL, NEWER_BUILD)).toBe(`${NATIONAL}/${NEWER_BUILD}`); + expect(parseBuildFolderId(`${NATIONAL}/${NEWER_BUILD}`)).toEqual({ + release: NATIONAL, + build: NEWER_BUILD, + }); + for (const value of [ + NATIONAL, + `${NATIONAL}/`, + `/${NEWER_BUILD}`, + `${NATIONAL}/${NEWER_BUILD}/release_manifest.json`, + `${NATIONAL}/..`, + `${NATIONAL}/.hidden`, + "latest", + "", + ]) { + expect(parseBuildFolderId(value), value).toBeNull(); + expect(isBuildFolderId(value), value).toBe(false); + } + expect(() => buildFolderId(NATIONAL, "a/b")).toThrow(); +}); + +test("a release directory is a release folder or a build folder, never a path that leaves releases/", () => { + expect(isReleaseDirectory(NATIONAL)).toBe(true); + expect(isReleaseDirectory(`${NATIONAL}/${NEWER_BUILD}`)).toBe(true); + for (const value of ["", "..", `${NATIONAL}/..`, `${NATIONAL}/${NEWER_BUILD}/extra`, "a b", 7, null]) { + expect(isReleaseDirectory(value), String(value)).toBe(false); + } +}); + +test("a release manifest names its build by its top-level release and build", () => { + expect(releaseManifestNamesBuild({ release: NATIONAL, build: NEWER_BUILD }, NATIONAL, NEWER_BUILD)) + .toBe(true); + // Today's manifests: `build` is an object, and its build_id is the release. + expect(releaseManifestNamesBuild( + { build: { build_id: NATIONAL, attempt_id: NEWER_BUILD } }, + NATIONAL, + NEWER_BUILD, + )).toBe(false); + expect(releaseManifestNamesBuild({ release: NATIONAL, build: OLDER_BUILD }, NATIONAL, NEWER_BUILD)) + .toBe(false); + expect(releaseManifestNamesBuild({ release: DENSE, build: NEWER_BUILD }, NATIONAL, NEWER_BUILD)) + .toBe(false); + expect(releaseManifestNamesBuild(null, NATIONAL, NEWER_BUILD)).toBe(false); +}); + +// Only Hugging Face's 404 for the file means a repository has no +// releases.json; every other answer is an error, never a fallback to tags. +const notFound = (errorCode?: string) => new Response("Not found", { + status: 404, + headers: errorCode ? { "X-Error-Code": errorCode } : {}, +}); + +test("a 404 for the file, with or without its error code, means the repository has no releases.json", async () => { + await expect(releasesRecordFromResponse(notFound("EntryNotFound"))).resolves.toBeNull(); + await expect(releasesRecordFromResponse(notFound())).resolves.toBeNull(); +}); + +test("a 404 that says the repository or the revision is missing is an error", async () => { + await expect(releasesRecordFromResponse(notFound("RepoNotFound"))) + .rejects.toThrow("Hugging Face returned 404 (RepoNotFound) for releases.json."); + await expect(releasesRecordFromResponse(notFound("RevisionNotFound"))) + .rejects.toThrow("Hugging Face returned 404 (RevisionNotFound) for releases.json."); +}); + +test("a server error or a refused token for releases.json is an error", async () => { + await expect(releasesRecordFromResponse(new Response("unavailable", { status: 503 }))) + .rejects.toThrow("Hugging Face returned 503 for releases.json."); + await expect(releasesRecordFromResponse(new Response("unauthorized", { + status: 401, + headers: { "X-Error-Code": "RepoNotFound" }, + }))).rejects.toThrow("Hugging Face returned 401 (RepoNotFound) for releases.json."); +}); diff --git a/frontend/packages/calibration-tree/src/release-record.ts b/frontend/packages/calibration-tree/src/release-record.ts new file mode 100644 index 00000000..a4c4eb29 --- /dev/null +++ b/frontend/packages/calibration-tree/src/release-record.ts @@ -0,0 +1,277 @@ +// `releases.json`: the one record of which build of each release a Microcosm +// dataset repository has published and which is current. The repository +// publishes every build in its own folder, never changed after publishing: +// +// releases.json +// releases///release_manifest.json +// releases///... +// +// Every reader finds the layout this way: a repository with releases.json is +// read from it and its build folders only; a repository without one is read +// from its tags and pointer files (`latest*.json`). No country registration +// names the layout, so a repository's switch needs no dashboard change. +// +// The record's shape and rules are microcosm-emitter's +// `microcosm_emitter_interface.releases` (microcosm-emitter#24), whose release +// writer is the only program that changes the file. This module reads the +// record with the same rules, so a record the writer would refuse is refused +// here too, with one exception: JSON.parse reads `1.0` as the number 1, so a +// `schema_version` of `1.0` passes here although the writer, which requires +// an integer, refuses it. The writer itself always writes `1`. Isomorphic: +// the release picker and the tree publisher share it. + +export const RELEASES_RECORD_PATH = "releases.json"; +export const RELEASES_RECORD_SCHEMA_VERSION = 1; +export const RELEASE_MANIFEST_NAME = "release_manifest.json"; +// The interface's MAX_RECORD_BYTES: the largest releases.json the writer's +// parser accepts, and the size its checks keep every record within. +export const MAX_RELEASES_RECORD_BYTES = 4 * 1024 * 1024; + +// The interface's SAFE_IDENTIFIER and ROLE_IDENTIFIER. +const SAFE_IDENTIFIER_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const ROLE_IDENTIFIER_RE = /^[a-z][a-z0-9_]{0,63}$/; +const RECORD_KEYS = ["default", "releases", "schema_version"]; +const RELEASE_KEYS = ["builds", "current", "role"]; +const BUILD_KEYS = ["published_at", "withdrawn"]; + +export interface RecordedBuildEntry { + /** As the writer recorded it; not reformatted. */ + publishedAt: string; + withdrawn: boolean; +} + +export interface RecordedRelease { + role: string; + /** Null while the release has no current build. */ + current: string | null; + builds: Record; +} + +export interface ReleasesRecord { + /** The release a repository's default dataset comes from, or null. */ + default: string | null; + releases: Record; +} + +/** One listed build, with what the record says about it and its release. */ +export interface RecordedBuild { + release: string; + build: string; + /** The build's folder under `releases/`: `/`. */ + id: string; + role: string; + publishedAt: string; + withdrawn: boolean; + /** The build is its release's current build. */ + current: boolean; + /** The build's release is the record's default release. */ + inDefaultRelease: boolean; +} + +export class ReleasesRecordError extends Error {} + +function isSafeIdentifier(value: unknown): value is string { + return typeof value === "string" && SAFE_IDENTIFIER_RE.test(value); +} + +function isPlainObject(value: unknown): value is Record { + return value != null && typeof value === "object" && !Array.isArray(value); +} + +function hasExactly(value: Record, keys: readonly string[]): boolean { + const present = Object.keys(value).sort(); + return present.length === keys.length && present.every((key, index) => key === keys[index]); +} + +function refuse(message: string): never { + throw new ReleasesRecordError(message); +} + +/** + * Parse `releases.json` and check it as the writer does: its exact shape, + * safe release and build names, and (`check_record`) that each `current` + * names a listed build that is not withdrawn and that `default` names a + * listed release. + */ +export function parseReleasesRecord(document: unknown): ReleasesRecord { + if (!isPlainObject(document) || !hasExactly(document, RECORD_KEYS)) { + refuse(`${RELEASES_RECORD_PATH} must have exactly ${RECORD_KEYS.join(", ")}.`); + } + if (document.schema_version !== RELEASES_RECORD_SCHEMA_VERSION) { + refuse(`${RELEASES_RECORD_PATH} schema_version must be ${RELEASES_RECORD_SCHEMA_VERSION}.`); + } + if (!isPlainObject(document.releases)) refuse("releases must be an object."); + const releases: Record = {}; + for (const [release, entry] of Object.entries(document.releases)) { + if (!isSafeIdentifier(release)) refuse("A release name is not a safe identifier."); + if (!isPlainObject(entry) || !hasExactly(entry, RELEASE_KEYS)) { + refuse(`Release ${release} must have ${RELEASE_KEYS.join(", ")}.`); + } + if (typeof entry.role !== "string" || !ROLE_IDENTIFIER_RE.test(entry.role)) { + refuse(`Release ${release} has an invalid role.`); + } + if (entry.current !== null && typeof entry.current !== "string") { + refuse(`Release ${release} current must be a build or null.`); + } + if (!isPlainObject(entry.builds)) refuse(`Release ${release} builds must be an object.`); + const builds: Record = {}; + for (const [build, buildEntry] of Object.entries(entry.builds)) { + if (!isSafeIdentifier(build)) refuse("A build name is not a safe identifier."); + if ( + !isPlainObject(buildEntry) || + !hasExactly(buildEntry, BUILD_KEYS) || + typeof buildEntry.published_at !== "string" || + !buildEntry.published_at || + typeof buildEntry.withdrawn !== "boolean" + ) { + refuse(`Build ${build} of ${release} is malformed.`); + } + builds[build] = { + publishedAt: buildEntry.published_at, + withdrawn: buildEntry.withdrawn, + }; + } + releases[release] = { role: entry.role, current: entry.current, builds }; + } + if (document.default !== null && typeof document.default !== "string") { + refuse("default must be a release name or null."); + } + const record: ReleasesRecord = { default: document.default, releases }; + if (record.default != null && !Object.hasOwn(releases, record.default)) { + refuse(`Default ${record.default} is not listed.`); + } + for (const [release, entry] of Object.entries(releases)) { + if (entry.current == null) continue; + // Only the listed builds: `builds` is an ordinary object, so a name such + // as "constructor" would otherwise find an inherited property. + const current = Object.hasOwn(entry.builds, entry.current) + ? entry.builds[entry.current] + : undefined; + if (!current) refuse(`Current build ${entry.current} of ${release} is not listed.`); + if (current.withdrawn) refuse(`Current build ${entry.current} of ${release} is withdrawn.`); + } + return record; +} + +/** + * Read `releases.json` from its bytes as the writer's `ReleasesRecord.parse` + * does: refuse a record larger than MAX_RELEASES_RECORD_BYTES or one that is + * not a readable JSON document, then check it with parseReleasesRecord. + */ +export function parseReleasesRecordBytes(bytes: Uint8Array): ReleasesRecord { + if (bytes.byteLength > MAX_RELEASES_RECORD_BYTES) { + refuse(`${RELEASES_RECORD_PATH} is larger than ${MAX_RELEASES_RECORD_BYTES} bytes.`); + } + let parsed: unknown; + try { + parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); + } catch { + refuse(`${RELEASES_RECORD_PATH} is not a readable JSON document.`); + } + return parseReleasesRecord(parsed); +} + +// Hugging Face's error codes for a 404 that is not about the file: the +// repository or the revision is missing (or unreadable with this token). +const MISSING_REPOSITORY_OR_REVISION = new Set(["RepoNotFound", "RevisionNotFound"]); + +/** + * Read Hugging Face's answer to a request for releases.json: the record, + * checked as parseReleasesRecordBytes checks it, or null when the repository + * has no releases.json at that revision. Only a 404 means "no record", and + * only when Hugging Face's error code (`X-Error-Code`) does not say that the + * repository or the revision is missing. Any other failure throws, so a + * reader never falls back to tags or pointer files because of it. + */ +export async function releasesRecordFromResponse( + response: Response, +): Promise { + const errorCode = response.headers.get("x-error-code"); + if (response.status === 404 && (errorCode == null || !MISSING_REPOSITORY_OR_REVISION.has(errorCode))) { + return null; + } + if (!response.ok) { + throw new Error( + `Hugging Face returned ${response.status}${errorCode ? ` (${errorCode})` : ""} ` + + `for ${RELEASES_RECORD_PATH}.`, + ); + } + return parseReleasesRecordBytes(new Uint8Array(await response.arrayBuffer())); +} + +/** A build's folder under `releases/`, which identifies it: `/`. */ +export function buildFolderId(release: string, build: string): string { + if (!isSafeIdentifier(release) || !isSafeIdentifier(build)) { + throw new ReleasesRecordError("A release and a build must be safe identifiers."); + } + return `${release}/${build}`; +} + +export function parseBuildFolderId( + value: unknown, +): { release: string; build: string } | null { + if (typeof value !== "string") return null; + const segments = value.split("/"); + if (segments.length !== 2 || !segments.every(isSafeIdentifier)) return null; + return { release: segments[0], build: segments[1] }; +} + +export function isBuildFolderId(value: unknown): value is string { + return parseBuildFolderId(value) != null; +} + +/** + * A folder under `releases/` that release files are read from: a release + * folder (``) or a build folder (`/`). Folders + * are interpolated into Hugging Face URLs that carry the server's token, so + * each segment passes the release-id allowlist and none can leave `releases/`. + */ +export function isReleaseDirectory(value: unknown): value is string { + return isSafeIdentifier(value) || isBuildFolderId(value); +} + +/** Every listed build, ordered by release, then build, as the writer sorts them. */ +export function recordedBuilds(record: ReleasesRecord): RecordedBuild[] { + const byName = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0); + return Object.keys(record.releases).sort(byName).flatMap((release) => { + const entry = record.releases[release]; + return Object.keys(entry.builds).sort(byName).map((build) => ({ + release, + build, + id: buildFolderId(release, build), + role: entry.role, + publishedAt: entry.builds[build].publishedAt, + withdrawn: entry.builds[build].withdrawn, + current: entry.current === build, + inDefaultRelease: record.default === release, + })); + }); +} + +/** + * The repository's current build: the current build of its default release, + * or null while the record names no default release or that release has no + * current build. + */ +export function currentDefaultBuild( + record: ReleasesRecord, +): { release: string; build: string; id: string } | null { + const release = record.default; + const build = release == null ? null : record.releases[release]?.current ?? null; + if (release == null || build == null) return null; + return { release, build, id: buildFolderId(release, build) }; +} + +/** + * Whether a build folder's release manifest names that release and build: + * the writer's `check_repository` rule, read from the manifest's top-level + * `release` and `build`. Manifests written before the build folders keep + * `build` as an object whose `build_id` is the release, and never match. + */ +export function releaseManifestNamesBuild( + manifest: unknown, + release: string, + build: string, +): boolean { + return isPlainObject(manifest) && manifest.release === release && manifest.build === build; +} diff --git a/frontend/packages/calibration-tree/src/staging-artifact.ts b/frontend/packages/calibration-tree/src/staging-artifact.ts index 6000381a..ddfc1dad 100644 --- a/frontend/packages/calibration-tree/src/staging-artifact.ts +++ b/frontend/packages/calibration-tree/src/staging-artifact.ts @@ -5,6 +5,7 @@ import { type MicrocosmCountry, asObject, assertSafeReleaseId, + assertSafeReleaseOrBuildFolderId, buildCalibration, buildComparison, latestMicrocosmCalibrationSummary, @@ -12,6 +13,7 @@ import { loadCountryRepositoryHashedJson, loadPointerReleaseId, loadPublishedCutReleases, + loadRecordedReleases, loadRelease, loadReleases, microcosmCountryGeography, @@ -982,7 +984,7 @@ export async function loadStagingTargetChangeDataset( ): Promise { if (stagingUnavailableReason(country)) return null; assertSafeReleaseId(runId, "run"); - assertSafeReleaseId(releaseId, "release"); + assertSafeReleaseOrBuildFolderId(releaseId, "release"); const progress = await stagingJsonOrNull( `runs/${runId}/progress.json`, TARGET_CHANGE_MUTABLE_CACHE_SECONDS, @@ -1292,9 +1294,10 @@ export async function stagingRunPipelineId( /** * The most recently published release build whose release is local-area, by - * the dataset roles `releases` carries (read from each release manifest, as - * the release picker reads them) and the publication time the dashboard - * manifest records. + * the dataset roles `releases` carries (read from releases.json, or from each + * release manifest, as the release picker reads them) and the publication + * time the dashboard manifest records. A build releases.json marks withdrawn + * is never chosen. */ export function newestPublishedLocalAreaRelease( manifest: CalibrationTreeManifest, @@ -1302,7 +1305,9 @@ export function newestPublishedLocalAreaRelease( releases: readonly ReleaseEntry[], ): CalibrationTreeManifestEntry | null { const localAreaReleases = new Set( - releases.filter((release) => release.is_local_area).map((release) => release.release_id), + releases + .filter((release) => release.is_local_area && release.withdrawn !== true) + .map((release) => release.release_id), ); const builds = (manifest.countries[country]?.builds ?? []).filter( (build) => @@ -1313,6 +1318,26 @@ export function newestPublishedLocalAreaRelease( return calibrationBuildsNewestFirst(builds)[0] ?? null; } +/** + * The releases a local-area Staging candidate may be compared with, with + * their roles. A repository with releases.json lists the builds it names and + * nothing else; one without lists the folders on main and its published + * tagged builds. A releases.json that cannot be read or is refused throws, + * so the candidate gets no baseline. + */ +export async function stagingBaselineReleases( + revalidate: number, + country: MicrocosmCountry, + manifest: CalibrationTreeManifest, +): Promise { + const recorded = await loadRecordedReleases(revalidate, country, manifest); + if (recorded) return recorded; + // The published tagged builds are the ones the folder listing cannot name. + const folders = await loadReleases(revalidate, country); + const tagged = await loadPublishedCutReleases(revalidate, country, manifest, folders); + return [...folders, ...tagged]; +} + function defaultStagingComparisonReleaseDependencies( revalidate: number, ): StagingComparisonReleaseDependencies { @@ -1321,13 +1346,9 @@ function defaultStagingComparisonReleaseDependencies( currentReleaseId: async (country) => (await loadPointerReleaseId(revalidate, country)).release_id, newestLocalAreaReleaseId: async (country) => { - const [{ manifest }, folders] = await Promise.all([ - readCalibrationTreeManifest(), - loadReleases(revalidate, country), - ]); - const tagged = await loadPublishedCutReleases(revalidate, country, manifest, folders); - return newestPublishedLocalAreaRelease(manifest, country, [...folders, ...tagged]) - ?.releaseId ?? null; + const { manifest } = await readCalibrationTreeManifest(); + const releases = await stagingBaselineReleases(revalidate, country, manifest); + return newestPublishedLocalAreaRelease(manifest, country, releases)?.releaseId ?? null; }, }; } diff --git a/frontend/packages/calibration-tree/src/staging-comparison-release.test.ts b/frontend/packages/calibration-tree/src/staging-comparison-release.test.ts index 7e67c2ba..c94dfdc9 100644 --- a/frontend/packages/calibration-tree/src/staging-comparison-release.test.ts +++ b/frontend/packages/calibration-tree/src/staging-comparison-release.test.ts @@ -7,14 +7,17 @@ import { type CalibrationTreeManifestEntry, } from "./calibration-tree-manifest"; import { stagingLocalAreaPipelines } from "./countries"; -import type { ReleaseEntry } from "./latest-artifact"; +import { InvalidReleaseIdError, type ReleaseEntry } from "./latest-artifact"; import { + loadStagingTargetChangeDataset, newestPublishedLocalAreaRelease, resolveStagingComparisonRelease, + stagingBaselineReleases, stagingRunPipelineId, stagingResolveUrl, type StagingComparisonReleaseDependencies, } from "./staging-artifact"; +import { missingReleasesRecord } from "./test-support/releases-record-responses"; // UK shapes as published on 19 Oct 2026. A local-area candidate's staged // receipt and run manifest record no dataset role, and its dataset file name @@ -217,3 +220,183 @@ test("a staging run's pipeline id is read from its run manifest", async () => { globalThis.fetch = originalFetch; } }); + +// A repository with releases.json (microcosm-emitter#24): the local-area +// release is the one releases.json gives the role local_area, and its builds +// are named by their folders. All values are synthetic. +const DENSE_OLDER_BUILD = `${DENSE_FOLDER}/uk-local-candidate-f100-s42-20261005T101500Z-0d0d0d0d`; +const DENSE_NEWER_BUILD = `${DENSE_FOLDER}/uk-local-candidate-f100-s42-20261019T000432Z-ee5c2dbe`; +const NATIONAL_BUILD = `${NATIONAL_FOLDER}/uk-frs-calibration-attempt-20261019T083323Z-6cba5d71`; + +function recordedReleases() { + const build = (publishedAt: string) => ({ published_at: publishedAt, withdrawn: false }); + return { + schema_version: 1, + default: NATIONAL_FOLDER, + releases: { + [NATIONAL_FOLDER]: { + role: "national", + current: NATIONAL_BUILD.split("/")[1], + builds: { [NATIONAL_BUILD.split("/")[1]]: build("2026-10-19T08:33:23+00:00") }, + }, + [DENSE_FOLDER]: { + role: "local_area", + current: null, + builds: { + [DENSE_OLDER_BUILD.split("/")[1]]: build("2026-10-05T10:15:00+00:00"), + [DENSE_NEWER_BUILD.split("/")[1]]: build("2026-10-19T00:04:32+00:00"), + }, + }, + }, + }; +} + +function buildFolderManifest(): CalibrationTreeManifest { + return [ + releaseBuild(NATIONAL_BUILD, "2026-10-19T08:33:23.000Z", "6"), + releaseBuild(DENSE_OLDER_BUILD, "2026-10-05T10:15:00.000Z", "7"), + releaseBuild(DENSE_NEWER_BUILD, "2026-10-19T00:04:32.000Z", "8"), + // A tagged build published before the build folders, newer than both. + releaseBuild(`${DENSE_FOLDER}-20261020T000000Z-ffffffff`, "2026-10-20T00:00:00.000Z", "9", DENSE_FOLDER), + ].reduce( + (manifest, entry) => withCalibrationTreeManifestEntry(manifest, "uk", entry), + emptyCalibrationTreeManifest(), + ); +} + +test("for a repository with releases.json, a local-area candidate's baseline is the newest published build of a local-area release it lists", async () => { + const originalFetch = globalThis.fetch; + const requested: string[] = []; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input); + requested.push(url); + if (url.endsWith("/resolve/main/releases.json")) return Response.json(recordedReleases()); + throw new Error(`Unexpected URL ${url}`); + }) as typeof fetch; + try { + const manifest = buildFolderManifest(); + const releases = await stagingBaselineReleases(0, "uk", manifest); + expect(newestPublishedLocalAreaRelease(manifest, "uk", releases)?.releaseId) + .toBe(DENSE_NEWER_BUILD); + // Nothing but releases.json: no release-folder listing and no tags. + expect(requested).toHaveLength(1); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("a withdrawn build is never a local-area candidate's baseline", async () => { + const record = recordedReleases(); + record.releases[DENSE_FOLDER].builds[DENSE_NEWER_BUILD.split("/")[1]].withdrawn = true; + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input); + if (url.endsWith("/resolve/main/releases.json")) return Response.json(record); + throw new Error(`Unexpected URL ${url}`); + }) as typeof fetch; + try { + const manifest = buildFolderManifest(); + const releases = await stagingBaselineReleases(0, "uk", manifest); + // The withdrawn build stays in the inventory, marked, as the picker shows it. + expect(releases.find((release) => release.release_id === DENSE_NEWER_BUILD)?.withdrawn).toBe(true); + expect(newestPublishedLocalAreaRelease(manifest, "uk", releases)?.releaseId) + .toBe(DENSE_OLDER_BUILD); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("for a repository without releases.json, the baseline comes from its release folders and published tagged builds", async () => { + const originalFetch = globalThis.fetch; + const requested: string[] = []; + const taggedDense = `${DENSE_FOLDER}-20261020T000000Z-ffffffff`; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input); + requested.push(url); + if (url.endsWith("/resolve/main/releases.json")) return missingReleasesRecord(); + if (url.endsWith("/tree/main/releases?recursive=true")) return Response.json([]); + if (url.endsWith(`/resolve/${"9".repeat(40)}/releases/${DENSE_FOLDER}/release_manifest.json`)) { + return Response.json({ dataset_role: "non_default_local_area", is_default: false }); + } + throw new Error(`Unexpected URL ${url}`); + }) as typeof fetch; + try { + const manifest = buildFolderManifest(); + const baseline = stagingBaselineReleases(0, "uk", manifest); + await expect(baseline).resolves.toBeDefined(); + const releases = await baseline; + // Builds in their own folders are listed only from releases.json, so the + // tagged build published before them is the baseline. + expect(newestPublishedLocalAreaRelease(manifest, "uk", releases)?.releaseId).toBe(taggedDense); + expect(requested.some((url) => url.endsWith("/tree/main/releases?recursive=true"))).toBe(true); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("a releases.json the release writer would refuse leaves a local-area candidate without a baseline", async () => { + const refused = recordedReleases(); + // A current build that is withdrawn is refused by the writer's rules. + refused.releases[NATIONAL_FOLDER].builds[NATIONAL_BUILD.split("/")[1]].withdrawn = true; + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input); + if (url.endsWith("/resolve/main/releases.json")) return Response.json(refused); + throw new Error(`Unexpected URL ${url}`); + }) as typeof fetch; + try { + const manifest = buildFolderManifest(); + await expect(stagingBaselineReleases(0, "uk", manifest)).rejects.toThrow("is withdrawn"); + let currentReleaseRead = false; + const comparison = resolveStagingComparisonRelease(LOCAL_CANDIDATE_RUN, "uk", { + runPipelineId: async () => "uk-local-candidate", + currentReleaseId: async () => { + currentReleaseRead = true; + return NATIONAL_BUILD; + }, + newestLocalAreaReleaseId: async (country) => + newestPublishedLocalAreaRelease( + manifest, + country, + await stagingBaselineReleases(0, country, manifest), + )?.releaseId ?? null, + }); + // The comparison fails: it is not made against the current release. + await expect(comparison).rejects.toThrow("is withdrawn"); + expect(currentReleaseRead).toBe(false); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("a staging candidate's target changes can be compared with a build in its own folder", async () => { + const originalFetch = globalThis.fetch; + const requested: string[] = []; + const progressUrl = stagingResolveUrl(`runs/${LOCAL_CANDIDATE_RUN}/progress.json`, "uk"); + // Every repository read fails, so loading stops at its first read. + globalThis.fetch = (async (input: string | URL | Request) => { + requested.push(String(input)); + return new Response(null, { status: 503 }); + }) as typeof fetch; + try { + const failure = await loadStagingTargetChangeDataset( + LOCAL_CANDIDATE_RUN, + DENSE_NEWER_BUILD, + "uk", + ).then(() => null, (error: unknown) => error); + // The build is accepted as the release to compare with: loading starts + // with the candidate's progress file and stops at the stubbed failure. + expect(failure).not.toBeInstanceOf(InvalidReleaseIdError); + expect(String(failure)).toContain("Staging fetch failed 503"); + expect(requested).toEqual([progressUrl]); + + // A path below a build folder is still refused before any read. + requested.length = 0; + await expect( + loadStagingTargetChangeDataset(LOCAL_CANDIDATE_RUN, `${DENSE_NEWER_BUILD}/extra`, "uk"), + ).rejects.toBeInstanceOf(InvalidReleaseIdError); + expect(requested).toEqual([]); + } finally { + globalThis.fetch = originalFetch; + } +}); diff --git a/frontend/packages/calibration-tree/src/test-support/releases-record-responses.ts b/frontend/packages/calibration-tree/src/test-support/releases-record-responses.ts new file mode 100644 index 00000000..e4262999 --- /dev/null +++ b/frontend/packages/calibration-tree/src/test-support/releases-record-responses.ts @@ -0,0 +1,22 @@ +// Hugging Face's answers to a request for `releases.json`, for the synthetic +// repositories in tests. A dataset repository that has no `releases.json` +// still publishes through its tags and pointer files; Hugging Face then +// answers 404 with the error code `EntryNotFound`. A 404 whose error code +// says the repository or the revision is missing is a different answer: the +// readers must not take it to mean that the repository has no record. + +/** The 404 for a file the revision does not have: no `releases.json`. */ +export function missingReleasesRecord(): Response { + return new Response("Entry not found", { + status: 404, + headers: { "X-Error-Code": "EntryNotFound" }, + }); +} + +/** The 404 for a revision the repository does not have. */ +export function missingRevision(): Response { + return new Response("Revision not found", { + status: 404, + headers: { "X-Error-Code": "RevisionNotFound" }, + }); +}