diff --git a/README.md b/README.md index defa5591a5..18d9331fb8 100644 --- a/README.md +++ b/README.md @@ -418,6 +418,10 @@ including Hypothesis properties) run in the normal `uv run pytest` suite. ## Releasing & alerts +[The release contract](docs/release-contract.md) (C1 to C5) says what the +release validator, the publication commands and the loaders enforce today, and +what version 1 (ARCH-1, cos d1160) asks of every country's releases. + The [native SPM role source-enrichment lane](docs/us-native-spm-role-source-enrichment.md) creates a new US H5 from the exact reviewed BuildP parent, preserves its original variables and schema-5 calibration evidence, and requires fresh country/wrapper diff --git a/changelog.d/1285-release-contract.added.md b/changelog.d/1285-release-contract.added.md new file mode 100644 index 0000000000..514c2edaad --- /dev/null +++ b/changelog.d/1285-release-contract.added.md @@ -0,0 +1,3 @@ +`docs/release-contract.md` puts the release contract on paper (ARCH-1, cos d1160): the end state, the releases in service on 2026-10-15, and contracts C1 to C5 (release manifest and certification, loader compatibility, staging and run outcome, the Logbook, publish and registry), each as the code enforces it on 2026-11-12 and as its version 1 would, with how far each milestone had got by that date. C5 version 1 takes the build-folder shape in which main already publishes every UK and US build: `releases///`, `releases.json` and `microcosm-publish-release-build`. The document says how C1 version 1 keys by declared country instead of release-name strings, records where the recertification lane and C2 version 1 disagree, carries microcosm#378's parity rule, and replaces the branch-only `us-uk-release-path.md`. It changes nothing that publishes. + +`tools/generate_release_contract_fixtures.py` writes version 1 of the contract's golden fixtures under `packages/microcosm-data/tests/fixtures/release_contract/v1`, following the staging-fixture pattern. For C1 it freezes one build folder's manifests for the UK national release and for the US national release, each from that country's own writer, and an inventory of what the contract requires of the UK national release. For C5 it freezes one `releases.json` for each country's repository, built with the emitter interface's own changes, and a registry snapshot. `writers.json` names the writer of every file `SHA256SUMS` lists, `SHA256SUMS` pins every byte, and `--check` fails when a regeneration differs. The UK national assembler's manifest construction moves into `uk_national_release_manifests`, a pure function the generator also calls; the assembler writes the same bytes as before. diff --git a/changelog.d/1285-uk-exact-k-id-minting.removed.md b/changelog.d/1285-uk-exact-k-id-minting.removed.md new file mode 100644 index 0000000000..000a44ffd5 --- /dev/null +++ b/changelog.d/1285-uk-exact-k-id-minting.removed.md @@ -0,0 +1 @@ +Retire `format_uk_release_id`, `UKReleaseIdentity` and `apply_uk_release_identity` from `microcosm.build.uk_runtime`: they minted `populace-uk---k` ids and had no caller. Version 1 of the release contract (`docs/release-contract.md`, C1, planned for M3) renders a new release's name, `microcosm---`, from the identity its manifest declares. The UK release names and the tier vocabulary stay, and the release contract still validates existing exact-k ids. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index b4cf5c74b0..8ebeb09ad8 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -341,6 +341,20 @@ HF_STAGING_READ_TOKEN= bash tools/run_integration_tests.sh ## The PR-CI / certification boundary +[The release contract](release-contract.md) (C1 to C5) states what the release +validator, the publication commands and the loaders enforce today, and what +version 1 (ARCH-1, cos d1160) asks of every country's releases. Change it, its +golden fixtures (`tools/generate_release_contract_fixtures.py`) and the code +that enforces it in the same pull request. The US national golden freezes the +manifests that the US fiscal-refresh tool's `_build_manifests` writes when it +gets only its required arguments and a staging block: an empty `timing`, a null +`ledger_artifact` and only the four gate entries that the function always +writes. A real build adds its own timing, its ledger provenance and the +optional gate blocks its run produces, and the golden freezes none of them. A +pull request that changes what `_build_manifests` always writes, such as +`US_RELEASE_GATE_EVIDENCE_FILES` or `US_DOCUMENTED_ABSENT_INPUTS`, or the +layout that `rewrite_release_dir` gives it, regenerates the fixtures too. + PR CI never receives external writer credentials or touches restricted microdata. Same-repository runs may receive the optional read-only `HF_STAGING_READ_TOKEN` in the `integration-uk` job; fork pull requests receive diff --git a/docs/release-contract.md b/docs/release-contract.md new file mode 100644 index 0000000000..c37c00bb58 --- /dev/null +++ b/docs/release-contract.md @@ -0,0 +1,1398 @@ +# The release contract + +What a Microcosm release must be before anyone may serve it, for every country. +Max ruled ARCH-1 yes on 2026-10-15 (cos d1160), adopting the end state below, +in which publishing refuses non-conforming releases from 2026-11-06. This +document states that end state and the five contracts, C1 to C5: each as the +code enforces it today, and each one's version 1. For C1 to C4, version 1 is +the requirement the 2026-10-09 plan adds. For C5, version 1 is the build-folder +shape the UK national line ships today, because d1160 froze the contract at the +UK national shape. Main already publishes, in that shape, every release that +`publishes_to_build_folder` names, so C5's version 1 lists what main still +lacks. + +Nothing here refuses anything. This document, its golden fixtures and their +tests describe and freeze; they do not change what publishes. Each "today" +statement below comes from reading the code at main's 6c64038f3 +(2026-11-12, the merge of microcosm#1583), or from executing against it, and +cites the function that does the work; statements about policyengine.py and the +Hub carry the date of their reading. The golden fixtures, their generator and +their tests arrive with this document, and so does one function named below: +`uk_national_release_manifests` returns the two manifest dictionaries that the +UK national assembler's `_stage_and_finalize` built inline at 6c64038f3. Unless +it says otherwise, each version-1 statement of C1 to C4 is a requirement the +code does not enforce on 2026-11-12. Beside each, this document names the +milestone the plan assigns it to, and the +[enforcement timeline](#enforcement-timeline) records how far each milestone +had got by that date. + +The ruling set 2026-11-06 for publishing to start refusing. On 2026-11-12 both +publication commands, `microcosm-publish-release-build` and the tagged +publisher `microcosm-publish-release`, refuse a build that fails today's C1 +(`validate_release_dir`, or its evidence sibling) or that recorded staging it +never delivered (today's C3, `publication_refusal`). Max decides when the +version-1 refusals of C1 to C4 start. + +This document replaces `docs/us-uk-release-path.md`, a planning snapshot that +never reached main. The snapshot's last version (363a9033b, 2026-09-15) lives +on the graph-native branches. Decision cos d1161 closed the five pull requests +on those branches (#1011, #995, #996, #999 and #1002) on 2026-10-15 and kept +the branches. Two of the snapshot's rules carry over: record every reference +period explicitly instead of inferring it from a filename (C1's declared +identity below), and make every dashboard and release verdict refer to the same +candidate bytes (C1's digest bindings). + +## The end state + +- **One producer per country.** Each country builds one population on + `run_graph` and derives every published size from it by selection on one + target register. +- **One release contract.** Every release passes C1 to C5, frozen at the shape + the UK national line ships. Each build sits in its own folder, + `releases///`. The repository's `releases.json` records + every build and names each release's current one. Only + `microcosm-publish-release-build` publishes a build, and only that command + makes one current (`--promote`, or `--make-current` at publication). Since + microcosm#1571 merged on 2026-11-11, the UK national, dense and local-area + releases and the five US releases publish only this way. +- **One registry.** `microcosm.data.registry` names every file any consumer + serves, and policyengine.py's bundle mirrors it. +- **Publishing refuses** any release that does not conform (from 2026-11-06, in + the ruling). +- **Retired:** the incumbent UK data package (uk-data), the Build P patch + lanes, the second US calibration driver and staging version 1. + +The plan that gets there, with owners and dates, is the 2026-10-09 systems +report that cos d1160 cites (Max's planning record, not in this repository; +milestones M0 to M7). This document is M0's deliverable. +[Enforcement timeline](#enforcement-timeline) lists the milestones that change +what the contract enforces. + +## Releases in service on 2026-10-15 + +The table records what three sources said on 2026-10-15: policyengine.py's +bundle 6.4.3 (`src/policyengine/data/bundle/manifest.json` at d74ddc713), the +public `policyengine/populace-us` Hub repository and `microcosm.data.registry`. +The last row names its own source. + +| Grain | Served release | Producer | Met the contract on 2026-10-15? | +| --- | --- | --- | --- | +| US national (policyengine.py and `latest.json`) | `populace-us-2024-spm-20260915` | A source enrichment of a parent release (its manifest declares `release_type: source_enrichment` and ships the parent's manifests); the 2026-10-09 report traces the parent to Build P | No: a separate source-enrichment contract, no certification, no Logbook row | +| US state and district (policyengine.py `regional_release_manifest_uri`) | `populace-us-2024-buildo-acs-local-767312d60-20260923T074941Z` | `tools/build_us_acs_local_release.py` | No: not in the registry, no staging, no Logbook row | +| US candidate (tag only) | `populace-us-2024-0fb05b6-4b57d15a287c-20260930T150401Z` (Route A) | `tools/route_a/` then the fiscal-refresh tool | No: 16 gates in an ad hoc `gates` dict, staging `{"enabled": false, "reason": "--no-staging"}`, no certification | +| UK, PolicyEngine app | uk-data 1.58.1, `enhanced_frs_2024_25` | the incumbent UK data package (uk-data) | Not a Microcosm release; certified for policyengine-uk 2.130.1 on the `legacy_compatible_model_package` basis | +| UK, `microcosm.data.resolve("uk")` | `populace_uk_2023.h5` (the June 2023 file) | none current | Grandfathered id | +| UK national line | `latest-national.json` named `microcosm-uk-2024-25-national` at a per-cut tag: the 2026-10-09 report's copy of the pointer, updated 2026-10-04, carries the tag `microcosm-uk-2024-25-national-20261002T230158Z-5c6b3f68`. This document holds no reading of the private UK repository from 2026-10-15 | `microcosm-build-uk` on `run_graph`, then `tools/certify_uk_release_cut.py` and `tools/assemble_uk_release_dir.py` | The assembler refused to write a cut that failed C1 as the code enforced it that day, and line promotion ran that day's C5 guards. It lacked what no producer wrote: C1's declared identity, C3's run-outcome binding and C4's Logbook binding | + +So three producers served three datasets, and microcosm's own registry pointed +the UK default at a fourth file. + +No row of the table carries a check later than 2026-10-15. Main has since +changed what the registry names and how the loader reaches it: + +- On 2026-11-02 microcosm#1432 made the UK 2024-25 national line the UK 2025 + default load. Its registry entry became `("uk", 2025, "compact")`, so + `microcosm.data.resolve("uk")` resolves to the national line, and the June + 2023 file stays at `("uk", 2023, "compact")`. +- microcosm#1505 (merged 2026-11-05), #1537 (merged 2026-11-09) and #1571 + (merged 2026-11-11) gave every registry entry a release: + `microcosm-uk-2024-25-national`, `microcosm-uk-2024-25-dense`, + `populace-uk-2023` (the June 2023 build's release, which + `publishes_to_build_folder` leaves out, so it takes no new build in a build + folder) and `microcosm-us-2024-national`. New US national builds declare + `microcosm_us_2024.h5`, and the entry also accepts `populace_us_2024.h5`, the + name that the builds published under tags carry. +- For every entry, the loader (`_resolve_certified_release`) reads the + repository's `releases.json` and loads the release's current build, or a + listed build that `build=` pins, from `releases///`. It + follows the entry's pointer file (`latest.json` or `latest-national.json`) + only where the repository has no `releases.json`. +- The registry names no entry for the other four US releases or for any UK + local-area release, so `microcosm.data.load` reaches none of them. +- The US tools now write builds of standing releases. The fiscal-refresh tool + (`tools/build_us_fiscal_refresh_release.py`) writes builds of + `microcosm-us-2024-national` (or of `microcosm-us-2024-evidence`), and + `tools/build_us_acs_local_release.py` writes builds of + `microcosm-us-2024-local`. + +Main's README says, on 2026-11-12, that the UK and US Hub repositories have +both switched to `releases.json`. This document has not read either +repository. + +## The five contracts + +| | Contract | Freezes | Enforced today by | Golden fixture | +| --- | --- | --- | --- | --- | +| C1 | Release manifest and certification | The release directory's files, both manifests, and a certification that the certifier composes from gate-battery reports | `validate_release_dir` (`microcosm/data/contract.py`), which `prepare_build_folder_release` runs before every build-folder publication; a build of `microcosm-us-2024-evidence` answers to `validate_evidence_release_dir` instead | `v1/c1/` | +| C2 | Loader compatibility | One rule admitting a model and Core version against a release | `microcosm.data.loader` and policyengine.py, separately | none | +| C3 | Staging telemetry and run outcome | How a build records and delivers its end | `publication_refusal` (`microcosm/data/publish_cli.py`), through `_staging_undelivered`, in both publication commands | the staging fixtures | +| C4 | Logbook | One durable row per terminal build attempt | nothing at publication | none | +| C5 | Publish and registry | The build-folder layout, `releases.json`, release names and the registry | `microcosm-publish-release-build` (`publish_release_build` and `promote_release_build` in `microcosm.build.release_publication`), `prepare_build_folder_release`, `publishes_to_build_folder`, the emitter's release writer, `parse_releases_record` and `microcosm.data.registry` | `v1/c5/` | + +### C1: the release manifest and certification + +#### Today + +`validate_release_dir(release_dir)` holds the certified release contract. Every +command that publishes a build runs it, or its evidence-tier sibling +`validate_evidence_release_dir`, before it hands over a file. +`microcosm-publish-release-build` runs it through +`prepare_build_folder_release` for every build it publishes except a build of +`microcosm-us-2024-evidence`, which answers to the evidence contract instead. +Before it validates anything, the tagged publisher's `prepare_release` refuses +any release that publishes into build folders. Promotion +(`microcosm-publish-release-build --promote`, through `promote_release_build`) +uploads no file and runs no contract: it reads the release and the build that +the local release manifest names. + +The validator reads the release's name from the directory. For a release that +publishes each build into its own folder, the directory carries the release's +name, such as `microcosm-us-2024-national`. `publishes_to_build_folder` lists +those releases: the UK national, dense and local-area releases and the five US +releases in `US_RELEASES`. For a build in the tagged layout the directory +carries the build id, such as `populace-us-2024--`. Before it +dispatches, the validator refuses two kinds of misplaced build. +`_refuse_misplaced_annual_years` refuses a build-folder build that declares +annual years outside `microcosm-us-2024-annual`, and a build of that release +that declares none. `_refuse_a_receipt_donor_that_is_not_an_enrichment` +refuses a build of `microcosm-us-2024-receipt-donor` that declares any release +type but a source enrichment. The validator then dispatches in three steps: + +1. **Release type.** The validator reads `release_manifest.json`'s + `release_type`. It hands two types to separate contracts and returns. + `source_enrichment` goes to `validate_source_enrichment_candidate`, the + Build P inheritance path; the served US default on 2026-10-15 was one of + these. That contract accepts a build in either layout. + `compatibility_recertification` goes to `validate_recertification_candidate` + (`microcosm/data/compatibility_recertification.py`, merged 2026-10-23), the + contract for a build of `microcosm-us-2024-national` that republishes a + published US calibration build's bytes under a newer policyengine-us. The + child always sits in a build folder. It names its parent by release and + build, or by build id and tag for a parent that kept only its tag. An absent + `release_type`, or `calibration`, means a calibration build; the validator + refuses any other value. When the manifest declares an annual-projection + extension, `validate_annual_projection_extension` checks it next. +2. **Dataset role.** `dataset_role` is `national_default` (also when absent) or + `non_default_local_area`. A local-area release goes to + `_validate_local_area_release_dir`, or to `_validate_uk_dense_release_dir` + when its name is the UK dense release's. +3. **The release name.** Everything else keys on the directory name: + - `required_release_files(release_id)` adds `us_source_coverage.json` for a + US release, `terminal_gates.json` for a UK exact-k id + (`populace-uk---k`), and `release_certification.json` for + the literal `microcosm-uk-2024-25-national`. `is_us_release` decides the + first: it accepts the five `US_RELEASES` names and any `populace-us-` + build id. For any other name `required_release_files` returns the three + base files: `build_manifest.json`, `release_manifest.json` and + `calibration_diagnostics.json`. The UK dense and local-area names are + among them, but step 2 sends a build in the local-area role to its own + validator and file list first (`_UK_DENSE_REQUIRED_RELEASE_FILES`, + `LOCAL_AREA_REQUIRED_RELEASE_FILES`). Whatever the name, the validator + skips `calibration_diagnostics.json` when the release manifest records + failed diagnostics generation (`calibration_diagnostics.status: failed`, + which `_calibration_diagnostics_required` reads). + - `_expected_model_package(release_id)` names `policyengine-us` for a US + release and `policyengine-uk` for any name that starts `microcosm-uk-` or + `populace-uk-`. For any other name it returns `None`. The checks then skip + the build manifest's model-package runtime pin and the + `compatible_model_packages` list, and they do not check which package + `built_with_model_package` names (it still needs a non-empty name and a + resolved version). + - `publishes_to_build_folder(release_id)` chooses how both manifests name + the build. + - The US critical-target fit, stored-input evidence, source-coverage and + dataset-file checks fire on `is_us_release`; the UK identity checks fire + on the `populace-uk-` prefix and the exact-k pattern. + +Whatever the name, a `calibration` build in the national-default role must +carry: + +- **`build_manifest.json`**: `code` with `repository`, a 40-character + `git_commit` and `git_dirty: false`; `runtime` with resolved `python`, + `policyengine-core` and, when the name implies a model package, that + package's versions; `dataset` and `calibration` with filenames and SHA-256s, + the calibration naming its target surface and registry; and a `gates` object + (`_check_build_manifest`). In the build-folder layout it also carries + `release` equal to the directory name and `build`, the build's name, and + none of the retired fields `build_id`, `attempt_id` and `cut_tag` + (`_check_build_folder_identity`). The build's name must match the emitter + interface's identifier rule (`_SAFE_IDENTIFIER_RE`): a letter or digit, then + up to 127 letters, digits, dots, underscores or hyphens. In the tagged + layout it carries `build_id` equal to the directory name instead. +- **`release_manifest.json`**: `schema_version` 1 + (`RELEASE_MANIFEST_SCHEMA_VERSION`) in both layouts; a non-empty + `compatible_core_packages` list that includes the built Core version and, + when the name implies a model package, a non-empty + `compatible_model_packages` list that includes the built model version; + `data_package`; and `default_datasets.national` naming a `microdata` + artifact (`_check_release_manifest`). In the build-folder layout it also + carries: + - `release` and `build` as in the build manifest, and + `_check_build_folder_builds_agree` refuses two manifests that name + different builds; + - `built_at`, `built_with_core_package` and `built_with_model_package` at + its top level (`_check_build_folder_release_details`); + - `artifacts`, each with `kind`, a bare file name as `path`, `repo_id`, + `sha256` and `role`, and no `revision` (`_check_build_folder_artifacts`). + `release_artifact_role` fixes the role: `dataset` for the microdata, + `calibration_weights` for the weights, and otherwise the artifact's key. + + A new US build in a build folder declares exactly one microdata file, its + release's (`US_RELEASE_DATASET_FILES`; `microcosm_us_2024.h5` for a national + build); the validator holds no tagged `populace-us-` build to that name. An + annual build declares its base build's H5 and one H5 for each projected year + instead (`_check_us_release_dataset_file`, `_check_us_annual_dataset_files`). + In the tagged layout the release manifest carries `build.build_id` equal to + the directory name, `build.built_with_core_package` and + `build.built_with_model_package`, and `artifacts` each with `kind`, `path`, + `repo_id`, `revision` and `sha256`, all pinned to one revision. + +A build folder's two manifests therefore differ from the tagged ones in four +ways. They name the release and the build as two strings, where the UK +national line's tagged `build_id` held the release's name and `attempt_id` and +`cut_tag` named the build. The release manifest records the build's details at +its top level. Each artifact carries its role. No artifact pins a revision, +because `releases.json` and the folder locate a build's files. Both layouts +carry `schema_version` 1, and `publishes_to_build_folder` tells them apart. A +build that the switch tool (`microcosm.build.build_folder_switch`) moved from +its tag also carries `migrated_from`, which names the tag, its commit and the +SHA-256 of the manifest the tool rewrote. + +Several writers produce the build-folder manifests on main. The UK national and +dense assemblers build both dictionaries themselves and run +`validate_release_dir` before they move the directory into place. The US +fiscal-refresh, ACS-local, source-enrichment and recertification tools build +tagged-shape manifests in a directory named after the release and then call +`rewrite_release_dir` (`microcosm.data.build_folder_manifests`), which rewrites +both manifests in place. The US annual assembler copies its base build's two +manifests, changes `release` and `build` in both, drops `migrated_from`, and in +the release manifest adds the annual metadata and an artifact for each file the +projection adds. The switch tool rewrites the manifests of the builds it moves. + +The **certification** is UK-only. The validator requires +`release_certification.json` of `microcosm-uk-2024-25-national`. Whatever its +name, the validator also refuses a calibration build in the national-default +role when its directory carries a `release_cut_gates.json`, or a +`terminal_gates.json` whose `posture` is `calibration_seam`, and no +certification. `_check_uk_release_certification` then requires exactly the +certification's sixteen fields. They include the integer `schema_version` 2, +`kind: uk_release_certification`, `country: uk`, the release id, the parent +spine's digest, and three records: `reference`, `since_baseline` and `parts`. +The `reference` names the build of `microcosm-uk-2024-25-national` that the +certifier compared the cut with: its build, file name, digest and built-with +policyengine-uk version, and whether the cut took the current build or a pinned +one. The `since_baseline` record states what changed since a fixed national +baseline build (`_check_uk_certification_since_baseline`). The `parts` number +exactly three: `spine`, `calibration_seam` and `release_cut`. Each part's +scoped spec digests must match the pins in `contract.py`, and every gate in its +scope must have passed: its `statuses` must equal +`{"passed": }`. The document must also say +`shippable: true` and carry, in `spec`, the full gate spec's digests, which +must match the committed full-manifest pins. One HMAC-SHA256 attestation covers +the whole document, under the key in `MICROCOSM_UK_TERMINAL_GATE_SIGNING_KEY`. +The validator accepts only a key that `microcosm.data.gate_signing_keys` +registers for verification (microcosm#1405, merged 2026-11-09), and the +attestation names that key by its SHA-256. The certification's parts carry no +signatures of their own; each part report beside it carries one, which +`compose_uk_release_certification` verifies before it signs. +`_check_uk_certification_evidence_binding` binds each part's report file in the +release directory (`spine_gates.json`, `terminal_gates.json`, +`release_cut_gates.json`) and the score receipt (`score_vs_reference.json`) to +the signed digests. Schema 2, the reference and the baseline record reached +main with microcosm#1574, merged 2026-11-11. On the national line, a +shippability verdict lives only in the certification. + +#### The id-string keying, and how C1 version 1 keys by declared country instead + +Every country-specific check hangs off the release name. Two consequences +follow, and `test_release_contract_keying.py` executes the id keying behind +both: + +- **A new country fails open.** An NZ, BE or AM release, or a US release of + another vintage such as `microcosm-us-2025-national`, gets only the three + base files and no model-package expectation: no certification, no source + coverage, no `compatible_model_packages` check. It validates against the + weakest contract by default. +- **No other country can publish into a build folder.** + `publishes_to_build_folder` names only the UK national, dense and local-area + releases and the five US releases. `microcosm-publish-release-build` refuses + any other name, for publication and promotion alike: its `main` checks + `publishes_to_build_folder` before anything else, and `build_folder_identity` + refuses the same names inside `publish_release_build` and + `promote_release_build`. So only the tagged publisher accepts a new country's + release. `line_for_release_id` still knows only + `microcosm-uk-2024-25-national` and `microcosm-uk-2024-25-local-k`. Its + remaining callers serve pointer files: `latest_line_release`, which the + loader's pointer reader calls, and `line_pointer_payload`, which no publisher + calls. + +The registry also disagrees with the name about the year. The registry files +the UK national release under `("uk", 2025, "compact")`, the UK 2025 default +load since microcosm#1432 (2026-11-02), while its name says `2024-25`; the +entry's `release` field carries that name. `test_release_contract_keying.py` +pins the mismatch. Until microcosm#1432, the live-loader test in +`test_loader.py` required every resolved release id to start with +`microcosm---` (or the `populace-` form), which the national +release's name cannot match; microcosm#1144 reported the failure from a live +run. On 2026-11-12 the test requires a release that the loader reads through +`releases.json` to carry the registry entry's release name exactly, and +requires a release that the loader reaches through a line pointer only to start +with `microcosm--`. + +#### Version 1, planned for M3: dispatch on the declared country + +Schema 1 covers two layouts on 2026-11-12. microcosm#1505, #1537 and #1571 +moved the UK and US releases to the build-folder layout without a schema +bump, so a tagged manifest and a build-folder manifest both carry +`schema_version` 1, and only `publishes_to_build_folder` tells them apart. +Version 1 keeps the schema number as the trigger: a manifest's +`schema_version` says which rules apply to it. Rules that keyed on which +fields a manifest happens to carry would let a half-declared manifest pick its +own rules. The bump to schema 2 lands with the pull request that adds the +declared identity below, and from then the build-folder writers emit 2. + +C1 version 1 dispatches on what the manifest declares instead of on its name: + +1. **Release manifest schema 2** keeps the build-folder layout and adds a + declared identity, required on every new build: + + ```json + { + "schema_version": 2, + "release": "microcosm-uk-2024-25-national", + "build": "", + "country": "uk", + "vintage": "2024-25", + "line": "national", + "dataset_role": "national_default", + "producer": {"tool": "tools/assemble_uk_release_dir.py", "commit": "<40-hex>"} + } + ``` + + `dataset_role` stops being optional. `producer` closes the gap that left + Build P's producer an inference: no manifest has a field that names its tool + today. A calibration build's `code` block records the repository and the + commit, and a source enrichment's or a recertification's also hashes its + producer's files (`code.source_files_sha256`). The plan has US builds record + `producer` at M2, and schema 2 requires it of every new build. +2. **One country table in the data shard** replaces the name tests. Each + registered country declares its model package, the files its releases add to + the C1 base set (the US adds `us_source_coverage.json` and the stored-input + evidence; every country adds its certification part reports), its + country-specific checks (the US critical-target fit, stored-input, + source-coverage and dataset-file checks; the UK identity, diagnostics and + gate-report checks), the lines it may publish, and its Hub repository. For + each line the table gives the role its release takes in `releases.json` + and the dataset file a build declares, as `US_RELEASES` and + `US_RELEASE_DATASET_FILES` do for the US today. Every check that keys on a + name today reads the table through the declared country instead: + `required_release_files`, `_expected_model_package`, `is_us_release` and + `publishes_to_build_folder`, and also each exact-k and constant-name test. + On 2026-11-12 a scan of the syntax tree counts 59 such calls and + comparisons in `contract.py` and 13 in `release.py`. `loader.py` holds + none, and `compatibility_recertification.py`, `source_enrichment.py`, + `annual_projections.py` and `build_folder_manifests.py` hold more. + `line_for_release_id` leaves with the pointer reader instead. A schema-2 US + build then cannot skip the US checks by choosing another name. +3. **Unknown countries fail closed.** The validator refuses them instead of + falling back to the base set. The plan registers NZ before the switch to + version 1, because cos d962's late-November deliverable depends on it. A new + country's release joins `publishes_to_build_folder` and the registry in the + pull request that authorizes its first publication (see C5 version 1). +4. **The validator derives the name instead of parsing it.** A schema-2 release + name must equal `microcosm---` rendered from the + declared fields, and the directory name must equal it. `` comes from + the country's closed list in the table, which registers each line by exact + name; C5 version 1 lists the lines in service. Under version 1 nothing reads + meaning out of the name string. `releases.json` carries no country, vintage + or line, because the emitter interface fixes its keys. So the loader checks + the fetched manifest's declared `country`, `vintage` and `line` against the + registry entry before it loads (planned; no loader does this on 2026-11-12). +5. **One vintage string.** The registry entry carries the vintage string, + and the loader compares the manifest's `vintage` with it exactly, which + removes the `2025` versus `2024-25` mismatch. +6. **Grandfathering is a frozen list of published builds.** Schema-1 + manifests keep today's name-keyed dispatch only for the (release, build) + pairs that each repository's `releases.json` lists at the switch to + version 1, and for tagged builds that never moved into a folder. The list + cannot hold release names alone, because a release keeps one constant name + across builds, so a name-only list would grandfather every future build. + `microcosm-publish-release-build` refuses a new schema-1 build. + +#### The frozen shape + +C1 freezes what the UK national release ships today: one build folder, +`releases/microcosm-uk-2024-25-national//`. A conforming national build +carries: + +- `build_manifest.json` and `release_manifest.json` in the shape of + [`v1/c1/microcosm-uk-2024-25-national/`](#golden-fixtures), which + `uk_national_release_manifests` in `tools/assemble_uk_release_dir.py` builds; +- `calibration_diagnostics.json`; +- `release_certification.json`, which the release-cut certifier + (`tools/certify_uk_release_cut.py`, through + `compose_uk_release_certification`) composes from the gate battery's signed + part reports; +- every part's report file and the score receipt that compares the cut with its + reference build, each of which the certification binds by digest. + +The UK dense and local-area releases carry no certification today +(`_UK_DENSE_REQUIRED_RELEASE_FILES` and `LOCAL_AREA_REQUIRED_RELEASE_FILES` +name none), and the plan has not said whether they will; C5 version 1 states +the open question for the dense line. + +The 2026-10-09 report's plan brings the US to this shape by adapter at M2: the +fiscal-refresh tool declares its gates in `us/gates.json`, projects its own +verdicts through the gate battery under `BlockingMode.MARKS_ARTIFACT`, and +composes the certification from the projected reports. It projects; it does not +re-evaluate. On 2026-11-12 neither `us/gates.json` nor that adapter exists, and +no US build carries a certification. The US national golden, +[`v1/c1/microcosm-us-2024-national/`](#golden-fixtures), therefore freezes +the two manifests the US fiscal-refresh tool writes today for a run that +passes `_build_manifests` only its required arguments and a staging block. A +real build adds blocks that the golden does not freeze. The validator asks +no certification of a US build, so that golden freezes a shape, not a +conforming release. +`test_us_fiscal_refresh_builder.py` and +`test_support/microcosm_data/release.py` (through +`_as_us_national_build_folder_release`) also pin the US national build folder +that `microcosm-publish-release-build` accepts. + +### C2: loader compatibility + +#### Today: two rules + +**microcosm.data's loader.** `_package_certification` reads +`compatible_model_packages` and `compatible_core_packages` from the release +manifest, in either layout. It keeps each entry that names the package and +refuses a specifier that PEP 440 cannot parse. It then refuses the release +unless an entry remains and the built version satisfies one of them. It reads +the built version from a build-folder manifest's top level and from a tagged +manifest's `build` object. At load, `_enforce_package_compatibility` refuses +unless the installed model package and the installed `policyengine-core` each +satisfy one of their specifiers. Only `load` runs that check: `download`, +`resolve_certified` and `download_certified` read and verify the same manifest +and leave the installed versions alone. + +**The release validator.** `_check_release_manifest` runs +`_check_compatible_package_entries` on every build with the national role, +whatever its `release_type`: calibration builds, the evidence tier, source +enrichments and recertifications, tagged or in a build folder (where +`_check_build_folder_release_details` runs it). For a release name to which +`_expected_model_package` assigns no package, such as a new country's, the +check skips the model list and still checks the Core list. The local-area +contract runs it on neither list: `_check_local_area_release_manifest` passes +`compatible_packages=False`, so for a local-area or dense build only the loader +checks them. The check requires a non-empty list, a name and a valid specifier +on each entry, an entry for the package, and the built version inside one of +its specifiers. An entry may declare `basis: publisher_claim` with a +`declared_by` naming who made the claim; an entry without a basis records what +the build measured. The check does not require an entry wider than the built +version to declare that basis, and it accepts a Core range. + +For source enrichments (the served US default on 2026-10-15), +`validate_source_enrichment_candidate` already asks for more. Each list must +be the exact pin `=={version}` unless the certified report declares a +publisher claim. The validator accepts a claim only as +`compatibility_claim_entry` builds it: it names its declarer, contains the +tested version, and has bounds above and below. Core always takes an exact pin +("no producer can declare a Core range", `source_enrichment.py`). + +A `compatibility_recertification` child is a new build of +`microcosm-us-2024-national`. Once its compatibility has passed, +`validate_recertification_candidate` requires both lists to equal what +`claim_entries` builds. `claim_entries` returns every entry of the parent plus +one model claim, which the same `compatibility_claim_entry` builds for the +policyengine-us version the child tested. When no parent entry covers the +tested Core, it adds an exact pin of that Core with `basis: publisher_claim`. A +pending child carries its parent's lists unchanged. +`_check_recertification_claim` narrows the model claim to `==T`, the tested +version, or to `>=L,_packages` entries for that package. The manifest must + carry at least one such entry, and each specifier must parse under PEP 440. +2. **Exact pins and claims.** An exact pin is an entry whose specifier is + exactly `==V` or `===V`, with no wildcard, where + `Version(V) == Version(built)` (PEP 440 equality, any local label included, + as in rule 4). Every other entry is a claim. It must declare + `basis: publisher_claim` and a `declared_by`, must contain the built + version, and must have bounds above and below. `compatibility_claim_entry` + applies the same tests today, except that it asks for the tested version, + which on a source enrichment is the built one. +3. **Core.** `policyengine-core` takes exact pins only. Claims apply to the model + package alone, as on the source-enrichment path. +4. **Admission.** A loader admits the installed version when + `Version(installed) == Version(built)`, PEP 440 equality with any local label + included, or when it satisfies a claim. Containment in an exact pin alone is + not enough, because `2.0.0+local` satisfies `==2.0.0`. Otherwise the loader + refuses the pair. +5. **Basis.** A loader names the basis `built_with_model_package` for the first + case and `publisher_claim` for the second, and attributes the second to the + first matching claim in manifest order. +6. **Legacy manifests.** Both loaders keep today's rule for a schema-1 + manifest, which every loadable release published before C1 version 1 + carries, and apply rules 1 to 5 to schema-2 manifests. (The evidence tier + writes `1-evidence`, which microcosm.data's loader refuses.) Adopting C2 + version 1 therefore changes no load of an already published release, + including the registry's UK default and the releases policyengine.py's + bundle pins, whatever their entries say. + +Every build that `microcosm-publish-release-build` publishes today carries +schema 1, except a build of the evidence release, which carries `1-evidence` +and which microcosm.data's loader refuses. So until C1 version 1 publishes the +first schema-2 manifest, the loaders' half of this rule changes no load, and +rules 2 and 3 tighten the release validator from M2. + +Rules 2 and 3 tighten `_check_compatible_package_entries`, which today accepts +a wider entry without a basis and a Core range on every national-role build. +Rule 4 tightens both loaders: microcosm.data's admits any installed version an +entry contains, and policyengine.py's admits any version a claim's specifier +covers. + +**Gap: local-area and dense builds.** Version 1 has one publication rule for +every role. A local-area or dense build declares its compatible packages like +any other build, and the validator checks both lists under rules 1 to 3. On +2026-11-12 `_check_local_area_release_manifest` checks neither. C2 version 1 +closes the gap at M2, with the rest of the rule (owner: anth-volk). + +**Open: the recertification lane.** The `compatibility_recertification` lane +(microcosm#1366, merged 2026-10-23; since microcosm#1571 its children are +builds of `microcosm-us-2024-national`) writes entries that rules 2 and 3, as +written, refuse: a model claim that does not contain the built version, since +the parent's own entries already cover that one, and, when no parent entry +covers the tested Core, an exact pin of that Core with +`basis: publisher_claim`. The release validator meets them first. +`validate_recertification_candidate` runs `_check_release_manifest`, which +reaches `_check_compatible_package_entries` through +`_check_build_folder_release_details`. Rules 2 and 3 tighten that check. A +loader meets them only when a caller loads a child with `build=`, since the +publisher never makes a recertification current. Under rule 6 it then applies +rules 1 to 5 only to the child of a schema-2 parent, because the lane keeps a +child's `schema_version` equal to its parent's. C1 version 1's schema-2 +requirement meets the same lane: `_check_release_manifest` compares the child's +schema version with `RELEASE_MANIFEST_SCHEMA_VERSION`, so once that constant +becomes 2, the child of any schema-1 parent fails either that check or the +lane's own equality check. The source-enrichment lane meets the bump too: +`validate_source_enrichment_candidate` requires `schema_version` 1 and runs the +same `_check_release_manifest`, so no source enrichment passes once the +constant becomes 2. Before M2 tightens the validator, either the rules exempt +the recertification lane or that lane changes; the plan does not yet say which. + +**Open: policyengine.py's qualified exact pair.** The `qualified_exact_pair` +basis admits a model and Core pair that the manifest neither built with nor +claims, on policyengine.py's own qualification ledger. Rules 4 and 5 have no +such case. Either version 1 names it as a consumer-side basis that no release +can write, or policyengine.py drops it. M2 settles which, when both loaders +adopt the rule. + +Under the plan, microcosm.data's loader and policyengine.py's bundle +certification both implement this rule at M2. policyengine.py's +`legacy_compatible_model_package` label becomes `publisher_claim`, and its Core +check becomes unconditional and exact. Owner: anth-volk. On 2026-11-12 +microcosm.data's loader still applies today's rule: microcosm#1505 taught +`_package_certification` to read a build folder's manifest and kept its +containment test, and microcosm#1537 and microcosm#1571 left the function +unchanged. + +### C3: staging telemetry and run outcome + +#### Today + +- **The delivery record.** `build_manifest.json` may carry a `staging` block. + In version 2 the block carries exactly `contract_version` (2), `enabled`, + `mode`, `run_id`, `configured_repository`, `upload_attempts`, + `upload_successes`, `read_back`, `last_error_code` and `opt_out_reason`. The + delivery record stays at version 2 while the staging documents carry version + 3 (`STAGING_CONTRACT_VERSION` and `STAGING_DOCUMENT_VERSION` in + `staging_v2.py`). The UK national and dense assemblers copy the run's + `staging_delivery`, which `validate_staging_delivery` checks, into that + block. When a US tool rewrites its directory for a build folder, + `build_folder_build_manifest` keeps the block. +- **The documents.** Staging version 3 adds a `blocked` lifecycle status beside + `running`, `completed` and `failed`. The UK producers write version 3 through + `StagingRunBundleWriterV2`. The US fiscal-refresh tool still writes version 1 + through `microcosm.build.staging.StagingRunBundleWriter`; no other tool + imports version 1, and `microcosm.build` re-exports it. The ACS-local tool + writes no staging documents. Since microcosm#1410 (merged 2026-11-02), both + writers hand the run's files to the build's emitter, which commits them to + the staging repository with the build's own Hugging Face credential. +- **The run outcome.** `microcosm.build.run_outcome` (microcosm#1147) decides + once how a build ended (`completed`, `blocked`, `failed`, `interrupted`, + `terminated`, `aborted`) and derives the staging status and the Logbook + disposition from that decision. The UK full build, spine build and row-wise + staging use it. On the US side only `program_telemetry` calls it, and only to + label a termination; no US tool takes a staging status or a Logbook + disposition from it. +- **The emitter.** microcosm#1153 moved the local emitter out of this repository + into the external `microcosm-emitter` package on 2026-10-13, and Max accepted + the extraction on 2026-10-15 (cos d1162's note). microcosm-build depends only + on `microcosm-emitter-interface` (`>=0.14.0,<1` on 2026-11-12). Each machine + installs the `microcosm-emitter` command on its own (for example with + `uv tool install microcosm-emitter`). The adapter, + `microcosm.build.telemetry_emitter`, starts it as the build's child process + with three modules: telemetry, Orrery graph publication, and the Hugging Face + hand-over, which commits staging run files and staged dataset bundles. The + adapter supplies build identity and never starts an emitter older than + `MINIMUM_EMITTER_VERSION`. `_packaged_minimum_emitter_version` reads that + floor from the package's `minimum_emitter_version.json` (0.14.0 on + 2026-11-12). +- **Required telemetry.** The emitter runs best effort unless + `MICROCOSM_TELEMETRY_REQUIRED` says `1`. With the variable unset or at `0`, a + missing, slow, refusing or outdated emitter leaves the build running without + it. With `1`, the adapter raises `TelemetryRequiredError` before the build + does any work when it cannot use the emitter; any other value raises + `ValueError`. The Modal stage runner (`tools/modal_us_stage_plan.py`) sets + `1` unless the plan sets `0`, and `tools/modal_us_stage.py` records each + stage's undelivered telemetry events without refusing anything. No UK driver + sets the variable, and neither does the fiscal-refresh tool. Delivery to the + collector gates neither a build nor a release. +- **Who starts an emitter.** The fiscal-refresh tool, the UK spine build, the + UK row-wise staging path and `program_telemetry` each start a build's own + emitter; the US Modal programs open `program_telemetry` (the PUF support base + and the ACS-local release tool among them). Commands that run outside a build + start a short-lived emitter with only its Hugging Face module + (`start_bundle_emitter`): `tools/stage_uk_rowwise_candidate.py`, + `tools/run_uk_cut.py` and `microcosm-publish-release-build`, which hands a + release build to it. +- **The publish gate.** `publish_cli.publication_refusal` holds the checks + every publication shares: non-release smoke output, a reform validation that + skipped its out-of-sample reforms, and undelivered staging + (`_staging_undelivered`). Both publication commands run it before they check + the build's release contract: `microcosm-publish-release-build`, once it has + confirmed that the release publishes into build folders, and + `microcosm-publish-release`, the tagged publisher. `_staging_undelivered` + refuses a build whose manifest records staging the build intended but never + delivered: an empty block, a version-2 record in `local_only` mode or with a + failed read-back, or an enabled run with no successful upload. It passes a + disabled record with a non-empty reason as an opt-out. It also passes a + manifest with no `staging` key, and a US ACS-local build publishes that way. + `--allow-missing-staging` overrides the gate on both commands. Neither + `prepare_build_folder_release` nor the function `publish_release_build` runs + the gate, and promotion (`--promote`) runs none. The Route A candidate in the + 2026-10-15 table carried the version-1 opt-out. + +#### Version 1 (planned) + +- **Each build answers for what it ran.** C3 and C4 bind a build by what it + ran. A build that ran a producer ships that run's staging terminal document + and its Logbook row. A derived build ships a pinned reference to its parent + (the release, the build and the digests of the parent's two manifests) and + the outcome record of its own step. It neither copies its parent's staging + and Logbook records nor inherits them. Three kinds of derived build publish + today, and each ships this much: + - **An annual projection** (`tools/assemble_us_annual_release_dir.py`). + `metadata.annual_projection_base` names the base by repository, release, + build, file path and the H5's SHA-256, and by no manifest digest. The build + ships `annual_manifest.json`, `annual_acceptance.json` and one receipt for + each projected year as its step's records. The assembler copies the base + build's build manifest, changes `release` and `build` and drops + `migrated_from`, so the base's `staging` block, when it has one, travels + into the annual build. + - **A source enrichment** (`tools/build_us_spm_role_enrichment.py`, + `tools/build_us_receipt_enrichment_release.py`). `parent_reference` names + the parent by repository, release and build, with the dataset's SHA-256 and + the digests that `source_enrichment.py` pins for the parent's files; the + build carries those files. The SPM-role lane pins both of the parent's + manifests (`PARENT_FILES`). The receipt lane pins the parent's release + manifest and not its build manifest (`RECEIPT_PARENT_FILES`), so its + reference lacks one of the two manifest digests that version 1 asks for. A + source enrichment's step record is `source_enrichment.json`, and its build + manifest declares a disabled `staging` block with a reason. + - **A compatibility recertification** + (`tools/build_us_compatibility_recertification.py`). The child carries its + parent's two manifests byte for byte, and + `compatibility_recertification.json` names the parent by release and + build and records both manifests' SHA-256. That report is its step's + record: the parent's contract replayed, and the compatibility verdict. Its + build manifest declares a disabled `staging` block with a reason. + + No derived build ships a Logbook row today. **Gap for M3:** + `microcosm-publish-release-build` has no C3 or C4 refusal for a derived + build. Each lane's own validator checks its parent reference. The staging + gate has no rule for a derived build: it passes the disabled block that a + source enrichment or a recertification declares, and it judges an annual + build by the `staging` block the assembler copied from its base. Version 1 + adds the refusal: a derived build must carry the pinned parent reference and + its own step's outcome record, and may carry no staging or Logbook record + that another run wrote. +- A build that ran a producer may not opt out of staging, and + `--allow-missing-staging` no longer applies to it. Every build that publishes + into a build folder holds the `national_default` or the local-area role, + since `RELEASE_ROLES` names no other, so this rule covers every role. +- The publisher keeps requiring remote staging delivery, as it does today, + because that delivery serves as the pre-publication review: the build appears + on the staging dashboard before anyone serves it. Telemetry and the Logbook + differ: their remote halves never gate. A staging outage must not force a + rebuild, though. M3 adds a command that re-delivers the build's own staging + bundle and reads it back, before the build publishes. The command writes its + receipt, `staging_redelivery.json`, into the release directory: the run id, + the repository, the files committed, the read-back result, and the SHA-256 of + the `progress.json` it re-delivered. It never rewrites the build manifest. + When `build_manifest.json`'s `staging` block records an undelivered run, + `release_manifest.json` names the receipt as an artifact, because a build + folder publishes only its two manifests, its checksum ledger and the + artifacts the release manifest declares. The publisher accepts the build only + if the receipt's read-back passed and its digest matches the shipped + `progress.json`. M3 also moves the delivery gate from the two commands into + `prepare_build_folder_release`, so every publication runs it. +- The build folder ships the build's staging version-3 terminal document (its + `progress.json`) as an artifact that `release_manifest.json` names, and + `build_manifest.json` binds it by digest. The build manifest records the + `run_outcome` that document states, and `microcosm-publish-release-build` + refuses any outcome other than `completed`. Builds run on Modal and other + hosts while publishing runs elsewhere, so the record travels with the build, + and the publisher never reads it from the build host. +- The publisher never requires telemetry delivery, so a collector outage cannot + block a release. +- The plan deletes staging version 1, its re-export from `microcosm.build` and + the version-1 branch of `_staging_undelivered` at M2, once the US writes + version 3 (microcosm#933). On 2026-11-12 the fiscal-refresh tool still writes + version 1, and `microcosm-publish-release-build` gates its builds through + that branch. Under the plan the staging dashboard keeps a version-1 reader + for history; this document has not read the dashboard's code. + +### C4: the Logbook + +#### Today + +`microcosm.build.logbook.record_build_attempt` validates a row of 17 fields +(`LOGBOOK_ROW_FIELDS`), writes it as `.json` under the caller's +spool directory (file fsync, atomic rename, directory fsync), and only then +attempts a remote insert. It raises on a local failure; it returns a remote +failure and never raises one. Rows chain: `row_digest` is the SHA-256 of the +canonical JSON of every non-chain field followed by `prev_row_digest`. The +disposition is one of `BUILD_DISPOSITIONS`, and +`run_outcome.logbook_disposition` maps each outcome onto one. + +The UK full build, spine build, row-wise drivers and release-cut certifier +write rows, and `tools/run_uk_cut.py` chains the certification's row on the +national build's: it passes the national build's row digest to +`tools/certify_uk_release_cut.py` as `--logbook-prev-row-digest`. On the US +side only `tools/build_us_multispine_pool.py` writes one; +`tools/us_bundle_generation/core.py` reads `logbook/us.jsonl`, validates its +chain and checks one row's `input_pins_digest`. The fiscal-refresh tool, the +ACS-local tool, the annual assembler and `program_telemetry` write none. +`logbook/us.jsonl` holds 28 rows, the last from 2026-08-09. + +Only the UK dense release records a Logbook row. +`tools/assemble_uk_dense_release_dir.py` reads the last row file in the +candidate's spool, in file-name order, names the build after the row's +`build_id`, and copies the row's `build_id`, `row_digest` and `prev_row_digest` +into `uk_source_coverage.json`. No validator reads that record, and the row +itself does not ship. The UK national manifests name the build after its +calibration attempt (`build`) and carry no row digest; no US build carries one +either. No publication command reads a Logbook row. + +#### Version 1 (planned) + +- Every terminal build attempt writes one row through `record_build_attempt`, + with its disposition from `logbook_disposition(run_outcome)`. +- When `record_build_attempt` returns, the producer copies its terminal + attempt's row into the release directory as `.json`. It does not + copy the row later from the spool, because `reconcile_spool` deletes a row + once the server acknowledges it. `release_manifest.json` names the row as an + artifact, so it publishes into the build folder, and `build_manifest.json` + records `logbook.row_digest`. The shipped row replaces the dense release's + unchecked `logbook_row` record in `uk_source_coverage.json`. +- `microcosm-publish-release-build` refuses a build that ran a producer when + its shipped row is missing, does not validate as a Logbook row, or does not + hash to that digest. The publisher does not require the remote insert. A + derived build ships no row of its own; C3's first rule says what it ships + instead. +- anth-volk decides whether microcosm#739's Logbook family model folds into + `run_outcome`. + +### C5: publish and registry + +#### Today + +The UK national, dense and local-area releases and the five US releases +publish each build into its own folder, `releases///`. The +repository's `releases.json` records each release's builds and names the +current one. For those releases the `latest*.json` pointer files survive as +read-only legacy: nothing writes one for them, and code reads one only for a +repository that has no `releases.json`. + +- **The releases.** `publishes_to_build_folder` names the releases that + publish into build folders: the UK national release + `microcosm-uk-2024-25-national`, the dense release + `microcosm-uk-2024-25-dense`, the local-area releases + `microcosm-uk-2024-25-local-k`, and the five US releases in + `US_RELEASES`. The function matches a local-area name by pattern + (`_UK_LOCAL_LINE_RELEASE_ID_RE`), so it admits every positive `N`. + `microcosm-us-2024-national` holds every national build: + calibrated builds, SPM source enrichments, compatibility recertifications + and exact-k builds. `microcosm-us-2024-local` holds the ACS local-area + builds, `microcosm-us-2024-receipt-donor` the reported-receipt source + enrichments, `microcosm-us-2024-evidence` the evidence-tier builds and + `microcosm-us-2024-annual` the annual projections. `US_RELEASES` gives each + its role in `releases.json`: `local_area` for the local release and + `national` for the other four. `RELEASE_ROLES` maps a build's + `dataset_role` onto those two roles. The registry reads the June 2023 UK + build as the one build of release `populace-uk-2023`, which + `publishes_to_build_folder` does not name, so that release takes no new + build in a folder. +- **Order.** A person runs `microcosm-publish-release-build` + (`microcosm.build.release_publication`) with the commands the UK assemblers + and the US tools print. Before it hands anything to an emitter, the command + refuses, in this order: + 1. a release directory whose name `publishes_to_build_folder` rejects; + 2. what `publication_refusal` refuses: non-release smoke output, a reform + validation that skipped its out-of-sample reforms, and staging that + never arrived (each of the last two with its override flag); + 3. `HF_HUB_OFFLINE` or `TRANSFORMERS_OFFLINE`, which the emitter would + inherit (`_refuse_offline`); + 4. `--make-current` on a compatibility recertification + (`_refuse_recertification_as_current`); + 5. a release manifest that does not name the directory's release, a build + and one repository (`build_folder_identity`); + 6. any `latest*.json` pointer file in the repository + (`_refuse_pointer_files`); + 7. a build that breaks its release contract, names a repository other than + `--repo-id`, declares a role other than its US release's role in + `US_RELEASES`, or ships a file whose SHA-256 differs from its manifest + (`prepare_build_folder_release`); + 8. a recertification whose parent the Hub does not serve as the child + carries it (`require_parent_publication`), and an annual build whose + base national build the Hub does not serve + (`require_base_publication`); + 9. an emitter whose credential cannot write the repository + (`write_access_problem`). + + `prepare_build_folder_release` ties no UK release to a role: it hands the + emitter the role that `RELEASE_ROLES` gives the build's own `dataset_role`. + When the child names its parent by release and build, + `require_parent_publication` reads the parent from its build folder at + `main`; it reads a parent that kept only its tag at that tag. The command + then hands the emitter a `PublishRelease` request: the repository, the + release, the build, the release's role, whether to make the build current, + and each file with its role and SHA-256. The emitter's release writer lives + in the separately installed `microcosm-emitter`; `release_publication` + documents that it commits the build's folder and the build's `releases.json` + entry in one commit. This repository holds only the record's reader. +- **What makes a build current.** Publication lists a build without making it + current. `--promote` makes a published build current + (`promote_release_build`): it reads only the names in the local manifest, + refuses a recertification and any pointer file, and hands the emitter a + `PromoteBuild` request. It runs neither the release contract nor + `publication_refusal` again. `--make-current` publishes a build and makes + it current in one change. Both refuse a compatibility recertification, + which a consumer loads with `build=`. The UK assemblers and + `publication_commands` print the publish command and the `--promote` + command. +- **`releases.json`.** `parse_releases_record` reads it under the writer's + rules: exactly the keys `schema_version` (the integer 1), `default` (a + listed release or `null`) and `releases`; for each release its `role`, its + `current` build or `null`, and each build's `published_at` and `withdrawn`; + a current build that the record lists and has not withdrawn; at most 4 MiB. + The record carries no country, vintage or line. The one-time `switch` step + of `microcosm.build.build_folder_switch` writes a repository's first record + itself and deletes the repository's `latest*.json` files in the same + commit; after that only the emitter's release writer changes the record. + The switch's `copy` step moves each tagged build into a folder and rewrites + its manifests, as C1 describes. +- **The tagged publisher and the pointer files.** `microcosm-publish-release` + (`publish_cli`, which `tools/publish_release.sh` wraps) still publishes a + release that keeps tags. It runs `publication_refusal`, then + `publish_release`. That function runs `prepare_release` (the release contract + and the pointer and tag guards), then `require_parent_publication` for a + recertification, then uploads the release files, creates the immutable tag + and writes `latest.json` or `latest-evidence.json` last. Each pointer is a + schema-1 JSON document at the repository root; `latest.json` holds + `schema_version`, `release_id`, `updated_at`, and `paths` to the contract + files (`latest_pointer_payload`). Only a `national_default` release whose tag + is its own id may move `latest.json`, and never a reported-receipt source + enrichment or a recertification. The tagged publisher refuses by release name + and by repository state: `prepare_release` refuses every release that + `publishes_to_build_folder` names, and `publish_release` refuses every + repository that has `releases.json` (`_refuse_releases_record`; only the + Hub's answer that the file is absent lets it go on). Nothing writes + `latest-.json`: `publish_release` takes no line, although + `line_pointer_payload` remains. Three readers of pointer files remain. The + loader follows `latest.json` (`latest_release`) or `latest-.json` + (`latest_line_release`) only for an entry whose repository has no + `releases.json`. `latest_evidence_release` returns the evidence release's + current build from `releases.json` where the file exists, and reads + `latest-evidence.json` otherwise. The switch reads the pointer files once, to + set each release's current build and the record's `default`. +- **The registry.** `microcosm.data.registry.REGISTRY` maps `(country, year, + variant)` to a `DatasetSpec`. Each names the Hub repository, the dataset + file, the engine class, the `release` the loader reads through + `releases.json`, and the pointer file the loader follows where the + repository has no `releases.json`. The registry holds four entries: + - `("uk", 2023, "compact")`: the June 2023 build, release + `populace-uk-2023`; + - `("uk", 2025, "compact")`: release `microcosm-uk-2024-25-national`, the + UK 2025 default load since microcosm#1432 (2026-11-02), with + `latest-national.json` as its pointer file; + - `("uk", 2025, "dense")`: release `microcosm-uk-2024-25-dense`; + - `("us", 2024, "compact")`: release `microcosm-us-2024-national`, whose + builds declare `microcosm_us_2024.h5` (`build_folder_filename`) or + `populace_us_2024.h5`. +- **How the loader resolves an entry.** `_resolve_certified_release` reads the + repository's `releases.json`. Where the file exists, + `_resolve_build_folder_release` takes the release's current build, or the + listed build that `build=` pins (a withdrawn pin loads with a warning), and + reads that build's `release_manifest.json` from its folder. + `_certified_release_from_manifest` then refuses a manifest that names another + release or build, declares a role other than the release's role in + `releases.json`, pins a revision on any artifact, or declares a dataset whose + role differs from `dataset`, whose repository differs from the registry's, or + whose file name the entry does not list. The loader goes to the entry's + pointer file only when the Hub answers that `releases.json` is absent or, + offline, when the cache never held the record. The loader ignores the + record's `default`: the registry chooses the release. + `load(unverified_root=True)` refuses a repository that has `releases.json`. +- **The gaps.** The registry has no entry for the US local-area release + `microcosm-us-2024-local`, whose builds carry the US state and district + file, or for any UK `local-k` release. policyengine.py's bundle, read on + 2026-11-11 at its main (5b6d7901c), pins four builds by tag: the UK + national build `microcosm-uk-2024-25-national-20261107T020434Z-eeb6093e`, + the UK dense build `microcosm-uk-2024-25-dense-20261107T173210Z-38605444`, + the US build `populace-us-2024-spm-20260915` and the US local-area build + `populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z`. Its certifier + (`require_tagged_layout`) refuses a tagged manifest from a repository that + has `releases.json` at `main`. This document does not check what the Hub + serves. On 2026-10-15 the UK default disagreed three ways: the registry's + default was the June file, policyengine.py served uk-data, and the + microcosm national line had its own pointer. + +#### Version 1 (planned) + +Version 1 is the build-folder shape for every country and line. Max's ruling +cos d1160 froze one contract at the UK national shape, and that shape is the +build folder: each build in `releases///`, `releases.json` as +the record, `microcosm-publish-release-build` as the only publisher, and a +change of the current build through that command (`--promote`, or +`--make-current` at publication) as the one step that moves a release. No line +publishes through a `latest-.json` pointer. The 2026-10-09 report's plan +set out to generalize that pointer beyond the UK, when the UK national line +published through `latest-national.json`; the build folder has replaced that +route. Main meets this shape for every release that `publishes_to_build_folder` +names. The rule that every country and line publishes into build folders lists +the gaps that remain in the shape, and the other rules name their own remaining +work. + +- **One grammar for release names.** A new release takes the name + `microcosm---`, rendered from C1's declared + identity. `` comes from a closed list for each country, which the + contract registers by exact name; version 1 writes no pattern for lines. + The lines in service on 2026-11-12: + - UK: `national` and `dense`, and a local-area line `local-k` for each + `N` that the registry names; + - US: `national`, `local`, `receipt-donor`, `evidence` and `annual`. + + `evidence` is a registered line on the retire list. A UK local-area release + takes the name `microcosm-uk-2024-25-local-k` for each `N` that the + registry names, and the pull request that authorizes a k's first + publication adds its registry entry. On 2026-11-12 the registry names no UK + local-area release, so the UK list holds no `local-k` line yet. Legacy + ids, `populace-uk-2023` among them, stay on C1's frozen list. Version 1 + fixes no grammar for build names. A build's name must pass the emitter + interface's identifier rule (`_SAFE_IDENTIFIER_RE`), and today's forms are + facts, not rules: a UK national build takes its calibration attempt's id + (`uk-frs-calibration-attempt--`), a UK dense build takes the + `build_id` of its Logbook row, a US build takes a `populace-us-2024-…` id, + and an annual build takes `-annual--`. +- **Every country and line publishes into build folders.** A new country's + release joins `publishes_to_build_folder` and the registry in the pull + request that authorizes its first publication. The gaps on 2026-11-12: + - *A new country's tagged publish.* Nothing refuses it: the tagged + publisher accepts any release outside `publishes_to_build_folder`, into a + repository without `releases.json`. M3's refusal of unknown countries + closes the gap, under M3's owners. + - *The NZ, AM and BE declarations.* Each country's `release_contract.json` + (under `packages/microcosm-build/src/microcosm/build/`) names + `latest.json` in its boundary. Each country's owner changes its file + before that country's first publication. + - *The UK local-area pattern.* `publishes_to_build_folder` admits + `microcosm-uk-2024-25-local-k` for every positive `N`, through + `_UK_LOCAL_LINE_RELEASE_ID_RE`, while the registry names no UK local-area + release. The function therefore admits a `k` that no pull request + registered. `test_release_contract_keying.py` pins today's admission with + `microcosm-uk-2024-25-local-k55000`, which the registry does not name. + microcosm#1586 plans to narrow the function to the k's that the registry + names, which flips that case; Max's session owns that change as a code + pull request. Under that plan `line_for_release_id` keeps the pattern, + because the pointer reader still calls it. + - *The tagged publisher.* `microcosm-publish-release` and + `tools/publish_release.sh` stay installed and sit on the + [retire list](#retire-list-as-of-2026-10-15). Their removal waits on the + refusal of a new country's tagged publish. Loading a tagged build that + never moved into a folder stays. + - *Pointer readers.* The loader's fallback (`DatasetSpec.pointer_path`, + `latest_release`, `latest_line_release`) and the `latest-evidence.json` + fallback in `latest_evidence_release` still resolve through `latest*.json`. + `microcosm.data` still exports `latest_release`, which reads `latest.json` + without looking for `releases.json`, and `publish_release`, which writes + it. They leave once no registered repository lacks `releases.json`. The + plan names no owner or milestone for them yet. + - *The UK cut runner.* `tools/run_uk_cut.py` still builds the tagged + publisher's arguments for the UK national release, and + `docs/uk-cut-anyone.md` still describes them; `prepare_release` refuses + that release. Moving the runner to `microcosm-publish-release-build` falls + to the UK cut's owner. + - *policyengine.py's pins.* Its bundle, read on 2026-11-11 at 5b6d7901c, + pins builds by tag; version 1 pins each by release and build in its + folder. + - *The default.* The loader takes each country's default release from the + registry. `releases.json` also names a `default`: in this repository only + the switch tool sets it, and no loader reads it. The gap: no check at + publication confirms that the record's `default` agrees with the registry. + - *The evidence release.* Its builds answer to + `validate_evidence_release_dir` and fail C1 by design. The + [retire list](#retire-list-as-of-2026-10-15) names it as an exception: + version 1 neither admits it to the contract nor retires it. +- **Every file any consumer serves has a registry entry**, including the US + local-area release `microcosm-us-2024-local` (M2), and each entry declares + its vintage. On 2026-11-12 the registry has no entry for + `microcosm-us-2024-local` or for any UK `local-k` release, and + `DatasetSpec` has no vintage field; each release's name carries the vintage. +- **policyengine.py mirrors the registry.** A CI check there asserts that + every bundle `data_releases` entry resolves, by release and build, through + a registry entry (anth-volk, M3). +- **Publishing enforces C1 to C4.** `microcosm-publish-release-build` refuses a + build without a certification, a build that ran a producer and ships no + `run_outcome` of `completed` or no Logbook row, a derived build without what + C3 version 1 asks of it, and an unknown country. On 2026-11-12 it runs the + release contract (C1) and the staging gate and refuses every release outside + `publishes_to_build_folder`. It checks no `run_outcome` and no Logbook row, + and `--promote` runs neither the contract nor the staging gate. The UK dense + line ships no `release_certification.json`: its signed verdict is its gate + report, `uk_local_gates.json`. The plan does not yet say whether the dense + line composes a certification or whether that report counts as one. + +## The parity rule + +The strangler rule from microcosm#378 governs every move of a stage from an +incumbent implementation onto the shared path, including the M4 move of US +national onto the UK national chain and the M6 move of US source stages onto +`run_graph`: + +- **The incumbent stays authoritative** until the new stage proves parity on a + pinned fixture run. Then the stage leaves the incumbent. +- **Data, gate and export stages need byte-identical outputs.** +- **Solver stages need declared tolerance bands**, because there is a measured + nondeterminism floor (the amendment to #378, citing microcosm#307). A solve + that has proved deterministic on a platform must instead produce + bitwise-equal weights on that platform, which is the 2026-10-09 report's M4 + acceptance for the dense solve. + +This document adds one requirement to #378's rule: the pull request that +deletes the incumbent stage records the pinned fixture, the declared tolerance +and the parity verdict. + +This section supersedes #378's rule. The pull request that adds this document +closes #378. + +## Enforcement timeline + +The 2026-10-09 report planned these milestones and proposed their owners. The +last column records what main holds at 6c64038f3 on 2026-11-12. + +C5's shape reached main outside these milestones. microcosm#1505 (merged +2026-11-05) added `microcosm-publish-release-build`, and microcosm#1534 +(merged 2026-11-09) added the tool that switches a repository to build +folders and `releases.json`. microcosm#1537 (merged 2026-11-09) made the +command the only publisher of UK national, dense and local-area builds, and +microcosm#1571 (merged 2026-11-11) did the same for every US build. C5 +version 1 takes that shape. + +| Milestone | Planned | Contract change | Owner | On main, 2026-11-12 | +| --- | --- | --- | --- | --- | +| M0 | 2026-10-16 | This document and the golden fixtures; nothing refuses | Max's session | microcosm#1285, which adds this document | +| M1 | 2026-10-23 | A UK national cut on policyengine-uk ≥ 2.122.2 with staging version 3, a Logbook row and a certification; the registry's UK default flips to it | juaristi22 | The registry flip, in microcosm#1432 (merged 2026-11-02). Since microcosm#1505 the entry also names release `microcosm-uk-2024-25-national`, and the loader reads that release's current build from `releases.json` where the repository has one. microcosm#1574 (merged 2026-11-11) moved the national certification to schema 2, which adds `reference` and `since_baseline`, and renamed the score receipt to `score_vs_reference.json`. This document does not check the current build's staging, Logbook row or certification on the Hub | +| M2 | 2026-10-30 | `us/gates.json` and the US adapter (C1); the US writes staging version 3 and a Logbook row and records `producer` (C3, C4); staging version 1 goes; the registry gains an entry for the US local-area release, which carries the state and district file (C5); one compatibility rule in both loaders and, at publication, for every role (C2) | Max's session, PavelMakarchuk, anth-volk | None of it: only am, be, nz and uk carry a `gates.json`; the fiscal-refresh tool composes no certification, still writes staging version 1 through `StagingRunBundleWriter` and records no Logbook row; no release manifest records a `producer`; the registry has no entry for `microcosm-us-2024-local`; `_check_local_area_release_manifest` checks no compatibility list; and microcosm.data's loader keeps today's containment rule. policyengine.py, at 5b6d7901c on 2026-11-11, keeps its three bases and the `legacy_compatible_model_package` label | +| M3 | 2026-11-06 | Release manifest schema 2 and declared-country dispatch; the validator refuses unknown countries, which also closes a new country's tagged publish; `microcosm-publish-release-build` refuses non-conforming builds, derived builds included; the staging re-delivery command; policyengine.py's registry check | Max's session, juaristi22, anth-volk | None of it: `RELEASE_MANIFEST_SCHEMA_VERSION` is 1; `required_release_files`, `_expected_model_package` and `publishes_to_build_folder` still key on the release name, and an unknown name still gets the base file set; `microcosm-publish-release-build` runs the nine checks that C5 lists under "Order" and adds none of M3's: no check it runs asks for a `run_outcome`, a Logbook row or a manifest's declared `country`, and `required_release_files` names `release_certification.json` for `microcosm-uk-2024-25-national` alone; C1's other certification rule keys on the gate files a directory carries, not on a declared country. `test_release_contract_keying.py`, which arrives with this document, pins today's keying. This document has not looked for policyengine.py's registry check | + +Max's rulings still decide anything that changes published numbers, such as +moving policyengine.py's UK default (UK-1 in the 2026-10-09 report). On +2026-11-11 policyengine.py's bundle, at 5b6d7901c, pins the UK to a build of +the Microcosm national release. + +## Golden fixtures + +`packages/microcosm-data/tests/fixtures/release_contract/v1/` freezes C1 and C5 +in bytes, the way `packages/microcosm-build/tests/fixtures/staging/` freezes the +staging documents that calibration-diagnostics vendors and byte-checks. Each +manifest golden and each `releases.json` holds the bytes that the writer of the +same file in a real build gives for the generator's synthetic inputs, and +`writers.json` names that writer. The folder holds ten files: + +| File | Contract | Writers, as `writers.json` names them, in call order (the last one serializes) | +| --- | --- | --- | +| `c1/microcosm-uk-2024-25-national/build_manifest.json` and `release_manifest.json` | C1 | `uk_national_release_manifests`, then `_write_json`, both in `tools/assemble_uk_release_dir.py`. The assembler's `_stage_and_finalize` calls the same two | +| `c1/microcosm-us-2024-national/build_manifest.json` and `release_manifest.json` | C1 | `_build_manifests`, then `_finish_build_folder_release`, both in `tools/build_us_fiscal_refresh_release.py`, then `rewrite_release_dir` (`microcosm.data.build_folder_manifests`), which `_finish_build_folder_release` calls. The builder's `_main` calls the first two | +| `c1/inventory.json` | C1 | The generator's `_c1_inventory`. It records what `microcosm.data.contract` requires of the UK national release: its line, its dataset role and its role in `releases.json`, whether it publishes into build folders, the required files, the retired build fields, the release manifest's schema version, and the certification's file, schema version, kind, required fields, part evidence files, score receipt, gate-battery phases and signing-key variable. It also lists the files the assembler ships, from the assembler's `_EVIDENCE` | +| `c5/uk/releases.json` and `c5/us/releases.json` | C5 | `add_build` and `make_current` (`microcosm_emitter_interface.releases`), `dataclasses.replace`, then `ReleasesRecord.serialize` | +| `c5/registry.json` | C5 | The generator's `_c5_registry`: every field of every `DatasetSpec` in `REGISTRY`, and the registry's default variant | +| `writers.json` | | The generator's `_writers`, which writes the generator's `WRITERS` table | +| `SHA256SUMS` | | The generator. It lists the other nine files | + +`tools/generate_release_contract_fixtures.py` writes them. Its `--check` +regenerates them into a temporary directory, compares every byte with the +committed folder and names each file that differs. The generator refuses a run +whose files its `WRITERS` table does not cover exactly. + +**The UK national golden.** The generator calls the assembler's pure function, +`uk_national_release_manifests`, with synthetic inputs, and replaces no seam: +the clock, the runtime versions, the commit and each certification part's +status census arrive as arguments. Every digest, package version, commit and +count in the two manifests is synthetic. Each digest is the SHA-256 of +`release-contract-fixture:`, and the build's name, +`uk-frs-calibration-attempt-20260101T000000Z-00000000`, takes the form of a +calibration attempt id. The parts' censuses, `{"passed": 3}`, `{"passed": 2}` +and `{"passed": 4}`, give the build manifest three passing parts without a gate +report. The staging block holds a successful version 2 delivery in the form +that `validate_staging_delivery` returns. The release manifest's SPI Public Use +Tape marker (microcosm#1095) names one synthetic stage. Its study number +(SN 9422) and conditions are the live values that +`microcosm.build.uk_runtime.spi_dependency` writes, which a release that rests +on the tape restates. + +**The US national golden.** The generator runs the US builder's own +`_build_manifests` on stub input files, then `_finish_build_folder_release`, so +`rewrite_release_dir` writes the bytes on disk. The builder reads the installed +packages, the checkout and the clock through globals of its module, and +`_build_manifests` computes the calibration gate's verdict itself from the +solve's diagnostics, through `_release_gate_failures`. The generator replaces +four of those globals and nothing else, and its docstring names the four: + +- `_runtime_versions` returns synthetic package versions; +- `_git_output` returns one synthetic commit for `rev-parse HEAD`; +- `datetime` becomes a clock fixed at `2026-01-01T00:00:00+00:00`; +- `_release_gate_failures` returns no failures, so the build manifest records + `gates.calibration.passed: true` and an empty `failures`, as the UK golden + records passing parts. The synthetic solve then needs no diagnostics. + +The stub dataset and calibration files hold `release-contract-fixture:`, +so their digests take the UK golden's form. The three JSON files that the +builder hashes in the release directory (`calibration_diagnostics.json`, +`us_source_coverage.json` and `us_ssi_take_up.json`) each hold +`{"release_contract_fixture": ""}`, because the builder parses the +coverage file for its fiscal-target exclusion receipt. The golden records that +receipt as absent. + +The US manifests embed live constants of the builder on purpose, because the +builder writes them into every build: + +- the `gate_evidence` keys (`US_RELEASE_GATE_EVIDENCE_FILES`). Each entry + reads `not_evaluated`, because the release directory holds no gate's verdict + and the run skips no gate; +- the documented absent inputs (`US_DOCUMENTED_ABSENT_INPUTS`): five names, + each with its text; +- the calibration diagnostics' schema version + (`CALIBRATION_DIAGNOSTICS_SCHEMA_VERSION`, 9); +- the fiscal-target exclusion receipt's key; +- the dataset and calibration keys and file names, and the repository id + (`policyengine/populace-us`). + +The rest of the two US manifests holds what `_build_manifests` writes for the +generator's call, which passes the function only its required arguments and a +staging block. For each optional value the call leaves out, the function +writes its default: no warm start, no selection source, an empty `timing`, a +null `ledger_artifact` and `default_dataset`, and no Medicaid enrollment +substitutions. It also writes no optional gate block, so the build manifest's +`gates` holds only the four entries that the function always writes: +`calibration`, `target_compilation`, `target_profile_coverage` and +`documented_absent_inputs`. A real build's `_main` passes its timing, the +ledger artifact's provenance, its gate results and receipts such as +`base_pool` and `post_export_scoring`, and the golden freezes none of those +blocks. + +**The two records.** Each `releases.json` holds one release, the country's +national one, with one build: the build its C1 golden names, published at the +fixture instant, not withdrawn and current. The generator builds each record +with the interface's own functions, in the order a repository lives it. +`add_build(make_current=False)` lists the build, as a publication does. +`make_current` makes it current, as a promotion does. +`dataclasses.replace(default=...)` then names the national release as the +record's `default`, as the switch tool's `_switch_record` does; interface +0.14.0 has no function that sets `default`. `ReleasesRecord.serialize` writes +the bytes. Each release takes the role `national`: the UK's from +`RELEASE_ROLES` and the national line's dataset role, the US's from +`US_RELEASES`. + +**What the goldens leave out.** No fixture holds a signed certification or a +gate-battery report. `_check_uk_gate_battery_report` and +`_check_uk_release_certification` refuse either one unless its spec digests +equal the UK gate spec's pins in `contract.py`: +`_UK_GATE_BATTERY_POLICY_SHA256`, `_UK_GATE_BATTERY_GATES_MANIFEST_SHA256`, +`_UK_GATE_BATTERY_SPEC_FINGERPRINT` and, for each certification part, +`_UK_CERTIFICATION_PART_DIGESTS`. Seven merges to main moved the spec +fingerprint between 2026-11-04 and 2026-11-12 (microcosm#1426, #1391, #1511, +#1535, #1550, #1574 and #1583), so a copy frozen before one of them fails those +checks after it. `test_no_fixture_holds_a_signed_certification` checks that no +fixture file is `release_certification.json`, that no document's `kind` is the +certification's, and that no document carries an `attestation` or a +`signature` key at any depth. `inventory.json` freezes the certification's +shape instead. `test_assemble_green_release_dir`, which assembles a national +release directory with a signed certification and validates it, keeps +covering its signed validity. + +Each golden build folder holds only its two manifests, and its test pins +exactly the refusals that its omissions draw: + +- The UK golden leaves out the dataset, the calibration weights and the six + evidence files (`calibration_diagnostics.json`, `release_certification.json`, + `terminal_gates.json`, `release_cut_gates.json`, `spine_gates.json` and + `score_vs_reference.json`). `validate_release_dir` refuses it for the two + required files among them, `calibration_diagnostics.json` and + `release_certification.json`, and for nothing else + (`test_uk_national_golden_is_refused_only_for_the_files_it_omits`). +- The US golden leaves out the dataset, the calibration weights, + `calibration_diagnostics.json`, `us_source_coverage.json`, + `us_ssi_take_up.json` and `stored_inputs.json`. That last file holds the + stored-input gate's verdict, which carries the SHA-256 of the live + stored-column register (`register_sha256`). `validate_release_dir` refuses + the golden for five things + (`test_us_national_golden_is_refused_only_for_the_files_it_omits`): the two + missing required files, `calibration_diagnostics.json` and + `us_source_coverage.json`, then three for the stored-input verdict. Each + manifest records `stored_inputs` as `not_evaluated`, and the release + manifest declares no `stored_inputs` artifact. + +Both pairs of manifests pass the manifest checks themselves +(`_check_build_manifest`, `_check_release_manifest` and +`_check_cross_manifest_consistency`) with no failure. `inventory.json` and +`registry.json` carry live values on purpose, because they freeze the +contract's constants and the registry. + +The tests: + +- `packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py` + imports `microcosm.data` and neither the emitter interface nor + `microcosm.build`. It pins every byte through `SHA256SUMS`. It checks that + `writers.json` names writers for exactly the files that `SHA256SUMS` lists, + that no golden names the generator among its writers, and that no fixture + holds a signed certification. It passes both pairs of manifests through the + manifest checks, pins each golden's refusals and checks the build-folder + layout of both pairs: release and build as strings, no retired field, and a + role and no revision on each artifact. It checks that the UK build + manifest's gates are the three parts' censuses, and that the US build + manifest records a passing calibration gate with every `gate_evidence` entry + `not_evaluated`. It compares the inventory with the contract's live + constants and with the files the UK release manifest ships. It reads each + `releases.json` with `parse_releases_record` and checks its `default`, its + one current build and its role against the C1 golden. Through the loader, it + selects each national artifact from the registry's entry and the record's + entry, and checks that the loader refuses the build under the other role. + Last, it compares `registry.json` with the live registry. +- `packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py`: + executable statements of today's name keying, which C1 version 1 replaces + deliberately. +- `packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py` + runs the generator's `--check`. It checks that every writer `writers.json` + names exists, and reads the source to check that the real build path still + calls each manifest golden's writers: `_stage_and_finalize` calls + `uk_national_release_manifests` and `_write_json`, the US builder's `_main` + calls `_build_manifests` and `_finish_build_folder_release`, and + `_finish_build_folder_release` calls `rewrite_release_dir`. It rebuilds each + `releases.json` from one publication, one promotion and the `default` step, + and checks the interface's serialization against the golden byte for byte + and this repository's reader against the interface's parse. On up to 60 + generated inputs each run, a Hypothesis property checks that for any valid + input `uk_national_release_manifests` meets the contract: the manifest + checks pass, the build-folder layout holds, the diagnostics match the + assembler's six evidence files, the loader selects the build through a + published and promoted record, the SPI marker and each part's census carry + through, and the output depends on the inputs alone, key order included. +- `test_assembled_release_has_the_release_contract_golden_shape` in + `packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py`: + a real assembly's manifests match the golden key for key and type for type, + whatever a list's length and whatever provider ids the publisher labels + carry, and its directory holds exactly the inventory's + `release_directory_files`. + +**Regenerate** when the contract changes on purpose, in the pull request that +changes it and this document: + +```bash +uv run python tools/generate_release_contract_fixtures.py +``` + +Any of these changes fails `--check` until the pull request regenerates the +fixtures: + +- the UK national assembler's manifests: what `uk_national_release_manifests` + writes, `_write_json`'s serialization (indent 1, no final newline), a + constant they write (the release name, the dataset key and file name, the + repository id, the evidence files, the SPI marker's study number and + conditions), or the form `validate_staging_delivery` gives a staging + delivery; +- what the US builder writes for the generator's call: the blocks that + `_build_manifests` always writes and the defaults it writes for a value the + call leaves out, `rewrite_release_dir`'s output (indent 2, a final newline), + or one of the live constants above. A change to a block that only a real + build's arguments produce, such as the ledger provenance or an optional + gate, leaves `--check` green; +- the contract's required files, certification constants, roles, artifact + roles or retired fields; +- the emitter interface's `add_build`, `make_current` or + `ReleasesRecord.serialize` (the repository requires + `microcosm-emitter-interface>=0.14.0,<1`); +- the registry; +- the generator's `WRITERS` table, or one of its synthetic inputs, such as a + build name, the fixture instant or a runtime version. A change of that kind + changes the fixtures, not the contract. + +That failure is the freeze working. No consumer in this repository vendors +the fixtures. One that does, as policyengine.py's planned registry check +would, should pin the SHA-256 of `SHA256SUMS`, as calibration-diagnostics +pinned the staging fixtures' when this document read it on 2026-11-03. + +## Retire list, as of 2026-10-15 + +The table lists the 2026-10-09 report's "retire now" items as GitHub and main +showed them on 2026-10-15. The last column gives what a second reading found on +2026-11-11, for the rows that reading covered. The rows for the US evidence +release and the tagged publisher joined the table on 2026-11-11. + +| Item | State on 2026-10-15 | Read again on 2026-11-11 | +| --- | --- | --- | +| Graph-native drafts #893, #935, #945, #949, #950 | Closed 2026-10-09 | Still closed, unmerged | +| #1011, #995, #996, #999, #1002 | Closed 2026-10-15 under cos d1161; branches kept | Still closed, unmerged; all five branches still exist | +| Orrery: #1148 | Closed 2026-10-12; #1144 and #1151 merged | The same | +| #1083 (US process telemetry) | Open (PavelMakarchuk). The emitter samples the build's process-tree CPU and memory, sends heartbeats and records runtime identity for the fiscal-refresh tool. Its failure classes exist in `run_outcome` but the US tool does not use them yet, and no staging document carries its `work` counters; both belong with microcosm#933. Noted on the pull request for its author | Still open. The fiscal-refresh tool still imports no `run_outcome`, and neither `staging.py` nor `staging_v2.py` carries a `work` key | +| #1082 (US staging always on) | Open (PavelMakarchuk). Belongs in microcosm#933 as staging version 3 for the fiscal-refresh tool. Noted on the pull request for its author | Still open; #933 still open; the tool still writes staging version 1 | +| #822, #824, #826 (Axiom and Belgium drafts) | This milestone closes them; BE re-enters through the transport composer after BE-1 | Closed 2026-10-15, unmerged | +| #642 (US legislative-district layer) | This milestone closes it; district products come from the one US population (M5) or #922 | Closed 2026-10-15, unmerged; #922 open | +| #378 (Build K epic) | Closes when the pull request that adds this document merges | Open | +| #873 (typed model artifacts) | Kept open when checked: microcosm-dynamics then pinned `microcosm-frame` and `microcosm-graph` to 3ff92b0ae, a commit on #873's branch that is not on main. GitHub records #873 closed unmerged at 20:33Z the same day, as superseded; its closing comment says microcosm-dynamics#541 had moved that pin to microcosm main | Still closed, unmerged | +| `tools/build_uk_rowwise_dataset.py` | Kept. The report's reason, that the graph driver already takes `--candidate-clone-counts`, does not settle it: both drivers accept the flag only for a dry run. `docs/uk-full-build-graph.md` keeps the row-wise driver as a separate driver, and Max had not ruled on UK-3 (dense or local-k) by 2026-10-15 | Both drivers still accept the flag only for a dry run | +| `format_uk_release_id`, `apply_uk_release_identity` | This milestone deletes them, with `UKReleaseIdentity`, which builds on `format_uk_release_id`: none had a caller outside its own tests and the `uk_runtime` re-export. The tier vocabulary and the line ids stay | On main none has a caller outside its own tests and the `uk_runtime` re-export | +| Stale text, microcosm.institute `/calibration`, the evidence tier | A separate task owns them (task_d2b70813) | Not read again. For the evidence tier, see the next row | +| The US evidence release, `microcosm-us-2024-evidence` | On this list since 2026-10-15, as the evidence tier | A named exception: version 1 neither admits it to the contract nor retires it. microcosm#1571 made it a standing release in `US_RELEASES`, with the `national` role. `tools/build_us_fiscal_refresh_release.py` writes its builds under `--evidence-release`. `prepare_build_folder_release` checks them with `validate_evidence_release_dir`; they carry schema `1-evidence` and fail C1's certified contract by design. The registry names no entry for it, so `microcosm.data.load` never serves it. No module under `packages/*/src` or `tools/` calls `latest_evidence_release`. Whoever retires the release must first find, from code, the readers of the evidence release and of `latest_evidence_release` | +| The tagged publisher: `microcosm-publish-release` and `tools/publish_release.sh` | Not on the report's list | On the list from 2026-11-11. It refuses every release that `publishes_to_build_folder` names and every repository that has `releases.json`. Its removal waits on the refusal of a new country's tagged publish (C5 version 1, M3). Loading a tagged build that never moved into a folder stays | +| microcosm-benchmarks, the calibration-diagnostics evaluation harness, policyengine-data's calibrate module | Each lives in another repository; proposed as a separate task (task_18c2af98) | Not read again | +| cos d816 | Ruled 2026-10-09 (per-country Core pins, microcosm#1143) | The same | +| cos d928 | Parked; its 2026-10-10 note records it resolved on main (the plan-2 exclusions renewed to 2026-11-03). Nothing to rule | Still parked. On main the plan-2 exclusions read approved on 2026-10-23 and expire on 2027-01-23 | diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py index c53ce33f9d..90411f338a 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/__init__.py @@ -427,9 +427,6 @@ UK_RELEASE_TIER_CPS_TRANSFER, UK_RELEASE_TIER_FRS, UK_RELEASE_TIERS, - UKReleaseIdentity, - apply_uk_release_identity, - format_uk_release_id, validate_uk_release_tier, ) from microcosm.build.uk_runtime.release_input_coverage import ( @@ -791,7 +788,6 @@ "UKRowwiseDatasetResult", "UKReleaseInputColumn", "UKReleaseInputCoverageManifest", - "UKReleaseIdentity", "UKEffectiveMassCoveragePolicy", "UKSPISupportResult", "UKSPIIncomeImputationResult", @@ -809,7 +805,6 @@ "VAT_LIABILITY_BANDS", "VINTAGES", "align_area_targets", - "apply_uk_release_identity", "apply_uk_source_lineage_modulus", "area_groups_from_codes", "area_support_tables", @@ -863,7 +858,6 @@ "fill_support_channel_from_source", "fit_tables", "footprint", - "format_uk_release_id", "frozen_vs_recomputed", "impute_uk_spi_income_support", "replace_uk_spi_support_tables", diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/release_identity.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/release_identity.py index 444db39f0c..efd4efa230 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/release_identity.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/release_identity.py @@ -1,25 +1,27 @@ -"""Canonical source-tier and exact-cardinality identity for UK releases. +"""Canonical UK release ids and the closed source-tier vocabulary. The UK has one extra release-id axis that the US does not: the licence class -of the household spine. It is provenance, not a quality label. Keeping the -closed vocabulary and formatter together prevents a manifest writer from -minting an unratified tier or an id that disagrees with its manifest fields. +of the household spine. It is provenance, not a quality label. The national +and dense releases each keep one constant name, and each of their builds +publishes into its own folder under that name. + +microcosm#1285 retired the minting helpers for the exact-cardinality +``populace-uk---k`` grammar, which had no caller +(docs/release-contract.md, retire list). Version 1 of the release contract, +planned for M3, renders a new release's name, +``microcosm---``, from the identity its manifest +declares, and fixes no grammar for a build's name (docs/release-contract.md, +C1 and C5). """ from __future__ import annotations -from collections.abc import Mapping -from dataclasses import dataclass - __all__ = [ "UK_DENSE_RELEASE_ID", "UK_NATIONAL_RELEASE_ID", "UK_RELEASE_TIERS", "UK_RELEASE_TIER_CPS_TRANSFER", "UK_RELEASE_TIER_FRS", - "UKReleaseIdentity", - "apply_uk_release_identity", - "format_uk_release_id", "validate_uk_release_tier", ] @@ -62,113 +64,3 @@ def validate_uk_release_tier(tier: object) -> str: "adjectives such as 'true', 'full', and 'public' are invalid." ) return tier - - -def _validate_positive_int(value: object, *, field: str) -> int: - if isinstance(value, bool) or not isinstance(value, int) or value <= 0: - raise ValueError( - f"UK release {field} must be a positive integer, got {value!r}." - ) - return value - - -def format_uk_release_id( - year: object, - tier: object, - record_count: object, -) -> str: - """Format ``populace-uk---k`` after strict validation.""" - - valid_year = _validate_positive_int(year, field="year") - valid_tier = validate_uk_release_tier(tier) - valid_record_count = _validate_positive_int(record_count, field="record_count") - return f"populace-uk-{valid_year}-{valid_tier}-k{valid_record_count}" - - -@dataclass(frozen=True) -class UKReleaseIdentity: - """The identity slice every future UK release manifest must record. - - :meth:`as_release_manifest_fields` deliberately returns the build id next - to its component fields. A manifest assembler consumes this validated - slice instead of accepting a free-form tier or a separately formatted id. - """ - - year: int - tier: str - record_count: int - - def __post_init__(self) -> None: - _validate_positive_int(self.year, field="year") - validate_uk_release_tier(self.tier) - _validate_positive_int(self.record_count, field="record_count") - - @property - def release_id(self) -> str: - """Return the canonical exact-cardinality release id.""" - - return format_uk_release_id(self.year, self.tier, self.record_count) - - def as_release_manifest_fields(self) -> dict[str, object]: - """Return identity fields, including the shared ``n_records`` seam.""" - - return { - "country": "uk", - "year": self.year, - "tier": self.tier, - "record_count": self.record_count, - "n_records": self.record_count, - "build": {"build_id": self.release_id}, - } - - -def apply_uk_release_identity( - manifest: Mapping[str, object], - identity: UKReleaseIdentity, -) -> dict[str, object]: - """Apply a validated UK identity without overwriting conflicting fields. - - Release manifests carry ``tier`` at the top level and ``build_id`` inside - the existing ``build`` object. The helper makes that schema seam - explicit, preserves all other build metadata, and refuses to relabel a - manifest whose identity was already assembled differently. - """ - - if not isinstance(manifest, Mapping): - raise TypeError("UK release manifest must be a mapping.") - if not isinstance(identity, UKReleaseIdentity): - raise TypeError("identity must be a UKReleaseIdentity.") - - expected_fields: dict[str, object] = { - "country": "uk", - "year": identity.year, - "tier": identity.tier, - "record_count": identity.record_count, - "n_records": identity.record_count, - } - for field, expected in expected_fields.items(): - if field in manifest and manifest[field] != expected: - raise ValueError( - f"UK release manifest {field!r} is {manifest[field]!r}, " - f"expected {expected!r}." - ) - - raw_build = manifest.get("build") - if raw_build is None: - build: dict[str, object] = {} - elif isinstance(raw_build, Mapping): - build = dict(raw_build) - else: - raise ValueError("UK release manifest 'build' must be an object.") - if "build_id" in build and build["build_id"] != identity.release_id: - raise ValueError( - "UK release manifest 'build.build_id' is " - f"{build['build_id']!r}, expected {identity.release_id!r}." - ) - build["build_id"] = identity.release_id - - return { - **dict(manifest), - **expected_fields, - "build": build, - } diff --git a/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py b/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py new file mode 100644 index 0000000000..b707689daa --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py @@ -0,0 +1,416 @@ +"""The release-contract fixture generator and the writers it freezes. + +``tools/generate_release_contract_fixtures.py`` writes the C1 and C5 golden +fixtures (docs/release-contract.md) with each file's own writer. The data +shard's ``test_release_contract_fixtures.py`` checks the committed bytes with +``microcosm.data`` alone. This module checks what needs the build shard: that +the generator reproduces the bytes, that every writer ``writers.json`` names +exists and is the one its real build path calls, that each ``releases.json`` is +the emitter interface's serialization, and that the UK assembler's manifests +satisfy the release contract for every input, not only the fixture's. +""" + +from __future__ import annotations + +import ast +import dataclasses +import importlib +import importlib.util +import json +import subprocess +import sys +from types import SimpleNamespace + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st +from microcosm_emitter_interface.releases import ( + ReleasesRecord, + add_build, + make_current, +) + +from microcosm.build.staging_v2 import validate_staging_delivery +from microcosm.build.uk_runtime.spi_dependency import ( + UK_SPI_PUBLIC_USE_TAPE_KEY, + uk_spi_public_use_tape_marker, +) +from microcosm.build.uk_runtime.spi_income import SPI_DONOR_UKDS_STUDY +from microcosm.data import contract, loader +from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY +from microcosm.data.releases_record import ( + RELEASES_RECORD_PATH, + build_folder, + parse_releases_record, +) +from test_support.paths import paths_for + +ROOT = paths_for("microcosm-build").repository +FIXTURES = paths_for("microcosm-data").tests / "fixtures" / "release_contract" / "v1" +ASSEMBLER_TOOL = "tools/assemble_uk_release_dir.py" +US_BUILDER_TOOL = "tools/build_us_fiscal_refresh_release.py" + + +def _load_assembler(): + path = ROOT / ASSEMBLER_TOOL + spec = importlib.util.spec_from_file_location("assemble_uk_release_dir", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +ASSEMBLER = _load_assembler() +#: The national release is the UK 2025 default load since microcosm#1432 (Max's +#: #823 ruling). +UK_NATIONAL_SPEC = REGISTRY[("uk", 2025, DEFAULT_VARIANT)] +UK_NATIONAL_ROLE = contract.RELEASE_ROLES[contract.NATIONAL_DEFAULT_DATASET_ROLE] + + +def test_release_contract_fixtures_are_reproducible(): + subprocess.run( + [ + sys.executable, + str(ROOT / "tools" / "generate_release_contract_fixtures.py"), + "--check", + ], + cwd=ROOT, + check=True, + ) + + +# --- writers.json --------------------------------------------------------------- + + +def _tool_function(tool: str, function: str) -> ast.FunctionDef | None: + """A tool's top-level function, read from its source without importing it.""" + + for node in ast.parse((ROOT / tool).read_text()).body: + if isinstance(node, ast.FunctionDef) and node.name == function: + return node + return None + + +def _called_in(tool: str, function: str) -> set[str]: + """The names a tool's top-level function calls.""" + + definition = _tool_function(tool, function) + assert definition is not None, f"{tool} defines no {function}" + return { + node.func.id + for node in ast.walk(definition) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + } + + +def _writer_exists(module: str, function: str) -> bool: + """Whether ``writers.json``'s writer resolves to a function. + + A tool is named by its path and read as source, so the check imports no + tool. Any other module is imported. + """ + + if module.endswith(".py"): + return _tool_function(module, function) is not None + target: object = importlib.import_module(module) + for part in function.split("."): + target = getattr(target, part, None) + return callable(target) + + +def test_every_writer_the_fixtures_name_exists(): + writers = json.loads((FIXTURES / "writers.json").read_text())["files"] + missing = [ + (relative_path, writer) + for relative_path, entry in writers.items() + for writer in entry["writers"] + if not _writer_exists(writer["module"], writer["function"]) + ] + assert missing == [] + + +def test_each_manifest_golden_names_the_writers_its_real_build_calls(): + """A golden freezes live bytes only while the real build path still calls + the writers ``writers.json`` names for it: the UK assembler's + ``_stage_and_finalize`` calls the pure function and its serializer, the US + builder's ``_main`` calls ``_build_manifests`` and + ``_finish_build_folder_release``, and that function calls + ``rewrite_release_dir``.""" + + writers = json.loads((FIXTURES / "writers.json").read_text())["files"] + + def named(release_id: str) -> list[tuple[str, str]]: + entries = { + json.dumps(writers[f"c1/{release_id}/{name}"]["writers"]) + for name in ("build_manifest.json", "release_manifest.json") + } + assert len(entries) == 1, release_id + return [ + (writer["module"], writer["function"]) + for writer in json.loads(entries.pop()) + ] + + assert named(contract._UK_NATIONAL_RELEASE_ID) == [ + (ASSEMBLER_TOOL, "uk_national_release_manifests"), + (ASSEMBLER_TOOL, "_write_json"), + ] + assert {"uk_national_release_manifests", "_write_json"} <= _called_in( + ASSEMBLER_TOOL, "_stage_and_finalize" + ) + + assert named(contract.US_NATIONAL_RELEASE_ID) == [ + (US_BUILDER_TOOL, "_build_manifests"), + (US_BUILDER_TOOL, "_finish_build_folder_release"), + ("microcosm.data.build_folder_manifests", "rewrite_release_dir"), + ] + assert {"_build_manifests", "_finish_build_folder_release"} <= _called_in( + US_BUILDER_TOOL, "_main" + ) + assert "rewrite_release_dir" in _called_in( + US_BUILDER_TOOL, "_finish_build_folder_release" + ) + + +# --- releases.json -------------------------------------------------------------- + + +@pytest.mark.parametrize("country", ["uk", "us"]) +def test_each_releases_record_is_the_interface_writers_serialization(country): + """Each golden ``releases.json`` is byte for byte what the emitter + interface serializes, and one publication (``add_build`` without + ``make_current``) then one promotion (``make_current``) give every field of + it but ``default``, which no interface change sets. This repository's + reader, which repeats the interface's rules, reads the same record.""" + + raw = (FIXTURES / "c5" / country / RELEASES_RECORD_PATH).read_bytes() + record = ReleasesRecord.parse(raw) + assert record.serialize() == raw + + (release, entry) = next(iter(record.releases.items())) + assert list(record.releases) == [release] + published = add_build( + ReleasesRecord.empty(), + release=release, + build=entry.current, + release_role=entry.role, + published_at=entry.builds[entry.current].published_at, + make_current=False, + ) + assert published.releases[release].current is None + promoted = make_current(published, release=release, build=entry.current) + assert promoted.default is None + assert dataclasses.replace(promoted, default=release).serialize() == raw + + read = parse_releases_record(raw) + assert read.default == record.default == release + assert set(read.releases) == set(record.releases) + read_entry = read.releases[release] + assert (read_entry.role, read_entry.current) == (entry.role, entry.current) + assert { + build: (listed.published_at, listed.withdrawn) + for build, listed in read_entry.builds.items() + } == { + build: (listed.published_at, listed.withdrawn) + for build, listed in entry.builds.items() + } + + +# --- The UK assembler's manifests, for every input -------------------------------- + +_HEX = "0123456789abcdef" +_digest = st.text(_HEX, min_size=64, max_size=64) +_version = st.from_regex(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", fullmatch=True) +_attempt_suffix = st.builds( + "{}{:02d}{:02d}T{:02d}{:02d}{:02d}Z-{}".format, + st.integers(2026, 2099).map(str), + st.integers(1, 12), + st.integers(1, 28), + st.integers(0, 23), + st.integers(0, 59), + st.integers(0, 59), + st.text(_HEX, min_size=8, max_size=8), +) +#: A shippable part's statuses: the certifier's census of its gates by status +#: (``_status_census``), which the contract requires to be all "passed". +_statuses = st.integers(1, 500).map(lambda count: {"passed": count}) +_staging = st.sampled_from( + [ + { + "contract_version": 2, + "enabled": True, + "mode": "local_and_remote", + "run_id": "uk-national-property", + "configured_repository": "policyengine/populace-uk-staging", + "upload_attempts": 3, + "upload_successes": 3, + "read_back": "passed", + "last_error_code": None, + "opt_out_reason": None, + }, + { + "contract_version": 2, + "enabled": False, + "mode": "disabled", + "run_id": None, + "configured_repository": None, + "upload_attempts": 0, + "upload_successes": 0, + "read_back": "not_requested", + "last_error_code": None, + "opt_out_reason": "--no-staging", + }, + ] +) +#: The SPI Public Use Tape marker of a run whose stages read the tape or not. +_spi_marker = st.sampled_from( + [ + uk_spi_public_use_tape_marker([]), + uk_spi_public_use_tape_marker( + [ + SimpleNamespace( + stage="property_stage", + artifacts=[{"ukds_study_number": SPI_DONOR_UKDS_STUDY}], + ) + ] + ), + ] +) + + +@st.composite +def _manifest_inputs(draw): + evidence_names = [name for _, _, name in ASSEMBLER._EVIDENCE] + return { + "measured": {name: draw(_digest) for name in ("candidate", *evidence_names)}, + "calibration_filename": f"{ASSEMBLER._DATASET_KEY}_calibration.npz", + "calibration_sha": draw(_digest), + "household_weight_year": { + "dataset_year": draw(st.integers(2020, 2040)), + "basis": draw(st.sampled_from(["dataset_year", "as_solved"])), + }, + # The build's name is the calibration attempt ID. + "attempt_id": "uk-frs-calibration-attempt-" + draw(_attempt_suffix), + "runtime": {package: draw(_version) for package in ASSEMBLER._RUNTIME_PACKAGES}, + "code_pin": draw(st.text(_HEX, min_size=40, max_size=40)), + "target_surface": { + "sha256": draw(_digest), + "n_targets": draw(st.integers(1, 100_000)), + }, + "target_registry": { + "version": draw(st.text(_HEX, min_size=1, max_size=16)), + "n_specs": draw(st.integers(1, 100_000)), + }, + "spine_part": {"statuses": draw(_statuses)}, + "seam_part": {"statuses": draw(_statuses)}, + "release_cut_part": {"statuses": draw(_statuses)}, + "staging_delivery": validate_staging_delivery(draw(_staging)), + "spi_marker": draw(_spi_marker), + "created_at": "2026-01-01T00:00:00+00:00", + "publisher_labels": draw( + st.dictionaries(st.text(min_size=1), st.text(min_size=1), max_size=3) + ), + } + + +@settings(max_examples=60, deadline=None) +@given(_manifest_inputs()) +def test_national_manifests_satisfy_the_release_contract(inputs): + """Invariant: for any valid inputs, the assembler's two manifests + + * pass the contract's manifest checks with no failure; + * name the national release and the same build, and carry none of the + fields that named a build before build folders; + * give every artifact its role and no revision; + * ship exactly the signed evidence as their diagnostics; + * load through ``releases.json``: once the build is published and + promoted, the loader selects it inside its own folder, at no revision, + with the digest and the package versions the inputs gave; + * restate the SPI Public Use Tape marker; + * copy each certification part's census; + * depend on the inputs alone, key order included. + """ + + build_manifest, release_manifest = ASSEMBLER.uk_national_release_manifests(**inputs) + release_id = contract._UK_NATIONAL_RELEASE_ID + build = inputs["attempt_id"] + + failures: list[str] = [] + contract._check_build_manifest(build_manifest, release_id, failures) + contract._check_release_manifest(release_manifest, release_id, failures) + contract._check_cross_manifest_consistency( + build_manifest, release_manifest, None, failures + ) + assert failures == [] + + for manifest in (build_manifest, release_manifest): + assert (manifest["release"], manifest["build"]) == (release_id, build) + assert not set(contract.RETIRED_BUILD_FIELDS) & set(manifest) + + artifacts = release_manifest["artifacts"] + assert not any("revision" in artifact for artifact in artifacts.values()) + assert {key: artifact["role"] for key, artifact in artifacts.items()} == { + key: contract.release_artifact_role(key, artifact["kind"]) + for key, artifact in artifacts.items() + } + assert { + artifact["path"] + for artifact in artifacts.values() + if artifact["kind"] == "diagnostics" + } == {filename for _, filename, _ in ASSEMBLER._EVIDENCE} + assert set(contract.required_release_files(release_id)) <= { + "build_manifest.json", + "release_manifest.json", + *(filename for _, filename, _ in ASSEMBLER._EVIDENCE), + } + + # The record a publication and then a promotion of this build give, as the + # interface serializes it and this repository's reader parses it. + published = add_build( + ReleasesRecord.empty(), + release=release_id, + build=build, + release_role=UK_NATIONAL_ROLE, + published_at=inputs["created_at"], + make_current=False, + ) + promoted = make_current(published, release=release_id, build=build) + entry = parse_releases_record(promoted.serialize()).releases[release_id] + certified = loader._certified_release_from_manifest( + UK_NATIONAL_SPEC, + release_id, + release_manifest, + expected_revision=None, + build=entry.current, + release_role=entry.role, + ) + assert certified.artifact_path == ( + f"{build_folder(release_id, build)}/{UK_NATIONAL_SPEC.filename}" + ) + assert certified.artifact_revision is None + assert certified.artifact_sha256 == inputs["measured"]["candidate"] + assert certified.model.built_version == inputs["runtime"]["policyengine-uk"] + assert certified.core.built_version == inputs["runtime"]["policyengine-core"] + + # The release restates the SPI Public Use Tape marker: the flag on the + # microdata's own entry, the whole marker under licensed_data. + microdata = artifacts[release_manifest["default_datasets"]["national"]] + assert ( + microdata["spi_public_use_tape_dependent"] is inputs["spi_marker"]["dependent"] + ) + assert release_manifest["licensed_data"] == { + UK_SPI_PUBLIC_USE_TAPE_KEY: inputs["spi_marker"] + } + + # The manifest records each part's census exactly as the certification signed it. + assert build_manifest["gates"] == { + "spine": inputs["spine_part"]["statuses"], + "calibration_seam": inputs["seam_part"]["statuses"], + "release_cut": inputs["release_cut_part"]["statuses"], + } + + # Deterministic, key order included: the builder is a function of its inputs. + again = ASSEMBLER.uk_national_release_manifests(**inputs) + assert [json.dumps(document, indent=1) for document in again] == [ + json.dumps(document, indent=1) + for document in (build_manifest, release_manifest) + ] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py index f12a42c039..4f52f29d3b 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py @@ -577,6 +577,69 @@ def test_assemble_preserves_successful_version_2_delivery( assert manifest["staging"] == delivery +_RELEASE_CONTRACT_C1 = ( + paths_for("microcosm-data").tests / "fixtures" / "release_contract" / "v1" / "c1" +) +#: Maps whose keys are data rather than schema: the provider ids of the labels. +_DATA_KEYED_PATHS = frozenset({("publisher_labels",)}) + + +def _json_shape(value: object, path: tuple[str, ...] = ()) -> object: + """A JSON document's keys and value types, without its values.""" + + if isinstance(value, dict): + if path in _DATA_KEYED_PATHS: + return {"*": sorted({_json_shape(item) for item in value.values()})} + return {key: _json_shape(item, (*path, key)) for key, item in value.items()} + if isinstance(value, list): + # A list's length is a value, not part of its shape: the golden's SPI + # Public Use Tape marker names one synthetic stage, while an assembly + # from the packaged spec names every stage that reads the tape. + shapes: list[object] = [] + for item in value: + shape = _json_shape(item, (*path, "[]")) + if shape not in shapes: + shapes.append(shape) + return shapes + return type(value).__name__ + + +def test_assembled_release_has_the_release_contract_golden_shape( + assembler_inputs, capsys +) -> None: + """The C1 golden fixture (docs/release-contract.md) is what this assembler + ships: a real assembly's manifests match it key for key and type for type, + and its directory holds exactly the inventory's files.""" + + record_path = assembler_inputs["diagnostics"].parent / "build_record.json" + record = json.loads(record_path.read_text()) + # The golden records a delivered run; a deliberate opt-out has the same keys + # but null strings, so match the delivery to compare types too. + golden_build = json.loads( + ( + _RELEASE_CONTRACT_C1 / UK_NATIONAL_RELEASE_ID / "build_manifest.json" + ).read_text() + ) + record["staging_delivery"] = golden_build["staging"] + record_path.write_text(json.dumps(record), encoding="utf-8") + + assert _load_driver_module().main(assembler_inputs["argv"]) == 0 + capsys.readouterr() + release_dir = assembler_inputs["out_dir"] / UK_NATIONAL_RELEASE_ID + + for name in ("build_manifest.json", "release_manifest.json"): + assembled = json.loads((release_dir / name).read_text()) + golden = json.loads( + (_RELEASE_CONTRACT_C1 / UK_NATIONAL_RELEASE_ID / name).read_text() + ) + assert _json_shape(assembled) == _json_shape(golden), name + inventory = json.loads((_RELEASE_CONTRACT_C1 / "inventory.json").read_text()) + assert ( + sorted(path.name for path in release_dir.iterdir()) + == inventory["release_directory_files"] + ) + + def test_assemble_refuses_candidate_sha_mismatch(assembler_inputs) -> None: assembler_inputs["candidate"].write_bytes( assembler_inputs["candidate"].read_bytes() + b"tampered" diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identity.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identity.py index 4055589876..51485185d3 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identity.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identity.py @@ -3,13 +3,11 @@ import pytest from microcosm.build import uk_runtime +from microcosm.build.uk_runtime import release_identity from microcosm.build.uk_runtime.release_identity import ( UK_RELEASE_TIER_CPS_TRANSFER, UK_RELEASE_TIER_FRS, UK_RELEASE_TIERS, - UKReleaseIdentity, - apply_uk_release_identity, - format_uk_release_id, validate_uk_release_tier, ) @@ -18,23 +16,12 @@ def test_uk_release_tiers_are_the_two_ratified_provenance_tokens() -> None: assert UK_RELEASE_TIER_FRS == "frs" assert UK_RELEASE_TIER_CPS_TRANSFER == "cps-transfer" assert UK_RELEASE_TIERS == frozenset({"frs", "cps-transfer"}) - assert uk_runtime.apply_uk_release_identity is apply_uk_release_identity + assert uk_runtime.validate_uk_release_tier is validate_uk_release_tier -@pytest.mark.parametrize( - ("tier", "expected"), - [ - ("frs", "populace-uk-2023-frs-k535080"), - ("cps-transfer", "populace-uk-2023-cps-transfer-k57240"), - ], -) -def test_uk_release_id_formatter_uses_tier_and_exact_record_count( - tier: str, - expected: str, -) -> None: - record_count = 535_080 if tier == "frs" else 57_240 - - assert format_uk_release_id(2023, tier, record_count) == expected +@pytest.mark.parametrize("tier", ["frs", "cps-transfer"]) +def test_uk_release_tier_accepts_the_ratified_tokens(tier: str) -> None: + assert validate_uk_release_tier(tier) == tier @pytest.mark.parametrize( @@ -58,95 +45,13 @@ def test_uk_release_tier_rejects_quality_adjectives_and_unknown_values( @pytest.mark.parametrize( - ("year", "record_count", "match"), - [ - (0, 1, "year"), - (-2023, 1, "year"), - (True, 1, "year"), - ("2023", 1, "year"), - (2023, 0, "record_count"), - (2023, -1, "record_count"), - (2023, True, "record_count"), - (2023, 1.5, "record_count"), - ], -) -def test_uk_release_id_formatter_rejects_non_positive_or_non_integer_axes( - year: object, - record_count: object, - match: str, -) -> None: - with pytest.raises(ValueError, match=match): - format_uk_release_id(year, "frs", record_count) - - -def test_uk_release_identity_is_the_manifest_assembly_surface() -> None: - identity = UKReleaseIdentity( - year=2023, - tier=UK_RELEASE_TIER_FRS, - record_count=535_080, - ) - - assert identity.release_id == "populace-uk-2023-frs-k535080" - assert identity.as_release_manifest_fields() == { - "country": "uk", - "year": 2023, - "tier": "frs", - "record_count": 535_080, - "n_records": 535_080, - "build": {"build_id": "populace-uk-2023-frs-k535080"}, - } - - -def test_uk_release_identity_validates_before_manifest_assembly() -> None: - with pytest.raises(ValueError, match="spine source licence class"): - UKReleaseIdentity(year=2023, tier="public", record_count=535_080) - - -def test_apply_uk_release_identity_preserves_existing_build_metadata() -> None: - identity = UKReleaseIdentity(year=2023, tier="frs", record_count=535_080) - manifest = { - "schema_version": 1, - "build": { - "built_with_core_package": { - "name": "policyengine-core", - "version": "3.19.0", - } - }, - } - - assembled = apply_uk_release_identity(manifest, identity) - - assert assembled["tier"] == "frs" - assert assembled["build"] == { - "build_id": "populace-uk-2023-frs-k535080", - "built_with_core_package": { - "name": "policyengine-core", - "version": "3.19.0", - }, - } - assert manifest == { - "schema_version": 1, - "build": { - "built_with_core_package": { - "name": "policyengine-core", - "version": "3.19.0", - } - }, - } - - -@pytest.mark.parametrize( - "manifest", - [ - {"tier": "cps-transfer"}, - {"n_records": 2}, - {"build": {"build_id": "populace-uk-2023-cps-transfer-k535080"}}, - ], + "retired", + ["UKReleaseIdentity", "apply_uk_release_identity", "format_uk_release_id"], ) -def test_apply_uk_release_identity_rejects_conflicting_identity( - manifest: dict[str, object], -) -> None: - identity = UKReleaseIdentity(year=2023, tier="frs", record_count=535_080) +def test_exact_k_id_minting_is_retired(retired: str) -> None: + """The exact-k minting helpers are gone: release contract version 1 + renders a new release's name from the identity its manifest declares + (docs/release-contract.md, C1).""" - with pytest.raises(ValueError, match="tier|n_records|build.build_id"): - apply_uk_release_identity(manifest, identity) + assert not hasattr(release_identity, retired) + assert not hasattr(uk_runtime, retired) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py new file mode 100644 index 0000000000..b880f95b78 --- /dev/null +++ b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py @@ -0,0 +1,415 @@ +"""The release contract's version 1 golden fixtures (docs/release-contract.md). + +The fixtures freeze C1 (one build folder's manifests for the UK national release +and for the US national release, and the contract's inventory for the UK +national release) and C5 (each repository's ``releases.json`` and the dataset +registry). These tests hold every byte to ``SHA256SUMS``, hold ``writers.json`` +to the files it must name, and prove each file is what the contract's own code +accepts or reads. They import only ``microcosm.data``: this package supports +Python versions the emitter interface does not. The build shard's +``test_release_contract_fixture_generation.py`` proves that the generator +reproduces the bytes and that each ``releases.json`` is the interface writer's +serialization. + +A failure here after a deliberate contract change means: regenerate with +``uv run python tools/generate_release_contract_fixtures.py`` and update +docs/release-contract.md in the same pull request. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json +import shutil +from pathlib import Path + +import pytest + +from microcosm.data import contract, loader +from microcosm.data.contract import ReleaseContractError, validate_release_dir +from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY +from microcosm.data.releases_record import ( + RELEASES_RECORD_PATH, + build_folder, + parse_releases_record, +) +from test_support.paths import paths_for + +FIXTURES = paths_for("microcosm-data").tests / "fixtures" / "release_contract" / "v1" +GENERATOR = "tools/generate_release_contract_fixtures.py" +UK_RELEASE = contract._UK_NATIONAL_RELEASE_ID +US_RELEASE = contract.US_NATIONAL_RELEASE_ID +#: Each golden build's release, with the registry entry that loads it. The UK +#: national release is the UK 2025 default load since microcosm#1432 (Max's +#: #823 ruling). +GOLDENS = { + "uk": (UK_RELEASE, REGISTRY[("uk", 2025, DEFAULT_VARIANT)]), + "us": (US_RELEASE, REGISTRY[("us", 2024, DEFAULT_VARIANT)]), +} +COUNTRIES = sorted(GOLDENS) +REGENERATE = ( + f"regenerate with `uv run python {GENERATOR}` and update docs/release-contract.md" +) + + +def _json(path: Path) -> dict: + return json.loads(path.read_text()) + + +def _listed() -> dict[str, str]: + """Each file ``SHA256SUMS`` lists, with its digest.""" + + listed = {} + for line in (FIXTURES / "SHA256SUMS").read_text().splitlines(): + expected, relative_path = line.split(" ", 1) + listed[relative_path] = expected + return listed + + +def _manifests(country: str) -> tuple[dict, dict]: + """A golden build folder's build manifest and release manifest.""" + + release_dir = FIXTURES / "c1" / GOLDENS[country][0] + return ( + _json(release_dir / "build_manifest.json"), + _json(release_dir / "release_manifest.json"), + ) + + +def _record(country: str): + """A golden ``releases.json``, as this package's reader parses it.""" + + return parse_releases_record( + (FIXTURES / "c5" / country / RELEASES_RECORD_PATH).read_bytes() + ) + + +def _refusals(country: str, tmp_path: Path) -> list[str]: + """What ``validate_release_dir`` refuses a golden build folder for.""" + + release_id = GOLDENS[country][0] + release_dir = tmp_path / release_id + shutil.copytree(FIXTURES / "c1" / release_id, release_dir) + with pytest.raises(ReleaseContractError) as refusal: + validate_release_dir(release_dir) + return refusal.value.failures + + +def _keys(value: object) -> set[str]: + """Every object key in a JSON document, at any depth.""" + + if isinstance(value, dict): + return set(value).union(*(_keys(item) for item in value.values())) + if isinstance(value, list): + return set().union(*(_keys(item) for item in value)) + return set() + + +def test_every_fixture_byte_is_pinned_by_sha256sums(): + listed = _listed() + on_disk = { + path.relative_to(FIXTURES).as_posix() + for path in FIXTURES.rglob("*") + if path.is_file() and path.name != "SHA256SUMS" + } + assert set(listed) == on_disk + for relative_path, expected in listed.items(): + observed = hashlib.sha256((FIXTURES / relative_path).read_bytes()).hexdigest() + assert observed == expected, f"{relative_path} changed; {REGENERATE}" + + +def test_writers_json_names_a_writer_for_exactly_the_pinned_files(): + """``writers.json`` names, for every file ``SHA256SUMS`` lists and for no + other, the calls that produce its bytes. A manifest or a ``releases.json`` + is a golden: its last writer is the function that serializes the same file + in a real build, never the generator.""" + + writers = _json(FIXTURES / "writers.json")["files"] + assert set(writers) == set(_listed()), REGENERATE + for relative_path, entry in writers.items(): + assert entry["writers"], relative_path + for writer in entry["writers"]: + assert set(writer) == {"module", "function"}, relative_path + assert all(isinstance(name, str) and name for name in writer.values()) + goldens = { + *( + f"c1/{release_id}/{name}" + for release_id, _ in GOLDENS.values() + for name in ("build_manifest.json", "release_manifest.json") + ), + *(f"c5/{country}/{RELEASES_RECORD_PATH}" for country in COUNTRIES), + } + assert goldens <= set(writers) + for relative_path, entry in writers.items(): + modules = {writer["module"] for writer in entry["writers"]} + if relative_path in goldens: + assert GENERATOR not in modules, relative_path + else: + # The inventory, the registry snapshot and writers.json itself. + assert modules == {GENERATOR}, relative_path + + +def test_no_fixture_holds_a_signed_certification(): + """No fixture file is a certification, and no fixture document carries an + ``attestation`` or a ``signature`` at any depth.""" + + assert contract._UK_RELEASE_CERTIFICATION_FILE not in { + Path(relative_path).name for relative_path in _listed() + } + for path in FIXTURES.rglob("*.json"): + document = _json(path) + assert document.get("kind") != contract._UK_RELEASE_CERTIFICATION_KIND, path + assert not {"attestation", "signature"} & _keys(document), path + + +# --- C1 ----------------------------------------------------------------------- + + +@pytest.mark.parametrize("country", COUNTRIES) +def test_golden_manifests_pass_the_manifest_checks_directly(country): + release_id = GOLDENS[country][0] + build_manifest, release_manifest = _manifests(country) + failures: list[str] = [] + contract._check_build_manifest(build_manifest, release_id, failures) + contract._check_release_manifest(release_manifest, release_id, failures) + contract._check_cross_manifest_consistency( + build_manifest, release_manifest, None, failures + ) + assert failures == [] + + +@pytest.mark.parametrize("country", COUNTRIES) +def test_golden_manifests_have_the_build_folder_layout(country): + """Both manifests name the release and the same build as two strings and + carry none of the fields that named a build before build folders. Each + artifact carries its role and no revision.""" + + release_id = GOLDENS[country][0] + assert contract.publishes_to_build_folder(release_id) + build_manifest, release_manifest = _manifests(country) + assert isinstance(build_manifest["build"], str) and build_manifest["build"] + for manifest in (build_manifest, release_manifest): + assert manifest["release"] == release_id + assert manifest["build"] == build_manifest["build"] + assert not set(contract.RETIRED_BUILD_FIELDS) & set(manifest) + assert ( + release_manifest["schema_version"] == contract.RELEASE_MANIFEST_SCHEMA_VERSION + ) + artifacts = release_manifest["artifacts"] + assert not any("revision" in artifact for artifact in artifacts.values()) + assert {key: artifact["role"] for key, artifact in artifacts.items()} == { + key: contract.release_artifact_role(key, artifact["kind"]) + for key, artifact in artifacts.items() + } + + +def test_uk_national_golden_is_refused_only_for_the_files_it_omits(tmp_path): + """``validate_release_dir`` refuses the UK golden for exactly the two + required files it omits on purpose: both bind live gate digests + (docs/release-contract.md, Golden fixtures). The assembler's own tests + validate a full signed directory.""" + + assert _refusals("uk", tmp_path) == [ + "required file 'calibration_diagnostics.json' is missing.", + "required file 'release_certification.json' is missing.", + ] + + +def test_us_national_golden_is_refused_only_for_the_files_it_omits(tmp_path): + """``validate_release_dir`` refuses the US golden for exactly five things, + each caused by one of the three files it omits on purpose: the calibration + diagnostics, the source coverage, and the stored-input verdict, which + binds a digest of the live stored-column register. The verdict's absence + draws three refusals: each manifest records ``stored_inputs`` as + ``not_evaluated``, and the release manifest declares no such artifact.""" + + failures = _refusals("us", tmp_path) + assert failures[:2] == [ + "required file 'calibration_diagnostics.json' is missing.", + f"required file {contract.US_SOURCE_COVERAGE_DIAGNOSTICS_FILE!r} is missing.", + ] + stored_inputs = failures[2:] + assert [failure.split(" ", 1)[0] for failure in stored_inputs] == [ + "build_manifest.json", + "release_manifest.json", + "release_manifest.json", + ] + for failure in stored_inputs: + assert repr(contract.US_STORED_INPUTS_EVIDENCE_KEY) in failure + assert "'not_evaluated'" in stored_inputs[0] + assert "'not_evaluated'" in stored_inputs[1] + assert repr(contract.US_STORED_INPUTS_EVIDENCE_FILE) in stored_inputs[2] + + +def test_uk_national_gates_are_the_certifications_part_censuses(): + """The build manifest copies each certification part's ``statuses``, which + the contract requires to be a census of that part's gates, all passed.""" + + gates = _manifests("uk")[0]["gates"] + assert set(gates) == set(contract._UK_CERTIFICATION_PART_EVIDENCE_FILES) + for part, census in gates.items(): + assert list(census) == ["passed"], part + assert isinstance(census["passed"], int) and census["passed"] > 0, part + + +def test_us_national_golden_records_a_passing_calibration_gate(): + """The US golden is a build whose calibration gate passed, and it binds no + gate verdict: every gate-evidence entry reads ``not_evaluated`` in both + manifests, and the stored-input verdict is one of those entries.""" + + build_manifest, release_manifest = _manifests("us") + calibration = build_manifest["gates"]["calibration"] + assert calibration["passed"] is True + assert calibration["failures"] == [] + for manifest in (build_manifest, release_manifest): + assert contract.US_STORED_INPUTS_EVIDENCE_KEY in manifest["gate_evidence"] + assert set(manifest["gate_evidence"].values()) == {"not_evaluated"} + + +def test_inventory_matches_the_live_contract(): + inventory = _json(FIXTURES / "c1" / "inventory.json") + certification = inventory["certification"] + assert inventory["release_id"] == UK_RELEASE + assert inventory["line"] == contract.line_for_release_id(UK_RELEASE) + assert inventory["dataset_role"] == contract.dataset_role_for_line( + inventory["line"] + ) + assert ( + inventory["release_role"] == contract.RELEASE_ROLES[inventory["dataset_role"]] + ) + assert inventory["publishes_to_build_folder"] is True + assert contract.publishes_to_build_folder(UK_RELEASE) + assert inventory["retired_build_fields"] == list(contract.RETIRED_BUILD_FIELDS) + assert ( + inventory["release_manifest_schema_version"] + == contract.RELEASE_MANIFEST_SCHEMA_VERSION + ) + assert inventory["required_release_files"] == list( + contract.required_release_files(UK_RELEASE) + ), REGENERATE + assert certification == { + "file": contract._UK_RELEASE_CERTIFICATION_FILE, + "schema_version": contract._UK_RELEASE_CERTIFICATION_SCHEMA_VERSION, + "kind": contract._UK_RELEASE_CERTIFICATION_KIND, + "required_fields": sorted(contract._UK_CERTIFICATION_REQUIRED_FIELDS), + "part_evidence_files": dict(contract._UK_CERTIFICATION_PART_EVIDENCE_FILES), + "score_receipt_file": contract._UK_CERTIFICATION_SCORE_RECEIPT_FILE, + "gate_battery_phases": list(contract._UK_GATE_BATTERY_PHASES), + "signing_key_env": contract._UK_GATE_BATTERY_SIGNING_KEY_ENV, + }, REGENERATE + + +def test_inventory_files_are_the_files_the_manifests_ship(): + inventory = _json(FIXTURES / "c1" / "inventory.json") + release_manifest = _manifests("uk")[1] + shipped = { + artifact["path"] + for artifact in release_manifest["artifacts"].values() + if artifact["kind"] == "diagnostics" + } + directory_files = set(inventory["release_directory_files"]) + assert directory_files == shipped | {"build_manifest.json", "release_manifest.json"} + assert set(inventory["required_release_files"]) <= directory_files + certification = inventory["certification"] + assert { + certification["file"], + certification["score_receipt_file"], + *certification["part_evidence_files"].values(), + } <= directory_files + + +# --- C5 ----------------------------------------------------------------------- + + +@pytest.mark.parametrize("country", COUNTRIES) +def test_releases_record_lists_the_golden_build_as_its_releases_current_build( + country, +): + """Each golden ``releases.json`` is one repository's record after one + publication and one promotion: it lists the C1 golden build, not + withdrawn, as the current build of the national release, gives that + release the role its manifest's ``dataset_role`` maps to, and names it as + the default.""" + + release_id = GOLDENS[country][0] + build_manifest, release_manifest = _manifests(country) + record = _record(country) + assert record.default == release_id + assert set(record.releases) == {release_id} + entry = record.releases[release_id] + assert entry.current == build_manifest["build"] == release_manifest["build"] + assert set(entry.builds) == {entry.current} + assert entry.builds[entry.current].withdrawn is False + dataset_role = release_manifest.get( + "dataset_role", contract.NATIONAL_DEFAULT_DATASET_ROLE + ) + assert entry.role == contract.RELEASE_ROLES[dataset_role] + if country == "us": + assert entry.role == contract.US_RELEASES[release_id] + + +@pytest.mark.parametrize("country", COUNTRIES) +def test_loader_selects_each_golden_build_through_its_releases_record(country): + """The registry entry names the golden's release. Given that release's + entry in ``releases.json``, the loader selects the dataset inside the + current build's folder, at no revision, with the packages the manifest + says the build ran.""" + + release_id, spec = GOLDENS[country] + assert spec.release == release_id + entry = _record(country).releases[release_id] + release_manifest = _manifests(country)[1] + certified = loader._certified_release_from_manifest( + spec, + release_id, + release_manifest, + expected_revision=None, + build=entry.current, + release_role=entry.role, + ) + # The file name a new build declares: the registry's ``filename``, or its + # ``build_folder_filename`` where the two differ (the US national release). + declared = spec.build_folder_filename or spec.filename + assert certified.build == entry.current + assert certified.artifact_repo_id == spec.hf_repo + assert certified.artifact_path == ( + f"{build_folder(release_id, entry.current)}/{declared}" + ) + assert certified.artifact_revision is None + assert certified.model.name == spec.engine_package + assert certified.model.specifiers == ( + f"=={release_manifest['built_with_model_package']['version']}", + ) + assert certified.core.specifiers == ( + f"=={release_manifest['built_with_core_package']['version']}", + ) + + +@pytest.mark.parametrize("country", COUNTRIES) +def test_loader_refuses_a_golden_build_under_the_other_role(country): + """``releases.json`` gives a release one role, and the loader refuses a + manifest whose ``dataset_role`` maps to another.""" + + release_id, spec = GOLDENS[country] + entry = _record(country).releases[release_id] + other_role = contract.RELEASE_ROLES[contract.NON_DEFAULT_LOCAL_AREA_DATASET_ROLE] + assert entry.role != other_role + with pytest.raises(ValueError, match="is listed with role"): + loader._certified_release_from_manifest( + spec, + release_id, + _manifests(country)[1], + expected_revision=None, + build=entry.current, + release_role=other_role, + ) + + +def test_registry_snapshot_matches_the_live_registry(): + snapshot = _json(FIXTURES / "c5" / "registry.json") + assert snapshot["default_variant"] == DEFAULT_VARIANT + assert snapshot["entries"] == [ + {"key": list(key), **dataclasses.asdict(REGISTRY[key])} + for key in sorted(REGISTRY) + ], f"the dataset registry changed; {REGENERATE} (C5)" diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py new file mode 100644 index 0000000000..305982a557 --- /dev/null +++ b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py @@ -0,0 +1,158 @@ +"""Executable statements of how the release contract keys on name strings today. + +docs/release-contract.md (C1, "The id-string keying") describes these gaps, and +C1 version 1, planned for milestone M3, replaces them with dispatch on the +manifest's declared country. Each test pins one of today's behaviours so that +the change is deliberate: when a change flips one, update the document and the +test together. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from microcosm.data import contract +from microcosm.data.contract import ( + REQUIRED_RELEASE_FILES, + ReleaseContractError, + line_for_release_id, + publishes_to_build_folder, + required_release_files, + validate_release_dir, +) +from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY +from test_support.microcosm_data.release import release_dir # noqa: F401 + +#: Names in the release grammar, ``microcosm---``, that +#: the contract does not list: three countries it does not know, and a US +#: vintage outside ``contract.US_RELEASES``. +UNLISTED_IDS = ( + "microcosm-nz-2025-national", + "microcosm-be-2025-national", + "microcosm-am-2025-national", + "microcosm-us-2025-national", +) +#: A US build's own release in the tagged layout, where the release was the +#: build. +TAGGED_US_ID = "populace-us-2024-0000000-20260101" + + +@pytest.mark.parametrize("release_id", UNLISTED_IDS) +def test_an_unlisted_id_gets_only_the_base_files_and_no_model_package(release_id): + assert required_release_files(release_id) == REQUIRED_RELEASE_FILES + assert contract._expected_model_package(release_id) is None + + +def test_the_us_releases_are_a_closed_list_of_five_names(): + assert dict(contract.US_RELEASES) == { + "microcosm-us-2024-national": "national", + "microcosm-us-2024-local": "local_area", + "microcosm-us-2024-receipt-donor": "national", + "microcosm-us-2024-evidence": "national", + "microcosm-us-2024-annual": "national", + } + + +@pytest.mark.parametrize("release_id", (*contract.US_RELEASES, TAGGED_US_ID)) +def test_the_us_contract_keys_on_five_exact_names_and_one_prefix(release_id): + """The US requirements apply to the five names in ``contract.US_RELEASES``, + matched exactly, and to every name with the ``populace-us-`` prefix. A US + name outside both, such as ``microcosm-us-2025-national``, is unlisted.""" + + assert contract.is_us_release(release_id) + assert required_release_files(release_id) == ( + *REQUIRED_RELEASE_FILES, + contract.US_SOURCE_COVERAGE_DIAGNOSTICS_FILE, + ) + assert contract._expected_model_package(release_id) == "policyengine-us" + + +@pytest.mark.parametrize("release_id", (*UNLISTED_IDS, TAGGED_US_ID)) +def test_an_unlisted_id_does_not_publish_into_a_build_folder(release_id): + """``publishes_to_build_folder`` lists the build-folder releases by name. + An unlisted name falls outside the list, and so does a US build's own + release in the tagged layout.""" + + assert not publishes_to_build_folder(release_id) + + +@pytest.mark.parametrize( + "release_id", + ( + contract._UK_NATIONAL_RELEASE_ID, + contract._UK_DENSE_RELEASE_ID, + "microcosm-uk-2024-25-local-k55000", + *contract.US_RELEASES, + ), +) +def test_the_uk_and_us_releases_publish_into_build_folders(release_id): + assert publishes_to_build_folder(release_id) + + +@pytest.mark.parametrize( + "release_id", (*UNLISTED_IDS, TAGGED_US_ID, *contract.US_RELEASES) +) +def test_only_uk_names_have_a_pointer_line(release_id): + """``line_for_release_id`` gives the ```` of a ``latest-.json`` + pointer file, which only the pointer reader still needs. No US release and + no unlisted name has one.""" + + assert line_for_release_id(release_id) is None + + +def test_the_uk_national_and_local_lines_are_the_only_lines(): + assert line_for_release_id(contract._UK_NATIONAL_RELEASE_ID) == "national" + assert line_for_release_id("microcosm-uk-2024-25-local-k55000") == "local-k55000" + assert line_for_release_id(contract._UK_DENSE_RELEASE_ID) is None + + +def test_the_registry_year_is_not_the_uk_national_releases_vintage(): + # The national release is the UK 2025 default load since microcosm#1432 + # (Max's #823 ruling). + spec = REGISTRY[("uk", 2025, DEFAULT_VARIANT)] + assert spec.release == contract._UK_NATIONAL_RELEASE_ID + assert spec.release == "microcosm-uk-2024-25-national" + assert not spec.release.startswith(f"microcosm-uk-{spec.year}-") + + +def _retarget(directory: Path, release_id: str, *, drop: tuple[str, ...] = ()): + """Rename a tagged release to ``release_id``, optionally dropping files.""" + + target = directory.with_name(release_id) + directory.rename(target) + build = json.loads((target / "build_manifest.json").read_text()) + build["build_id"] = release_id + (target / "build_manifest.json").write_text(json.dumps(build)) + manifest = json.loads((target / "release_manifest.json").read_text()) + manifest["build"]["build_id"] = release_id + for key in list(manifest["artifacts"]): + if manifest["artifacts"][key]["path"] in drop: + del manifest["artifacts"][key] + else: + manifest["artifacts"][key]["revision"] = release_id + (target / "release_manifest.json").write_text(json.dumps(manifest)) + for name in drop: + (target / name).unlink() + return target + + +def test_the_same_bytes_pass_under_an_unlisted_id_and_fail_under_a_us_id( + release_dir, # noqa: F811 +): + """A new country's release fails open. In the tagged layout, which an + unlisted name takes, renaming a US release to an NZ name lifts the + source-coverage and stored-input requirements with nothing else changed.""" + + drop = ("us_source_coverage.json", "stored_inputs.json") + unlisted = _retarget(release_dir, "microcosm-nz-2025-national", drop=drop) + validate_release_dir(unlisted) + + us = _retarget(unlisted, TAGGED_US_ID) + with pytest.raises(ReleaseContractError) as refusal: + validate_release_dir(us) + assert "required file 'us_source_coverage.json' is missing." in ( + refusal.value.failures + ) diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/SHA256SUMS b/packages/microcosm-data/tests/fixtures/release_contract/v1/SHA256SUMS new file mode 100644 index 0000000000..20deb330f4 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/SHA256SUMS @@ -0,0 +1,9 @@ +ef662a0787031c95b95e745cabffd41b3a7b92ab11283c2343af0bffad4bd904 c1/inventory.json +8e53c9192be76a2e9b691919ce27598695b1403073de791ac0f7b23d09f434e0 c1/microcosm-uk-2024-25-national/build_manifest.json +c10d33a17e23a1f18b53fad775077bbe4bd76012f877821af194d709ef69f640 c1/microcosm-uk-2024-25-national/release_manifest.json +1cdfc01a19324729b2cb9e456c17a3684fa50f28f7c21889340ad81a46f103c4 c1/microcosm-us-2024-national/build_manifest.json +a0846ca19b3164302d5093c7eecd2e611d727f6149b906dacfa56b83376f4495 c1/microcosm-us-2024-national/release_manifest.json +2f8c927b5e0b53dfc8315b38f67d92dae7c1d7574b1fc55ee48ea8133df2eb50 c5/registry.json +1230f545477e6f095f94c1b61539a60a76f14f10146a2b022ea6f3aa66323dbd c5/uk/releases.json +51061e4109b7c5e45e7ba0bcd0efc366d0ed54fe906c737a63ddc1f821a0ff96 c5/us/releases.json +997af7b89d2119b2fa9fc2ba601aa9e37bac593c4eca36d17ceec55a5c2ae910 writers.json diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/inventory.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/inventory.json new file mode 100644 index 0000000000..3dc2f8e006 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/inventory.json @@ -0,0 +1,67 @@ +{ + "certification": { + "file": "release_certification.json", + "gate_battery_phases": [ + "preflight", + "assembled", + "transferred", + "terminal" + ], + "kind": "uk_release_certification", + "part_evidence_files": { + "calibration_seam": "terminal_gates.json", + "release_cut": "release_cut_gates.json", + "spine": "spine_gates.json" + }, + "required_fields": [ + "attestation", + "candidate", + "country", + "diagnostics_sha256", + "doctrine", + "exclusions_evaluated_on", + "kind", + "parent_spine", + "parts", + "reference", + "release_id", + "schema_version", + "score_receipt", + "shippable", + "since_baseline", + "spec" + ], + "schema_version": 2, + "score_receipt_file": "score_vs_reference.json", + "signing_key_env": "MICROCOSM_UK_TERMINAL_GATE_SIGNING_KEY" + }, + "dataset_role": "national_default", + "line": "national", + "publishes_to_build_folder": true, + "release_directory_files": [ + "build_manifest.json", + "calibration_diagnostics.json", + "release_certification.json", + "release_cut_gates.json", + "release_manifest.json", + "score_vs_reference.json", + "spine_gates.json", + "terminal_gates.json" + ], + "release_id": "microcosm-uk-2024-25-national", + "release_manifest_schema_version": 1, + "release_role": "national", + "required_release_files": [ + "build_manifest.json", + "release_manifest.json", + "calibration_diagnostics.json", + "release_certification.json" + ], + "retired_build_fields": [ + "build_id", + "attempt_id", + "cut_tag" + ], + "schema_name": "microcosm.release-contract.c1-inventory", + "schema_version": 1 +} diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-uk-2024-25-national/build_manifest.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-uk-2024-25-national/build_manifest.json new file mode 100644 index 0000000000..09762bad17 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-uk-2024-25-national/build_manifest.json @@ -0,0 +1,62 @@ +{ + "release": "microcosm-uk-2024-25-national", + "build": "uk-frs-calibration-attempt-20260101T000000Z-00000000", + "code": { + "repository": "PolicyEngine/microcosm", + "git_commit": "a8fe1b954d0d42c1a6b10d663024d11201717a50", + "git_dirty": false + }, + "build_sha": "a8fe1b9", + "runtime": { + "python": "3.13.0", + "policyengine-core": "3.0.0", + "policyengine-uk": "2.0.0", + "microcosm-data": "0.1.0", + "microcosm-build": "0.1.0", + "microcosm-calibrate": "0.1.0" + }, + "dataset": { + "filename": "microcosm_uk_2024_25.h5", + "sha256": "d357112f939979d7e34696637ef874ca0531902c86bd34f503e1885d02eafb3e" + }, + "calibration": { + "filename": "microcosm_uk_2024_25_calibration.npz", + "sha256": "d1356e9ae3fb9baea7e7860931eeb274874f5ac61fc0b87277fc8245eac0801f", + "household_weight_year": { + "dataset_year": 2024, + "basis": "dataset_year" + }, + "target_surface": { + "sha256": "48b07537f3af196a534c7591ef2638babeb38c3d8dcfef910512b457ee5f2de8", + "n_targets": 2 + }, + "target_registry": { + "version": "release-contract-fixture-v1", + "n_specs": 2 + } + }, + "gates": { + "spine": { + "passed": 3 + }, + "calibration_seam": { + "passed": 2 + }, + "release_cut": { + "passed": 4 + } + }, + "created_at": "2026-01-01T00:00:00+00:00", + "staging": { + "contract_version": 2, + "enabled": true, + "mode": "local_and_remote", + "run_id": "uk-national-release-contract-fixture", + "configured_repository": "policyengine/populace-uk-staging", + "upload_attempts": 6, + "upload_successes": 6, + "read_back": "passed", + "last_error_code": null, + "opt_out_reason": null + } +} \ No newline at end of file diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-uk-2024-25-national/release_manifest.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-uk-2024-25-national/release_manifest.json new file mode 100644 index 0000000000..0bfc0cd2ce --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-uk-2024-25-national/release_manifest.json @@ -0,0 +1,109 @@ +{ + "schema_version": 1, + "release": "microcosm-uk-2024-25-national", + "build": "uk-frs-calibration-attempt-20260101T000000Z-00000000", + "built_at": "2026-01-01T00:00:00+00:00", + "built_with_core_package": { + "name": "policyengine-core", + "version": "3.0.0" + }, + "built_with_model_package": { + "name": "policyengine-uk", + "version": "2.0.0" + }, + "data_package": { + "name": "microcosm-data", + "version": "0.1.0" + }, + "default_datasets": { + "national": "microcosm_uk_2024_25" + }, + "compatible_core_packages": [ + { + "name": "policyengine-core", + "specifier": "==3.0.0" + } + ], + "compatible_model_packages": [ + { + "name": "policyengine-uk", + "specifier": "==2.0.0" + } + ], + "artifacts": { + "microcosm_uk_2024_25": { + "kind": "microdata", + "path": "microcosm_uk_2024_25.h5", + "repo_id": "policyengine/populace-uk-private", + "sha256": "d357112f939979d7e34696637ef874ca0531902c86bd34f503e1885d02eafb3e", + "role": "dataset", + "spi_public_use_tape_dependent": true + }, + "microcosm_uk_2024_25_calibration": { + "kind": "calibration", + "path": "microcosm_uk_2024_25_calibration.npz", + "repo_id": "policyengine/populace-uk-private", + "sha256": "d1356e9ae3fb9baea7e7860931eeb274874f5ac61fc0b87277fc8245eac0801f", + "role": "calibration_weights" + }, + "calibration_diagnostics": { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": "policyengine/populace-uk-private", + "sha256": "835fb1bf9e7ae31b5446813f76a8bc2c1fbb5e73d3dad2aae71558102c6988b5", + "role": "calibration_diagnostics" + }, + "release_certification": { + "kind": "diagnostics", + "path": "release_certification.json", + "repo_id": "policyengine/populace-uk-private", + "sha256": "a587dbc0e451e476bc45d2e49898935bcd2f58b52d8805b4710c79ad25615dd9", + "role": "release_certification" + }, + "terminal_gates": { + "kind": "diagnostics", + "path": "terminal_gates.json", + "repo_id": "policyengine/populace-uk-private", + "sha256": "4da83cdcad9ae46e5c2d455476f5da1103490ca8398c543db4401cb1b4dacb40", + "role": "terminal_gates" + }, + "release_cut_gates": { + "kind": "diagnostics", + "path": "release_cut_gates.json", + "repo_id": "policyengine/populace-uk-private", + "sha256": "5d5bc71f11821673fe286473e15dcf74770cbccde099d2a893f9300c13ed23a8", + "role": "release_cut_gates" + }, + "spine_gates": { + "kind": "diagnostics", + "path": "spine_gates.json", + "repo_id": "policyengine/populace-uk-private", + "sha256": "63eb81ac3d1dba7a137813c57358455c4b08c9e8383639d9ae26406121bece9a", + "role": "spine_gates" + }, + "score_vs_reference": { + "kind": "diagnostics", + "path": "score_vs_reference.json", + "repo_id": "policyengine/populace-uk-private", + "sha256": "75064c846279290ec8980518224b0ef5d65b2646813883dc643ef3954ef59cf4", + "role": "score_vs_reference" + } + }, + "description": "UK national calibration pipeline release build assembled from attempt uk-frs-calibration-attempt-20260101T000000Z-00000000.", + "publisher_labels": { + "ons": "Office for National Statistics" + }, + "licensed_data": { + "spi_public_use_tape": { + "study": "SN 9422", + "dependent": true, + "stages": [ + "release_contract_fixture_stage" + ], + "conditions": [ + "No attempt may be made to attribute a record to a named individual.", + "Material that includes analyses of the tape goes to HMRC at least ten working days before it is distributed or published." + ] + } + } +} \ No newline at end of file diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-us-2024-national/build_manifest.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-us-2024-national/build_manifest.json new file mode 100644 index 0000000000..e6d6d8ab26 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-us-2024-national/build_manifest.json @@ -0,0 +1,97 @@ +{ + "release": "microcosm-us-2024-national", + "build": "populace-us-2024-0000000-20260101", + "build_sha": "a8fe1b9", + "created_at": "2026-01-01T00:00:00+00:00", + "staging": { + "enabled": true, + "run_id": "us-national-release-contract-fixture", + "repo_id": "policyengine/populace-us-staging", + "uploads_succeeded": true + }, + "code": { + "repository": "PolicyEngine/microcosm", + "git_commit": "a8fe1b954d0d42c1a6b10d663024d11201717a50", + "git_dirty": false + }, + "runtime": { + "python": "3.13.0", + "microcosm-build": "0.1.0", + "microcosm-calibrate": "0.1.0", + "microcosm-data": "0.1.0", + "microcosm-frame": "0.1.0", + "policyengine-core": "3.0.0", + "policyengine-us": "1.0.0", + "numpy": "2.0.0", + "pandas": "2.0.0", + "torch": "2.0.0" + }, + "timing": {}, + "ledger_artifact": null, + "gate_evidence": { + "esi_premiums": "not_evaluated", + "input_coverage": "not_evaluated", + "input_mass_parity": "not_evaluated", + "qrf_tail_concentration": "not_evaluated", + "reform_coverage_smoke": "not_evaluated", + "stored_inputs": "not_evaluated" + }, + "fiscal_target_exclusion_receipt": { + "artifact": "us_source_coverage", + "path": "us_source_coverage.json", + "sha256": "2a4c5ce460a7c63b0c4bdfe379a1c91497d6eaf5f6286affe2b98984bfa8890e", + "key": "fiscal_target_exclusion_receipt", + "present": false, + "receipt_sha256": null + }, + "dataset": { + "filename": "microcosm_us_2024.h5", + "sha256": "e5df1650192da1659359652a6f1218a18a07cba38bdb1e4f754a248e0ea6d40b", + "default": null + }, + "calibration": { + "filename": "microcosm_us_2024_calibration.npz", + "sha256": "d1356e9ae3fb9baea7e7860931eeb274874f5ac61fc0b87277fc8245eac0801f", + "warm_start": { + "enabled": false + }, + "selection_source": { + "enabled": false + }, + "target_surface": { + "sha256": "48b07537f3af196a534c7591ef2638babeb38c3d8dcfef910512b457ee5f2de8", + "n_targets": 1 + }, + "target_registry": { + "version": "release-contract-fixture-v1", + "n_specs": 1 + }, + "medicaid_enrollment_substitutions": [] + }, + "gates": { + "calibration": { + "passed": true, + "failures": [], + "initial_loss": 2.0, + "final_loss": 1.0, + "fraction_within_10pct": 1.0 + }, + "target_compilation": { + "dropped_target_names": [] + }, + "target_profile_coverage": { + "passed": true, + "failures": [], + "details": { + "requirements_checked": 1 + } + }, + "documented_absent_inputs": { + "is_homeless": "No ASEC source: the CPS samples the housed population, so the pre-HR1 SNAP ABAWD homeless exemption cannot fire (PolicyEngine/microcosm#351).", + "was_in_foster_care": "No ASEC item for foster-care history, so the pre-HR1 former-foster-youth ABAWD exemption (7 CFR 273.24(c)(9)) cannot fire (PolicyEngine/microcosm#351).", + "is_snap_work_program_participant": "No ASEC item measures SNAP E&T or qualifying work-program participation, so compliance via program participation never fires; USDA reports E&T reaches a small minority of participants, so the always-False default understates compliance only modestly (PolicyEngine/microcosm#249).", + "weekly_snap_work_program_hours": "No ASEC item measures qualifying work-program hours, so combined work-plus-program hours toward the 20-hour ABAWD test omit program hours (PolicyEngine/microcosm#249).", + "is_snap_workfare_participant": "No ASEC item measures workfare participation under 7 CFR 273.7(m), which satisfies the ABAWD requirement regardless of hours; defaults False (PolicyEngine/microcosm#249)." + } + } +} diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-us-2024-national/release_manifest.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-us-2024-national/release_manifest.json new file mode 100644 index 0000000000..3d3bdcafd8 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/microcosm-us-2024-national/release_manifest.json @@ -0,0 +1,107 @@ +{ + "schema_version": 1, + "release": "microcosm-us-2024-national", + "build": "populace-us-2024-0000000-20260101", + "built_at": "2026-01-01T00:00:00+00:00", + "built_with_core_package": { + "name": "policyengine-core", + "version": "3.0.0" + }, + "built_with_model_package": { + "name": "policyengine-us", + "version": "1.0.0" + }, + "timing": {}, + "ledger_artifact": null, + "gate_evidence": { + "esi_premiums": "not_evaluated", + "input_coverage": "not_evaluated", + "input_mass_parity": "not_evaluated", + "qrf_tail_concentration": "not_evaluated", + "reform_coverage_smoke": "not_evaluated", + "stored_inputs": "not_evaluated" + }, + "fiscal_target_exclusion_receipt": { + "artifact": "us_source_coverage", + "path": "us_source_coverage.json", + "sha256": "2a4c5ce460a7c63b0c4bdfe379a1c91497d6eaf5f6286affe2b98984bfa8890e", + "key": "fiscal_target_exclusion_receipt", + "present": false, + "receipt_sha256": null + }, + "warm_start_calibration": { + "enabled": false + }, + "selection_source": { + "enabled": false + }, + "default_dataset": null, + "documented_absent_inputs": { + "is_homeless": "No ASEC source: the CPS samples the housed population, so the pre-HR1 SNAP ABAWD homeless exemption cannot fire (PolicyEngine/microcosm#351).", + "was_in_foster_care": "No ASEC item for foster-care history, so the pre-HR1 former-foster-youth ABAWD exemption (7 CFR 273.24(c)(9)) cannot fire (PolicyEngine/microcosm#351).", + "is_snap_work_program_participant": "No ASEC item measures SNAP E&T or qualifying work-program participation, so compliance via program participation never fires; USDA reports E&T reaches a small minority of participants, so the always-False default understates compliance only modestly (PolicyEngine/microcosm#249).", + "weekly_snap_work_program_hours": "No ASEC item measures qualifying work-program hours, so combined work-plus-program hours toward the 20-hour ABAWD test omit program hours (PolicyEngine/microcosm#249).", + "is_snap_workfare_participant": "No ASEC item measures workfare participation under 7 CFR 273.7(m), which satisfies the ABAWD requirement regardless of hours; defaults False (PolicyEngine/microcosm#249)." + }, + "data_package": { + "name": "microcosm-data", + "version": "0.1.0" + }, + "default_datasets": { + "national": "microcosm_us_2024" + }, + "compatible_core_packages": [ + { + "name": "policyengine-core", + "specifier": "==3.0.0" + } + ], + "compatible_model_packages": [ + { + "name": "policyengine-us", + "specifier": "==1.0.0" + } + ], + "calibration_diagnostics": { + "status": "available", + "schema_version": 9, + "sha256": "5f4fd23313e2a194098c6f044a847360fe995f97d21aed1dba25d0f606f1fb92" + }, + "artifacts": { + "microcosm_us_2024": { + "kind": "microdata", + "path": "microcosm_us_2024.h5", + "repo_id": "policyengine/populace-us", + "sha256": "e5df1650192da1659359652a6f1218a18a07cba38bdb1e4f754a248e0ea6d40b", + "role": "dataset" + }, + "microcosm_us_2024_calibration": { + "kind": "calibration", + "path": "microcosm_us_2024_calibration.npz", + "repo_id": "policyengine/populace-us", + "sha256": "d1356e9ae3fb9baea7e7860931eeb274874f5ac61fc0b87277fc8245eac0801f", + "role": "calibration_weights" + }, + "calibration_diagnostics": { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": "policyengine/populace-us", + "sha256": "5f4fd23313e2a194098c6f044a847360fe995f97d21aed1dba25d0f606f1fb92", + "role": "calibration_diagnostics" + }, + "us_source_coverage": { + "kind": "diagnostics", + "path": "us_source_coverage.json", + "repo_id": "policyengine/populace-us", + "sha256": "2a4c5ce460a7c63b0c4bdfe379a1c91497d6eaf5f6286affe2b98984bfa8890e", + "role": "us_source_coverage" + }, + "us_ssi_take_up": { + "kind": "diagnostics", + "path": "us_ssi_take_up.json", + "repo_id": "policyengine/populace-us", + "sha256": "c70728a4a22f38943fdd5108865efad25dd389049c9d641639d8f984c9a5fe74", + "role": "us_ssi_take_up" + } + } +} diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/registry.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/registry.json new file mode 100644 index 0000000000..da6a6283f9 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/registry.json @@ -0,0 +1,79 @@ +{ + "default_variant": "compact", + "entries": [ + { + "build_folder_filename": null, + "country": "uk", + "engine_class": "UKSingleYearDataset", + "engine_module": "policyengine_uk.data", + "engine_package": "policyengine-uk", + "filename": "populace_uk_2023.h5", + "hf_repo": "policyengine/populace-uk-private", + "key": [ + "uk", + 2023, + "compact" + ], + "pointer_path": "latest.json", + "release": "populace-uk-2023", + "variant": "compact", + "year": 2023 + }, + { + "build_folder_filename": null, + "country": "uk", + "engine_class": "UKSingleYearDataset", + "engine_module": "policyengine_uk.data", + "engine_package": "policyengine-uk", + "filename": "microcosm_uk_2024_25.h5", + "hf_repo": "policyengine/populace-uk-private", + "key": [ + "uk", + 2025, + "compact" + ], + "pointer_path": "latest-national.json", + "release": "microcosm-uk-2024-25-national", + "variant": "compact", + "year": 2025 + }, + { + "build_folder_filename": null, + "country": "uk", + "engine_class": "UKSingleYearDataset", + "engine_module": "policyengine_uk.data", + "engine_package": "policyengine-uk", + "filename": "microcosm_uk_2024_25_dense.h5", + "hf_repo": "policyengine/populace-uk-private", + "key": [ + "uk", + 2025, + "dense" + ], + "pointer_path": "latest.json", + "release": "microcosm-uk-2024-25-dense", + "variant": "dense", + "year": 2025 + }, + { + "build_folder_filename": "microcosm_us_2024.h5", + "country": "us", + "engine_class": "USSingleYearDataset", + "engine_module": "policyengine_us.data", + "engine_package": "policyengine-us", + "filename": "populace_us_2024.h5", + "hf_repo": "policyengine/populace-us", + "key": [ + "us", + 2024, + "compact" + ], + "pointer_path": "latest.json", + "release": "microcosm-us-2024-national", + "variant": "compact", + "year": 2024 + } + ], + "schema_name": "microcosm.release-contract.registry", + "schema_version": 1 +} diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/uk/releases.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/uk/releases.json new file mode 100644 index 0000000000..1591b4d9e5 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/uk/releases.json @@ -0,0 +1,16 @@ +{ + "schema_version": 1, + "default": "microcosm-uk-2024-25-national", + "releases": { + "microcosm-uk-2024-25-national": { + "role": "national", + "current": "uk-frs-calibration-attempt-20260101T000000Z-00000000", + "builds": { + "uk-frs-calibration-attempt-20260101T000000Z-00000000": { + "published_at": "2026-01-01T00:00:00+00:00", + "withdrawn": false + } + } + } + } +} diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/us/releases.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/us/releases.json new file mode 100644 index 0000000000..ab3bf52b56 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/us/releases.json @@ -0,0 +1,16 @@ +{ + "schema_version": 1, + "default": "microcosm-us-2024-national", + "releases": { + "microcosm-us-2024-national": { + "role": "national", + "current": "populace-us-2024-0000000-20260101", + "builds": { + "populace-us-2024-0000000-20260101": { + "published_at": "2026-01-01T00:00:00+00:00", + "withdrawn": false + } + } + } + } +} diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/writers.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/writers.json new file mode 100644 index 0000000000..1ec32e5942 --- /dev/null +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/writers.json @@ -0,0 +1,126 @@ +{ + "files": { + "c1/inventory.json": { + "writers": [ + { + "function": "_c1_inventory", + "module": "tools/generate_release_contract_fixtures.py" + } + ] + }, + "c1/microcosm-uk-2024-25-national/build_manifest.json": { + "writers": [ + { + "function": "uk_national_release_manifests", + "module": "tools/assemble_uk_release_dir.py" + }, + { + "function": "_write_json", + "module": "tools/assemble_uk_release_dir.py" + } + ] + }, + "c1/microcosm-uk-2024-25-national/release_manifest.json": { + "writers": [ + { + "function": "uk_national_release_manifests", + "module": "tools/assemble_uk_release_dir.py" + }, + { + "function": "_write_json", + "module": "tools/assemble_uk_release_dir.py" + } + ] + }, + "c1/microcosm-us-2024-national/build_manifest.json": { + "writers": [ + { + "function": "_build_manifests", + "module": "tools/build_us_fiscal_refresh_release.py" + }, + { + "function": "_finish_build_folder_release", + "module": "tools/build_us_fiscal_refresh_release.py" + }, + { + "function": "rewrite_release_dir", + "module": "microcosm.data.build_folder_manifests" + } + ] + }, + "c1/microcosm-us-2024-national/release_manifest.json": { + "writers": [ + { + "function": "_build_manifests", + "module": "tools/build_us_fiscal_refresh_release.py" + }, + { + "function": "_finish_build_folder_release", + "module": "tools/build_us_fiscal_refresh_release.py" + }, + { + "function": "rewrite_release_dir", + "module": "microcosm.data.build_folder_manifests" + } + ] + }, + "c5/registry.json": { + "writers": [ + { + "function": "_c5_registry", + "module": "tools/generate_release_contract_fixtures.py" + } + ] + }, + "c5/uk/releases.json": { + "writers": [ + { + "function": "add_build", + "module": "microcosm_emitter_interface.releases" + }, + { + "function": "make_current", + "module": "microcosm_emitter_interface.releases" + }, + { + "function": "replace", + "module": "dataclasses" + }, + { + "function": "ReleasesRecord.serialize", + "module": "microcosm_emitter_interface.releases" + } + ] + }, + "c5/us/releases.json": { + "writers": [ + { + "function": "add_build", + "module": "microcosm_emitter_interface.releases" + }, + { + "function": "make_current", + "module": "microcosm_emitter_interface.releases" + }, + { + "function": "replace", + "module": "dataclasses" + }, + { + "function": "ReleasesRecord.serialize", + "module": "microcosm_emitter_interface.releases" + } + ] + }, + "writers.json": { + "writers": [ + { + "function": "_writers", + "module": "tools/generate_release_contract_fixtures.py" + } + ] + } + }, + "schema_name": "microcosm.release-contract.fixture-writers", + "schema_version": 1 +} diff --git a/tools/assemble_uk_release_dir.py b/tools/assemble_uk_release_dir.py index 863cec7184..adf69ec5d3 100644 --- a/tools/assemble_uk_release_dir.py +++ b/tools/assemble_uk_release_dir.py @@ -59,6 +59,18 @@ "microcosm-build", "microcosm-calibrate", ) +#: The signed evidence a national release ships beside its manifests, in +#: release-manifest order: the artifact key, the release-directory filename, and +#: the name ``_assemble`` measures its digest under. +_EVIDENCE = ( + ("calibration_diagnostics", "calibration_diagnostics.json", "diagnostics"), + ("release_certification", "release_certification.json", "certification"), + ("terminal_gates", "terminal_gates.json", "calibration seam report"), + ("release_cut_gates", "release_cut_gates.json", "release-cut report"), + ("spine_gates", "spine_gates.json", "spine report"), + # The head-to-head with the reference (microcosm#1095). + ("score_vs_reference", "score_vs_reference.json", "score receipt"), +) def _uk_publisher_labels() -> dict[str, str]: @@ -369,18 +381,12 @@ def _assemble(args: argparse.Namespace) -> dict[str, object]: calibration_path.unlink(missing_ok=True) -def _stage_and_finalize( +def uk_national_release_manifests( *, - args: argparse.Namespace, - staging_parent: Path, - destination: Path, - npz_destination: Path, - calibration_path: Path, + measured: Mapping[str, str], calibration_filename: str, - household_weight: np.ndarray, - initial_household_weight: np.ndarray, + calibration_sha: str, household_weight_year: Mapping[str, object], - measured: Mapping[str, str], attempt_id: str, runtime: Mapping[str, str], code_pin: str, @@ -389,20 +395,20 @@ def _stage_and_finalize( spine_part: Mapping[str, object], seam_part: Mapping[str, object], release_cut_part: Mapping[str, object], - spine_report_path: Path, staging_delivery: Mapping[str, object], spi_marker: Mapping[str, object], -) -> dict[str, object]: - np.savez( - calibration_path, - household_weight=household_weight, - initial_household_weight=initial_household_weight, - ) - calibration_sha = _sha256(calibration_path) + created_at: str, + publisher_labels: Mapping[str, str], +) -> tuple[dict[str, object], dict[str, object]]: + """Return the national release build's build and release manifests. + + A pure function of its inputs: the assembler writes exactly these two + documents, and ``tools/generate_release_contract_fixtures.py`` writes the + release-contract golden fixtures (docs/release-contract.md, C1) with this + same function, so a change to either manifest's shape is a change to those + fixtures. + """ - created_at = datetime.now(UTC).isoformat() - release_dir = staging_parent / UK_NATIONAL_RELEASE_ID - release_dir.mkdir(parents=True) # The build is the calibration attempt: both manifests name it, and the # release, so the emitter can publish it into its own folder. build_manifest = { @@ -414,7 +420,7 @@ def _stage_and_finalize( "git_dirty": False, }, "build_sha": code_pin[:7], - "runtime": runtime, + "runtime": dict(runtime), "dataset": { "filename": _DATASET_FILENAME, "sha256": measured["candidate"], @@ -446,30 +452,6 @@ def _stage_and_finalize( "created_at": created_at, "staging": dict(staging_delivery), } - build_manifest_path = release_dir / "build_manifest.json" - _write_json(build_manifest_path, build_manifest) - - evidence = { - "calibration_diagnostics": ( - args.diagnostics_json, - "calibration_diagnostics.json", - ), - "release_certification": ( - args.certification_json, - "release_certification.json", - ), - "terminal_gates": (args.seam_gate_report, "terminal_gates.json"), - "release_cut_gates": ( - args.release_cut_gate_json, - "release_cut_gates.json", - ), - "spine_gates": (spine_report_path, "spine_gates.json"), - # The head-to-head with the reference (microcosm#1095). - "score_vs_reference": ( - args.score_receipt, - "score_vs_reference.json", - ), - } def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: return { @@ -526,55 +508,89 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: calibration_sha, ), **{ - key: artifact(key, "diagnostics", filename, measured[name]) - for key, (_source, filename), name in ( - ( - "calibration_diagnostics", - evidence["calibration_diagnostics"], - "diagnostics", - ), - ( - "release_certification", - evidence["release_certification"], - "certification", - ), - ( - "terminal_gates", - evidence["terminal_gates"], - "calibration seam report", - ), - ( - "release_cut_gates", - evidence["release_cut_gates"], - "release-cut report", - ), - ( - "spine_gates", - evidence["spine_gates"], - "spine report", - ), - ( - "score_vs_reference", - evidence["score_vs_reference"], - "score receipt", - ), - ) + key: artifact(key, "diagnostics", filename, measured[measured_as]) + for key, filename, measured_as in _EVIDENCE }, }, "description": ( "UK national calibration pipeline release build assembled from " f"attempt {attempt_id}." ), - "publisher_labels": _uk_publisher_labels(), + "publisher_labels": dict(publisher_labels), "licensed_data": {UK_SPI_PUBLIC_USE_TAPE_KEY: dict(spi_marker)}, } + return build_manifest, release_manifest + + +def _stage_and_finalize( + *, + args: argparse.Namespace, + staging_parent: Path, + destination: Path, + npz_destination: Path, + calibration_path: Path, + calibration_filename: str, + household_weight: np.ndarray, + initial_household_weight: np.ndarray, + household_weight_year: Mapping[str, object], + measured: Mapping[str, str], + attempt_id: str, + runtime: Mapping[str, str], + code_pin: str, + target_surface: Mapping[str, object], + target_registry: Mapping[str, object], + spine_part: Mapping[str, object], + seam_part: Mapping[str, object], + release_cut_part: Mapping[str, object], + spine_report_path: Path, + staging_delivery: Mapping[str, object], + spi_marker: Mapping[str, object], +) -> dict[str, object]: + np.savez( + calibration_path, + household_weight=household_weight, + initial_household_weight=initial_household_weight, + ) + calibration_sha = _sha256(calibration_path) + + created_at = datetime.now(UTC).isoformat() + release_dir = staging_parent / UK_NATIONAL_RELEASE_ID + release_dir.mkdir(parents=True) + build_manifest, release_manifest = uk_national_release_manifests( + measured=measured, + calibration_filename=calibration_filename, + calibration_sha=calibration_sha, + household_weight_year=household_weight_year, + attempt_id=attempt_id, + runtime=runtime, + code_pin=code_pin, + target_surface=target_surface, + target_registry=target_registry, + spine_part=spine_part, + seam_part=seam_part, + release_cut_part=release_cut_part, + staging_delivery=staging_delivery, + spi_marker=spi_marker, + created_at=created_at, + publisher_labels=_uk_publisher_labels(), + ) + build_manifest_path = release_dir / "build_manifest.json" + _write_json(build_manifest_path, build_manifest) release_manifest_path = release_dir / "release_manifest.json" _write_json(release_manifest_path, release_manifest) + sources = { + "calibration_diagnostics": args.diagnostics_json, + "release_certification": args.certification_json, + "terminal_gates": args.seam_gate_report, + "release_cut_gates": args.release_cut_gate_json, + "spine_gates": spine_report_path, + "score_vs_reference": args.score_receipt, + } evidence_summary: dict[str, dict[str, str]] = {} - for key, (source, filename) in evidence.items(): + for key, filename, _measured_as in _EVIDENCE: copy_path = release_dir / filename - shutil.copyfile(source, copy_path) + shutil.copyfile(sources[key], copy_path) evidence_summary[key] = { "path": str(destination / filename), "sha256": _sha256(copy_path), diff --git a/tools/generate_release_contract_fixtures.py b/tools/generate_release_contract_fixtures.py new file mode 100644 index 0000000000..f972111c4a --- /dev/null +++ b/tools/generate_release_contract_fixtures.py @@ -0,0 +1,571 @@ +"""Generate or verify the release-contract golden fixtures (version 1). + +docs/release-contract.md defines the release contract, C1 to C5. These fixtures +freeze two of its parts in bytes, the way ``generate_staging_contract_fixtures.py`` +freezes the staging documents that calibration-diagnostics byte-checks. Each +golden comes from the writer that produces the same file in a real build, and +``writers.json`` names that writer for every file ``SHA256SUMS`` lists. + +C1, the release manifest +------------------------ +One build folder's ``build_manifest.json`` and ``release_manifest.json`` for the +UK national release and for the US national release: + +* The UK pair. ``uk_national_release_manifests`` builds both documents and + ``_write_json`` serializes them; both live in + ``tools/assemble_uk_release_dir.py``. +* The US pair. ``_build_manifests`` in ``tools/build_us_fiscal_refresh_release.py`` + writes both manifests, and ``_finish_build_folder_release`` rewrites them into + the build-folder layout by calling + ``microcosm.data.build_folder_manifests.rewrite_release_dir``. The fixture + freezes that function's serialization of the builder's content. +* ``c1/inventory.json`` lists the files and certification fields the release + contract requires of the UK national release. The generator reads them from + ``microcosm.data.contract``. + +C5, publication +--------------- +One ``releases.json`` for each country's dataset repository, and +``c5/registry.json``, a snapshot of ``microcosm.data.registry.REGISTRY``. + +The emitter's release writer is the only writer of a live ``releases.json``. It +lives outside this repository, and ``microcosm_emitter_interface.releases`` +holds its rules. The generator builds each record from three sources: + +1. ``add_build`` with ``make_current=False``, the interface's change for a + publication; +2. ``make_current``, the interface's change for a promotion; +3. ``dataclasses.replace(record, default=...)``, the step + ``microcosm.build.build_folder_switch._switch_record`` takes to set + ``default``. The interface has no function that sets it. Both goldens name + the national release as the default. + +``ReleasesRecord.serialize`` then gives the bytes. + +Seams the generator replaces +---------------------------- +The UK writer is a pure function, so it needs no seam: the clock, the runtime +versions and each certification part's census arrive as arguments. + +The US builder reads the clock, the checkout and the installed packages through +module globals, and ``_build_manifests`` computes the calibration gate itself. +The generator replaces four globals of the builder's module and nothing else: + +* ``_runtime_versions`` returns the synthetic versions in ``US_RUNTIME``; +* ``_git_output`` returns one synthetic commit for ``rev-parse HEAD``; +* ``datetime`` becomes a clock fixed at ``FIXTURE_TIME``; +* ``_release_gate_failures`` returns no failures, so the US build manifest + records a passing calibration gate, as the UK inputs give each certification + part a passing census. + +Synthetic and live values +------------------------- +Every digest, version, identifier and gate count in the manifests and records +is synthetic. A digest is the SHA-256 of ``release-contract-fixture:``, so +no reader can mistake one for a real artifact; the three JSON files the US +builder hashes in its release directory hold +``{"release_contract_fixture": ""}`` instead, because the builder +parses the coverage file. The SPI Public Use Tape marker names one synthetic +stage; its study number and conditions are the live constants of +``microcosm.build.uk_runtime.spi_dependency``. + +Some values are live on purpose. ``c1/inventory.json`` and ``c5/registry.json`` +freeze the contract's constants and the registry. The US manifests carry what +the US builder writes for this generator's call, which passes +``_build_manifests`` only its required arguments and a staging block: the +layout of ``_build_manifests`` and ``rewrite_release_dir``, the gate-evidence keys +(``US_RELEASE_GATE_EVIDENCE_FILES``), the documented-absent inputs +(``US_DOCUMENTED_ABSENT_INPUTS``), the calibration diagnostics' schema version +(``CALIBRATION_DIAGNOSTICS_SCHEMA_VERSION``), the fiscal-target exclusion +receipt's key, the dataset and calibration keys and file names, and the +repository id. A pull request that changes one of those regenerates the +fixtures. A real build also writes its timing, its ledger provenance and its +optional gate blocks, and the fixtures freeze none of those. + +What the fixtures omit +---------------------- +No fixture holds a signed certification, a gate-battery report, calibration +diagnostics, a source-coverage file or a stored-input verdict. Those bind +digests of live registers, which most pull requests move. The tests in +``test_release_contract_fixtures.py`` pin exactly which refusals each omission +causes. + +Regenerate after a deliberate contract change, in the same pull request that +updates docs/release-contract.md:: + + uv run python tools/generate_release_contract_fixtures.py + +``--check`` regenerates into a temporary directory and fails, naming each file +that differs, unless every byte matches the committed fixtures. +""" + +from __future__ import annotations + +import argparse +import dataclasses +import hashlib +import importlib.util +import json +import shutil +import tempfile +from datetime import datetime +from pathlib import Path +from types import ModuleType, SimpleNamespace + +from microcosm_emitter_interface.releases import ( + ReleasesRecord, + add_build, + make_current, +) + +from microcosm.build.staging_v2 import validate_staging_delivery +from microcosm.build.uk_runtime.spi_dependency import uk_spi_public_use_tape_marker +from microcosm.build.uk_runtime.spi_income import SPI_DONOR_UKDS_STUDY +from microcosm.data import contract +from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY +from microcosm.data.releases_record import RELEASES_RECORD_PATH + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_OUTPUT = ( + ROOT + / "packages" + / "microcosm-data" + / "tests" + / "fixtures" + / "release_contract" + / "v1" +) +GENERATOR = "tools/generate_release_contract_fixtures.py" +ASSEMBLER = "tools/assemble_uk_release_dir.py" +US_BUILDER = "tools/build_us_fiscal_refresh_release.py" +INTERFACE_RELEASES = "microcosm_emitter_interface.releases" + +#: One instant for every timestamp the fixtures carry. +FIXTURE_TIME = "2026-01-01T00:00:00+00:00" +UK_RELEASE = contract._UK_NATIONAL_RELEASE_ID +US_RELEASE = contract.US_NATIONAL_RELEASE_ID +#: The UK national build's name: a calibration attempt ID. +UK_BUILD = "uk-frs-calibration-attempt-20260101T000000Z-00000000" +#: The US national build's name: a build ID with the ``populace-us-`` prefix +#: the US builder requires (``_assert_us_release_id``). +US_BUILD = "populace-us-2024-0000000-20260101" +UK_LINE = "national" +#: Synthetic runtime versions. Each is a resolved PEP 440 version, which is all the +#: contract asks of a runtime pin. +UK_RUNTIME = { + "python": "3.13.0", + "policyengine-core": "3.0.0", + "policyengine-uk": "2.0.0", + "microcosm-data": "0.1.0", + "microcosm-build": "0.1.0", + "microcosm-calibrate": "0.1.0", +} +#: The packages the US builder's ``_runtime_versions`` reports, in its order. +US_RUNTIME = { + "python": "3.13.0", + "microcosm-build": "0.1.0", + "microcosm-calibrate": "0.1.0", + "microcosm-data": "0.1.0", + "microcosm-frame": "0.1.0", + "policyengine-core": "3.0.0", + "policyengine-us": "1.0.0", + "numpy": "2.0.0", + "pandas": "2.0.0", + "torch": "2.0.0", +} +#: A successful version 2 staging delivery, matching the staging fixtures' +#: ``delivery_success`` case apart from its run id. +UK_STAGING_DELIVERY = { + "contract_version": 2, + "enabled": True, + "mode": "local_and_remote", + "run_id": "uk-national-release-contract-fixture", + "configured_repository": "policyengine/populace-uk-staging", + "upload_attempts": 6, + "upload_successes": 6, + "read_back": "passed", + "last_error_code": None, + "opt_out_reason": None, +} +#: One synthetic spine stage that reads the SPI Public Use Tape, so the UK +#: manifests carry the marker a tape-dependent national release restates +#: (microcosm#1095): the flag on the microdata entry and ``licensed_data``. +UK_SPI_STAGE = SimpleNamespace( + stage="release_contract_fixture_stage", + artifacts=[{"ukds_study_number": SPI_DONOR_UKDS_STUDY}], +) +#: The release-directory files the US builder hashes into its manifests. The +#: fixtures ship none of them. +_US_HASHED_FILES = ( + "calibration_diagnostics.json", + "us_source_coverage.json", + "us_ssi_take_up.json", +) + + +def _writer(module: str, function: str) -> dict[str, str]: + return {"module": module, "function": function} + + +_UK_MANIFEST_WRITERS = [ + _writer(ASSEMBLER, "uk_national_release_manifests"), + _writer(ASSEMBLER, "_write_json"), +] +_US_MANIFEST_WRITERS = [ + _writer(US_BUILDER, "_build_manifests"), + _writer(US_BUILDER, "_finish_build_folder_release"), + _writer("microcosm.data.build_folder_manifests", "rewrite_release_dir"), +] +_RELEASES_RECORD_WRITERS = [ + _writer(INTERFACE_RELEASES, "add_build"), + _writer(INTERFACE_RELEASES, "make_current"), + _writer("dataclasses", "replace"), + _writer(INTERFACE_RELEASES, "ReleasesRecord.serialize"), +] +#: Every fixture file ``SHA256SUMS`` lists, with the calls that produce its +#: bytes, in call order: the last one serializes. A module is a dotted name, or +#: a path from the repository root for a tool. ``_writers`` writes this table as +#: ``writers.json`` and refuses a run whose files it does not cover exactly. +WRITERS: dict[str, list[dict[str, str]]] = { + "c1/inventory.json": [_writer(GENERATOR, "_c1_inventory")], + f"c1/{UK_RELEASE}/build_manifest.json": _UK_MANIFEST_WRITERS, + f"c1/{UK_RELEASE}/release_manifest.json": _UK_MANIFEST_WRITERS, + f"c1/{US_RELEASE}/build_manifest.json": _US_MANIFEST_WRITERS, + f"c1/{US_RELEASE}/release_manifest.json": _US_MANIFEST_WRITERS, + "c5/registry.json": [_writer(GENERATOR, "_c5_registry")], + f"c5/uk/{RELEASES_RECORD_PATH}": _RELEASES_RECORD_WRITERS, + f"c5/us/{RELEASES_RECORD_PATH}": _RELEASES_RECORD_WRITERS, + "writers.json": [_writer(GENERATOR, "_writers")], +} + + +def fixture_digest(name: str) -> str: + """The synthetic SHA-256 the fixtures use for ``name``.""" + + return hashlib.sha256(_fixture_bytes(name)).hexdigest() + + +def _fixture_bytes(name: str) -> bytes: + """A stub file's bytes, whose SHA-256 is ``fixture_digest(name)``.""" + + return f"release-contract-fixture:{name}".encode() + + +def _fixture_commit() -> str: + return hashlib.sha1(b"release-contract-fixture").hexdigest() + + +def _load(tool: str) -> ModuleType: + """Import one of the repository's tools from its file.""" + + path = ROOT / tool + spec = importlib.util.spec_from_file_location(path.stem, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _json_bytes(payload: object) -> bytes: + return (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode() + + +def _c1_uk_national(root: Path, assembler: ModuleType) -> None: + """Write the UK national build folder's manifests with the UK assembler.""" + + measured = { + name: fixture_digest(name) + for name in ("candidate", *(name for _, _, name in assembler._EVIDENCE)) + } + build_manifest, release_manifest = assembler.uk_national_release_manifests( + measured=measured, + calibration_filename=f"{assembler._DATASET_KEY}_calibration.npz", + calibration_sha=fixture_digest("calibration"), + household_weight_year={"dataset_year": 2024, "basis": "dataset_year"}, + attempt_id=UK_BUILD, + runtime=UK_RUNTIME, + code_pin=_fixture_commit(), + target_surface={"sha256": fixture_digest("target surface"), "n_targets": 2}, + target_registry={"version": "release-contract-fixture-v1", "n_specs": 2}, + # Each part's statuses are the certifier's census of its gates by status + # (``_status_census``); a shippable part is all "passed". The counts are + # synthetic, so the fixture does not move when a UK gate scope grows. + spine_part={"statuses": {"passed": 3}}, + seam_part={"statuses": {"passed": 2}}, + release_cut_part={"statuses": {"passed": 4}}, + staging_delivery=validate_staging_delivery(UK_STAGING_DELIVERY), + spi_marker=uk_spi_public_use_tape_marker([UK_SPI_STAGE]), + created_at=FIXTURE_TIME, + publisher_labels={"ons": "Office for National Statistics"}, + ) + release_dir = root / "c1" / UK_RELEASE + assembler._write_json(release_dir / "build_manifest.json", build_manifest) + assembler._write_json(release_dir / "release_manifest.json", release_manifest) + + +def _c1_inventory(root: Path, assembler: ModuleType) -> None: + """Write what the live contract requires of the UK national release.""" + + dataset_role = contract.dataset_role_for_line(UK_LINE) + inventory = { + "schema_name": "microcosm.release-contract.c1-inventory", + "schema_version": 1, + "release_id": UK_RELEASE, + "line": contract.line_for_release_id(UK_RELEASE), + "dataset_role": dataset_role, + "release_role": contract.RELEASE_ROLES[dataset_role], + "publishes_to_build_folder": contract.publishes_to_build_folder(UK_RELEASE), + "retired_build_fields": list(contract.RETIRED_BUILD_FIELDS), + "release_manifest_schema_version": contract.RELEASE_MANIFEST_SCHEMA_VERSION, + "required_release_files": list(contract.required_release_files(UK_RELEASE)), + "release_directory_files": sorted( + [ + "build_manifest.json", + "release_manifest.json", + *(filename for _, filename, _ in assembler._EVIDENCE), + ] + ), + "certification": { + "file": contract._UK_RELEASE_CERTIFICATION_FILE, + "schema_version": contract._UK_RELEASE_CERTIFICATION_SCHEMA_VERSION, + "kind": contract._UK_RELEASE_CERTIFICATION_KIND, + "required_fields": sorted(contract._UK_CERTIFICATION_REQUIRED_FIELDS), + "part_evidence_files": dict(contract._UK_CERTIFICATION_PART_EVIDENCE_FILES), + "score_receipt_file": contract._UK_CERTIFICATION_SCORE_RECEIPT_FILE, + "gate_battery_phases": list(contract._UK_GATE_BATTERY_PHASES), + "signing_key_env": contract._UK_GATE_BATTERY_SIGNING_KEY_ENV, + }, + } + path = root / "c1" / "inventory.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_json_bytes(inventory)) + + +class _FixtureClock(datetime): + """``datetime`` whose ``now`` is the fixture instant.""" + + @classmethod + def now(cls, tz=None): + return datetime.fromisoformat(FIXTURE_TIME).astimezone(tz) + + +class _FixtureTargetRegistry: + """The two things ``_build_manifests`` reads from the target registry.""" + + version = "release-contract-fixture-v1" + + def __len__(self) -> int: + return 1 + + +def _c1_us_national(root: Path) -> None: + """Write the US national build folder's manifests with the US builder. + + The module docstring names the four globals of the builder's module this + replaces. Everything else is the builder's own code: ``_build_manifests``, + ``_staging_manifest_block`` and ``_finish_build_folder_release``. + """ + + builder = _load(US_BUILDER) + builder._runtime_versions = lambda: dict(US_RUNTIME) + builder._git_output = lambda *args: ( + _fixture_commit() if args == ("rev-parse", "HEAD") else "" + ) + builder.datetime = _FixtureClock + # Given a synthetic solve, the builder's own gate fails and lists every + # critical fiscal target the solve's diagnostics lack, so a golden that + # kept its verdict would move with the US critical-target list. This seam + # returns no failures, and the solve result below then needs no diagnostics. + builder._release_gate_failures = lambda *args, **kwargs: [] + with tempfile.TemporaryDirectory(prefix="release-contract-us-") as temporary: + work = Path(temporary) + release_dir = work / "releases" / US_RELEASE + release_dir.mkdir(parents=True) + artifact_root = work / "artifacts" + artifact_root.mkdir() + (artifact_root / builder.DATASET_FILENAME).write_bytes( + _fixture_bytes("dataset") + ) + (artifact_root / builder.CALIBRATION_FILENAME).write_bytes( + _fixture_bytes("calibration") + ) + for name in _US_HASHED_FILES: + # JSON, because the builder parses the coverage file for the + # fiscal-target exclusion receipt. + (release_dir / name).write_bytes( + json.dumps({"release_contract_fixture": name}).encode() + ) + builder._build_manifests( + release_id=US_BUILD, + release_dir=release_dir, + artifact_root=artifact_root, + result=SimpleNamespace( + initial_loss=2.0, final_loss=1.0, fraction_within_10pct=1.0 + ), + target_surface={ + "sha256": fixture_digest("target surface"), + "n_targets": 1, + }, + registry=_FixtureTargetRegistry(), + dropped={"dropped_target_names": []}, + target_profile_gate=builder.GateResult( + name="target_profile_coverage", + passed=True, + details={"requirements_checked": 1}, + ), + staging=builder._staging_manifest_block( + SimpleNamespace( + staging_bundle=object(), + run_id="us-national-release-contract-fixture", + repo_id="policyengine/populace-us-staging", + uploads_succeeded=True, + ) + ), + ) + builder._finish_build_folder_release( + release_dir, + build=US_BUILD, + artifact_root=artifact_root, + evidence_release=False, + ) + target = root / "c1" / US_RELEASE + target.mkdir(parents=True, exist_ok=True) + for name in ("build_manifest.json", "release_manifest.json"): + (target / name).write_bytes((release_dir / name).read_bytes()) + + +def _one_current_build(*, release: str, build: str, role: str) -> ReleasesRecord: + """A repository's record after one build is published, then promoted. + + The module docstring names the source of each of the three steps. + """ + + published = add_build( + ReleasesRecord.empty(), + release=release, + build=build, + release_role=role, + published_at=FIXTURE_TIME, + make_current=False, + ) + promoted = make_current(published, release=release, build=build) + return dataclasses.replace(promoted, default=release) + + +def _c5_releases(root: Path) -> None: + """Write each country's ``releases.json`` with the interface's serializer.""" + + records = { + "uk": _one_current_build( + release=UK_RELEASE, + build=UK_BUILD, + role=contract.RELEASE_ROLES[contract.dataset_role_for_line(UK_LINE)], + ), + "us": _one_current_build( + release=US_RELEASE, + build=US_BUILD, + role=contract.US_RELEASES[US_RELEASE], + ), + } + for country, record in records.items(): + path = root / "c5" / country / RELEASES_RECORD_PATH + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(record.serialize()) + + +def _c5_registry(root: Path) -> None: + """Write a snapshot of the live dataset registry.""" + + registry = { + "schema_name": "microcosm.release-contract.registry", + "schema_version": 1, + "default_variant": DEFAULT_VARIANT, + "entries": [ + {"key": list(key), **dataclasses.asdict(REGISTRY[key])} + for key in sorted(REGISTRY) + ], + } + path = root / "c5" / "registry.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_json_bytes(registry)) + + +def _writers(root: Path) -> None: + """Write ``writers.json``; refuse a run that ``WRITERS`` does not cover.""" + + path = root / "writers.json" + written = {*_tree(root), path.name} + if written != set(WRITERS): + raise SystemExit( + "WRITERS must name a writer for exactly the files the generator " + f"writes; it differs on {sorted(written ^ set(WRITERS))}" + ) + path.write_bytes( + _json_bytes( + { + "schema_name": "microcosm.release-contract.fixture-writers", + "schema_version": 1, + "files": {name: {"writers": WRITERS[name]} for name in sorted(WRITERS)}, + } + ) + ) + + +def _generate(root: Path) -> None: + root.mkdir(parents=True, exist_ok=True) + assembler = _load(ASSEMBLER) + _c1_uk_national(root, assembler) + _c1_inventory(root, assembler) + _c1_us_national(root) + _c5_releases(root) + _c5_registry(root) + _writers(root) + checksums = [ + f"{hashlib.sha256(content).hexdigest()} {name}" + for name, content in sorted(_tree(root).items()) + ] + (root / "SHA256SUMS").write_text("\n".join(checksums) + "\n") + + +def _tree(root: Path) -> dict[str, bytes]: + return { + path.relative_to(root).as_posix(): path.read_bytes() + for path in root.rglob("*") + if path.is_file() + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Generate or verify the release-contract golden fixtures." + ) + parser.add_argument("--check", action="store_true") + parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) + args = parser.parse_args(argv) + + with tempfile.TemporaryDirectory(prefix="microcosm-release-contract-") as temporary: + generated = Path(temporary) / "v1" + _generate(generated) + if args.check: + fresh, committed = _tree(generated), _tree(args.output) + differing = sorted( + name + for name in set(fresh) | set(committed) + if fresh.get(name) != committed.get(name) + ) + if differing: + raise SystemExit( + f"release-contract fixtures are not reproducible: {differing} " + "differ. Regenerate with `uv run python " + "tools/generate_release_contract_fixtures.py` and update " + "docs/release-contract.md in the same change" + ) + return 0 + if args.output.exists(): + shutil.rmtree(args.output) + shutil.copytree(generated, args.output) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())