From 76864f1115ed212a8fec3951372e6d30963cfd8d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:11:52 +0400 Subject: [PATCH 01/10] Test that the UK certification tool takes a build in its own folder The policyengine.py certification tool reads a UK national build only at a Hugging Face tag. These tests describe the build-folder form (#1762): the build named by --national-build and --dense-build, refused unless releases.json at main lists it and has not withdrawn it, pinned at the commit that published its folder or one the operator names, and handed to certify-data as its folder's manifest at that commit. They also cover the kept local-area build, the regional microdata download, the regional constant rewrite, resume, the changelog fragment, the commit message and the pull request body. Co-Authored-By: Claude Opus 5.5 --- .../test_certify_uk_cut_in_policyengine_py.py | 637 +++++++++++++++--- ...st_certify_uk_cut_rehearsal_regressions.py | 206 ++++-- 2 files changed, 674 insertions(+), 169 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py index b4d124b368..ef51d8e9a6 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py @@ -3,8 +3,12 @@ from __future__ import annotations import argparse +import dataclasses +import hashlib import json +import re import subprocess +from types import SimpleNamespace import pytest from hypothesis import given, settings @@ -12,16 +16,76 @@ from tools import certify_uk_cut_in_policyengine_py as handoff -NATIONAL = "microcosm-uk-2024-25-national-20261021T195620Z-a858c100" -DENSE = "microcosm-uk-2024-25-dense-20261019T000432Z-ee5c2dbe" -NEW_DENSE = "microcosm-uk-2024-25-dense-20261026T010203Z-0badc0de" +NATIONAL = "uk-frs-calibration-attempt-20261021T195620Z-a858c100" +DENSE = "uk-local-candidate-f100-s42-20261019T000432Z-ee5c2dbe" +NEW_DENSE = "uk-local-candidate-f100-s42-20261026T010203Z-0badc0de" +NATIONAL_COMMIT = "4a3b77ac" * 5 +DENSE_COMMIT = "9da09946" * 5 +NEW_DENSE_COMMIT = "0badc0de" * 5 +#: A national build as it was named while UK builds were tagged. +NATIONAL_TAG = "microcosm-uk-2024-25-national-20261021T195620Z-a858c100" + + +def _build(release, build, commit, model="2.134.4", claims=None): + return handoff.PublishedBuild( + release=release, + build=build, + commit=commit, + model=model, + core="3.33.3", + claims=(f"=={model}",) if claims is None else claims, + ) + + +def test_a_build_is_named_by_its_name_and_optionally_its_commit(): + args = handoff.parse( + ["--national-build", NATIONAL, "--drop-regional-release", "--pepy-repo", "p"] + ) + assert (args.national_build, args.national_data_commit) == (NATIONAL, None) + args = handoff.parse( + ["--national-build", NATIONAL, "--national-data-commit", NATIONAL_COMMIT, + "--dense-build", DENSE, "--dense-data-commit", DENSE_COMMIT, + "--pepy-repo", "p"] + ) # fmt: skip + assert (args.national_data_commit, args.dense_build, args.dense_data_commit) == ( + NATIONAL_COMMIT, + DENSE, + DENSE_COMMIT, + ) -def test_only_cut_tags_are_certified(): - assert handoff.check_tag(NATIONAL, "national") == NATIONAL - for bad in ("main", NATIONAL + "x", DENSE, "microcosm-uk-2024-25-national"): - with pytest.raises(handoff.CertifyError, match="never @main"): - handoff.check_tag(bad, "national") +@pytest.mark.parametrize( + ("national", "message"), + [ + # policyengine.py refuses every tagged manifest from a repository + # with releases.json, so a tag no longer names a build. + (["--national-tag", NATIONAL_TAG], "required: --national-build"), + (["--national-build", "../" + NATIONAL], "is not a build name"), + (["--national-build", "releases/x"], "is not a build name"), + # A branch or a short commit moves or is ambiguous; a pin is a commit. + ( + ["--national-build", NATIONAL, "--national-data-commit", "main"], + "--national-data-commit must be a full 40-character commit", + ), + ( + [ + "--national-build", + NATIONAL, + "--national-data-commit", + NATIONAL_COMMIT[:9], + ], + "--national-data-commit must be a full 40-character commit", + ), # fmt: skip + ( + ["--national-build", NATIONAL, "--dense-data-commit", DENSE_COMMIT], + "--dense-data-commit goes with --dense-build", + ), + ], +) +def test_only_a_safe_build_name_and_a_full_commit_are_taken(national, message, capsys): + with pytest.raises(SystemExit): + handoff.parse([*national, "--drop-regional-release", "--pepy-repo", "p"]) + assert message in capsys.readouterr().err @pytest.mark.parametrize( @@ -33,13 +97,13 @@ def test_only_cut_tags_are_certified(): ], ) def test_coverage_is_built_with_or_an_exact_claim(model, claims, version, covered): - cut = handoff.CutVersions(tag=DENSE, model=model, core="3.33.3", claims=claims) - assert handoff.covers(cut, version) is covered + build = _build(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT, model, claims) + assert handoff.covers(build, version) is covered def _args(**kwargs): base = dict( - dense_tag=None, + dense_build=None, keep_regional_release=False, area_coded_national_uri=None, drop_regional_release=False, @@ -47,32 +111,74 @@ def _args(**kwargs): return argparse.Namespace(**{**base, **kwargs}) +def test_a_build_is_certified_from_its_folder_at_its_commit(): + assert handoff.manifest_uri( + handoff.NATIONAL_RELEASE, NATIONAL, NATIONAL_COMMIT + ) == ( + f"hf://dataset/policyengine/populace-uk-private@{NATIONAL_COMMIT}" + f"/releases/microcosm-uk-2024-25-national/{NATIONAL}/release_manifest.json" + ) + build = _build(handoff.NATIONAL_RELEASE, NATIONAL, NATIONAL_COMMIT) + assert build.manifest_uri == handoff.manifest_uri( + handoff.NATIONAL_RELEASE, NATIONAL, NATIONAL_COMMIT + ) + assert build.pin == handoff.BuildPin( + handoff.NATIONAL_RELEASE, NATIONAL, NATIONAL_COMMIT + ) + + def test_each_route_produces_its_certify_data_flags(): - record = {"regional_source_manifest_uri": handoff.manifest_uri(DENSE, "x")} - dense = handoff.regional_flags(_args(dense_tag=NEW_DENSE), record) - assert dense[0] == "--regional-manifest-uri" and f"@{NEW_DENSE}/" in dense[1] - assert handoff.regional_tag(dense) == NEW_DENSE - kept = handoff.regional_flags(_args(keep_regional_release=True), record) + record = { + "regional_source_manifest_uri": handoff.manifest_uri( + handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT + ) + } + new = _build(handoff.DENSE_RELEASE, NEW_DENSE, NEW_DENSE_COMMIT) + dense = handoff.regional_flags(_args(dense_build=NEW_DENSE), record, new) + assert dense == ["--regional-manifest-uri", new.manifest_uri] + kept = handoff.regional_flags(_args(keep_regional_release=True), record, None) assert kept == ["--regional-manifest-uri", record["regional_source_manifest_uri"]] - area = handoff.regional_flags(_args(area_coded_national_uri="hf://model/x@1/r"), {}) + area = handoff.regional_flags( + _args(area_coded_national_uri="hf://model/x@1/r"), {}, None + ) assert area[-2:] == ["--regional-release-kind", "area_coded_national"] - assert handoff.regional_tag(area) is None - dropped = handoff.regional_flags(_args(drop_regional_release=True), record) + dropped = handoff.regional_flags(_args(drop_regional_release=True), record, None) assert dropped == ["--drop-regional-release"] with pytest.raises(handoff.CertifyError, match="no regional release"): - handoff.regional_flags(_args(keep_regional_release=True), {}) + handoff.regional_flags(_args(keep_regional_release=True), {}, None) + + +def test_only_a_folder_manifest_in_the_build_repository_names_a_build(): + uri = handoff.manifest_uri(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT) + assert handoff.folder_reference(uri) == handoff.BuildPin( + handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT + ) + tagged = ( + "hf://dataset/policyengine/populace-uk-private@microcosm-uk-2024-25-dense-" + "20261019T000432Z-ee5c2dbe/releases/microcosm-uk-2024-25-dense/" + "release_manifest.json" + ) + for other in ( + tagged, + uri.replace("populace-uk-private", "policyengine-uk-data-private"), + uri.replace("release_manifest.json", "build_manifest.json"), + "hf://model/x@1/r", + "", + None, + ): + assert handoff.folder_reference(other) is None def test_routes_are_mutually_exclusive_and_required(): repo = ["--pepy-repo", "pepy"] with pytest.raises(SystemExit): - handoff.parse(["--national-tag", NATIONAL, *repo]) + handoff.parse(["--national-build", NATIONAL, *repo]) with pytest.raises(SystemExit): handoff.parse( [ - "--national-tag", + "--national-build", NATIONAL, - "--dense-tag", + "--dense-build", DENSE, "--drop-regional-release", *repo, @@ -80,28 +186,41 @@ def test_routes_are_mutually_exclusive_and_required(): ) with pytest.raises(SystemExit): handoff.parse( - ["--national-tag", NATIONAL, "--drop-regional-release", "--open-pr", *repo] + [ + "--national-build", + NATIONAL, + "--drop-regional-release", + "--open-pr", + *repo, + ] ) # The policyengine.py clone is the operator's to name; no machine's layout. with pytest.raises(SystemExit): - handoff.parse(["--national-tag", NATIONAL, "--drop-regional-release"]) + handoff.parse(["--national-build", NATIONAL, "--drop-regional-release"]) -def test_the_regional_tag_is_rewritten_only_as_a_literal(tmp_path): +def test_the_regional_build_and_commit_are_rewritten_only_as_literals(tmp_path): for relative in handoff.CONSTANT_FILES: path = tmp_path / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_text( - f'A = "{DENSE}"\nB = "hf://x@{DENSE}/releases/r.json"\n' - f"# {DENSE} in a comment stays\nC = 'x{DENSE}'\n" + f'A = "{DENSE}"\nB = "releases/r/{DENSE}/x.h5"\n' + f'R = "{DENSE_COMMIT}"\nU = "x.h5@{DENSE_COMMIT}"\n' + f"# {DENSE} at {DENSE_COMMIT} in a comment stays\nC = 'x{DENSE}'\n" ) - changed = handoff.rewrite_regional_constants(tmp_path, DENSE, NEW_DENSE) + old = handoff.BuildPin(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT) + new = handoff.BuildPin(handoff.DENSE_RELEASE, NEW_DENSE, NEW_DENSE_COMMIT) + changed = handoff.rewrite_regional_constants(tmp_path, old, new) assert sorted(changed) == sorted(handoff.CONSTANT_FILES) text = (tmp_path / handoff.CONSTANT_FILES[0]).read_text() assert f'A = "{NEW_DENSE}"' in text - assert f"@{NEW_DENSE}/releases" in text - assert f"# {DENSE} in a comment stays" in text - assert handoff.rewrite_regional_constants(tmp_path, DENSE, DENSE) == [] + assert f'"releases/r/{NEW_DENSE}/x.h5"' in text + assert f'R = "{NEW_DENSE_COMMIT}"' in text + assert f'U = "x.h5@{NEW_DENSE_COMMIT}"' in text + assert f"# {DENSE} at {DENSE_COMMIT} in a comment stays" in text + assert handoff.rewrite_regional_constants(tmp_path, new, new) == [] + assert handoff.rewrite_regional_constants(tmp_path, None, new) == [] + assert handoff.rewrite_regional_constants(tmp_path, new, None) == [] @given( @@ -120,8 +239,11 @@ def test_the_rewrite_is_a_bijection_on_literals(tmp_path_factory, old, new): path = root / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_text(original) - handoff.rewrite_regional_constants(root, old, new) - handoff.rewrite_regional_constants(root, new, old) + commit = "c" * 40 + before = handoff.BuildPin(handoff.DENSE_RELEASE, old, commit) + after = handoff.BuildPin(handoff.DENSE_RELEASE, new, commit) + handoff.rewrite_regional_constants(root, before, after) + handoff.rewrite_regional_constants(root, after, before) for relative in handoff.CONSTANT_FILES: assert (root / relative).read_text() == original @@ -136,7 +258,8 @@ def test_dropped_overlays_are_reported(): def test_the_pr_body_leaves_every_judgment_to_a_person(): body = handoff.pr_body( { - "national_tag": NATIONAL, + "national_build": NATIONAL, + "national_commit": NATIONAL_COMMIT, "model": "2.134.4", "core": "3.33.3", "regional_summary": "`--drop-regional-release`", @@ -150,6 +273,8 @@ def test_the_pr_body_leaves_every_judgment_to_a_person(): } ) for needed in ( + f"Microcosm UK national build `{NATIONAL}`", + f"`{NATIONAL_COMMIT}`", "UC floor acceptance", "enhanced_frs_2024_25", "Certification warnings", @@ -158,6 +283,26 @@ def test_the_pr_body_leaves_every_judgment_to_a_person(): "- [ ]", ): assert needed in body + assert NATIONAL_TAG not in body and "cut" not in body.split("\n", 1)[0] + + +def test_the_pr_body_asks_for_a_check_when_old_builds_shared_a_commit(): + """policyengine.py's rewrite moves every quoted copy of the old national + commit, so a local-area constant that shared it moves too.""" + + context = { + "national_build": NATIONAL, + "national_commit": NATIONAL_COMMIT, + "model": "2.134.4", + "core": "3.33.3", + "regional_summary": "`--keep-regional-release`", + "microcosm_commit": "a" * 40, + "commands": [], + } + assert "shared commit" not in handoff.pr_body(context) + body = handoff.pr_body({**context, "shared_old_commit": DENSE_COMMIT}) + assert f"shared commit `{DENSE_COMMIT}`" in body + assert "- [ ] **Local-area revision constants.**" in body MISMATCH = [ @@ -170,32 +315,45 @@ def test_the_pr_body_leaves_every_judgment_to_a_person(): ] -def _dense_route(monkeypatch, tmp_path, *, audit_support=None): - """A national cut on 2.134.4 and a regional cut on 2.132.6, offline.""" +def _dense_route( + monkeypatch, tmp_path, *, audit_support=None, regional_uri=None, printed=None +): + """A national build on 2.134.4 and a local-area build on 2.132.6, offline. - cuts = { - NATIONAL: handoff.CutVersions(NATIONAL, "2.134.4", "3.33.3", ("==2.134.4",)), - DENSE: handoff.CutVersions(DENSE, "2.132.6", "3.33.3", ("==2.132.6",)), + Returns the builds read (release, build, commit) and the local-area + builds whose microdata was downloaded. + """ + + builds = { + NATIONAL: _build(handoff.NATIONAL_RELEASE, NATIONAL, NATIONAL_COMMIT), + DENSE: _build(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT, "2.132.6"), } - monkeypatch.setattr(handoff, "read_cut", lambda tag, release: cuts[tag]) - monkeypatch.setattr(handoff, "writer_check", lambda tag, repo: []) + reads, downloads = [], [] + + def read(release, build, *, commit=None, **kwargs): + reads.append((release, build, commit)) + found = builds[build] + return found if commit is None else _replace(found, commit=commit) + + monkeypatch.setattr(handoff, "read_published_build", read) + monkeypatch.setattr(handoff, "writer_check", lambda build, repo: []) monkeypatch.setattr( handoff, "regional_audit_support", lambda repo, base: audit_support ) - downloads = [] monkeypatch.setattr( handoff, "fetch_regional_microdata", - lambda tag, release, **kw: downloads.append(tag) or {}, + lambda build, **kw: downloads.append(build.build) or {}, ) monkeypatch.setattr( handoff.subprocess, "run", lambda *a, **k: handoff.subprocess.CompletedProcess(a, 0, "", ""), ) - bundle = ( - '{"data_releases": {"uk": {"regional_source_manifest_uri": ' - f'"{handoff.manifest_uri(DENSE, handoff.DENSE_RELEASE)}"}}}}}}' + if regional_uri is None: + regional_uri = handoff.manifest_uri(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT) + bundle = json.dumps( + {"data_releases": {"uk": {"regional_source_manifest_uri": regional_uri}}} ) def check_output(argv, **kwargs): @@ -206,12 +364,18 @@ def check_output(argv, **kwargs): return "b" * 40 monkeypatch.setattr(handoff.subprocess, "check_output", check_output) - return downloads + return reads, downloads + +def _replace(build, **changes): + return dataclasses.replace(build, **changes) -def test_a_dry_run_refuses_an_uncovered_dense_cut_before_writing(monkeypatch, tmp_path): - downloads = _dense_route(monkeypatch, tmp_path) - base = ["--national-tag", NATIONAL, "--keep-regional-release", "--dry-run", + +def test_a_dry_run_refuses_an_uncovered_dense_build_before_writing( + monkeypatch, tmp_path +): + reads, downloads = _dense_route(monkeypatch, tmp_path) + base = ["--national-build", NATIONAL, "--keep-regional-release", "--dry-run", "--pepy-repo", str(tmp_path)] # fmt: skip with pytest.raises( handoff.CertifyError, match="built with policyengine-uk 2.132.6" @@ -221,20 +385,86 @@ def test_a_dry_run_refuses_an_uncovered_dense_cut_before_writing(monkeypatch, tm assert handoff.certify(handoff.parse([*base, *MISMATCH])) == 0 assert downloads == [] another = handoff.parse( - ["--national-tag", NATIONAL, "--dense-tag", DENSE, "--dry-run", + ["--national-build", NATIONAL, "--dense-build", DENSE, "--dry-run", "--pepy-repo", str(tmp_path)] ) # fmt: skip - monkeypatch.setattr(handoff, "writer_check", lambda tag, repo: ["#700 open"]) + monkeypatch.setattr(handoff, "writer_check", lambda build, repo: ["#700 open"]) with pytest.raises(handoff.CertifyError, match="already being certified"): handoff.certify(another) +def test_a_kept_local_area_build_is_read_at_the_bundles_commit( + monkeypatch, tmp_path, capsys +): + """The bundle pins its local-area build by folder and commit; the route + reads that build there, so its model check and audit still run.""" + + reads, _ = _dense_route(monkeypatch, tmp_path) + args = handoff.parse( + ["--national-build", NATIONAL, "--keep-regional-release", "--dry-run", + "--pepy-repo", str(tmp_path), *MISMATCH] + ) # fmt: skip + assert handoff.certify(args) == 0 + assert reads == [ + (handoff.NATIONAL_RELEASE, NATIONAL, None), + (handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT), + ] + output = capsys.readouterr().out + plan = json.loads(output[output.find("{") :]) + assert plan["regional"].endswith("(regional built on 2.132.6; mismatch accepted)") + + +def test_a_named_build_and_its_commit_reach_certify_data(monkeypatch, tmp_path, capsys): + reads, _ = _dense_route(monkeypatch, tmp_path) + args = handoff.parse( + ["--national-build", NATIONAL, "--national-data-commit", "1" * 40, + "--dense-build", DENSE, "--dense-data-commit", "2" * 40, + "--accept-regional-model-mismatch", "recorded", "--audited-by", "A", + "--regional-limitation", "L", "--dry-run", "--pepy-repo", str(tmp_path)] + ) # fmt: skip + assert handoff.certify(args) == 0 + assert reads == [ + (handoff.NATIONAL_RELEASE, NATIONAL, "1" * 40), + (handoff.DENSE_RELEASE, DENSE, "2" * 40), + ] + output = capsys.readouterr().out + plan = json.loads(output[output.find("{") :]) + assert plan["national_build"] == NATIONAL + assert plan["national_manifest_uri"] == handoff.manifest_uri( + handoff.NATIONAL_RELEASE, NATIONAL, "1" * 40 + ) + assert ( + handoff.manifest_uri(handoff.DENSE_RELEASE, DENSE, "2" * 40) + in (plan["regional"]) + ) + assert plan["branch"] == "certify-uk-a858c100" + + +def test_a_kept_tagged_regional_release_refuses_before_any_read(monkeypatch, tmp_path): + """policyengine.py refuses a tagged manifest from a repository with + releases.json, so keeping one could never certify.""" + + tagged = ( + "hf://dataset/policyengine/populace-uk-private@microcosm-uk-2024-25-dense-" + "20261019T000432Z-ee5c2dbe/releases/microcosm-uk-2024-25-dense/" + "release_manifest.json" + ) + reads, _ = _dense_route(monkeypatch, tmp_path, regional_uri=tagged) + args = handoff.parse( + ["--national-build", NATIONAL, "--keep-regional-release", "--dry-run", + "--pepy-repo", str(tmp_path)] + ) # fmt: skip + with pytest.raises(handoff.CertifyError, match="not a build in its own folder"): + handoff.certify(args) + assert [read[1] for read in reads] == [NATIONAL] + + def test_a_base_without_the_audit_refuses_before_any_download(monkeypatch, tmp_path): - downloads = _dense_route( + _, downloads = _dense_route( monkeypatch, tmp_path, audit_support=f"it has no {handoff.AUDIT_SCRIPT}" ) args = handoff.parse( - ["--national-tag", NATIONAL, "--keep-regional-release", + ["--national-build", NATIONAL, "--keep-regional-release", "--pepy-repo", str(tmp_path), "--skip-tests", *MISMATCH] ) # fmt: skip with pytest.raises(handoff.CertifyError, match="policyengine.py#699"): @@ -255,12 +485,12 @@ def test_an_accepted_mismatch_needs_an_auditor_and_a_limitation(drop): del flags[index : index + 2] with pytest.raises(SystemExit): handoff.parse( - ["--national-tag", NATIONAL, "--keep-regional-release", + ["--national-build", NATIONAL, "--keep-regional-release", "--pepy-repo", "p", *flags] ) # fmt: skip with pytest.raises(SystemExit): handoff.parse( - ["--national-tag", NATIONAL, "--keep-regional-release", + ["--national-build", NATIONAL, "--keep-regional-release", "--pepy-repo", "p", *drop] ) # fmt: skip @@ -274,7 +504,7 @@ def test_a_mismatch_needs_readable_text_in_every_field(flag, text): flags[flags.index(flag) + 1] = text with pytest.raises(SystemExit): handoff.parse( - ["--national-tag", NATIONAL, "--keep-regional-release", + ["--national-build", NATIONAL, "--keep-regional-release", "--pepy-repo", "p", *flags] ) # fmt: skip assert handoff.readable("ok") and not handoff.readable(text) @@ -297,53 +527,260 @@ def run(argv, **kwargs): assert handoff.AUDIT_SCRIPT in handoff.regional_audit_support(tmp_path, "c" * 40) -def test_every_regional_microdata_file_is_fetched_and_checked(monkeypatch, tmp_path): - import hashlib - import sys - import types - - files = {"dense.h5": b"dense", "other.H5": b"other", "notes.csv": b"csv"} - for name, data in files.items(): - (tmp_path / name).write_bytes(data) - manifest = { - "artifacts": { - "microcosm_uk_2024_25_dense": { - "kind": "microdata", "path": "dense.h5", "revision": "r1", - "sha256": hashlib.sha256(b"dense").hexdigest(), +class FakeHub: + """The Hub calls the tool makes, answered from ``files``. + + ``files`` maps ``(repo_id, path, revision)`` to bytes, and + ``last_commits`` maps a path to its last commit on ``main``. + """ + + def __init__(self, root, files, last_commits=None): + self.root, self.files = root, files + self.last_commits = last_commits or {} + self.downloads, self.listings = [], [] + + def hf_hub_download(self, repo_id, filename, *, repo_type=None, revision=None, + **options): # fmt: skip + assert repo_type == "dataset" + self.downloads.append((repo_id, filename, revision, options)) + key = (repo_id, filename, revision) + if key not in self.files: + raise FileNotFoundError(f"{repo_id} has no {filename} at {revision}") + path = self.root / hashlib.sha256(repr(key).encode()).hexdigest() + path.write_bytes(self.files[key]) + return str(path) + + def get_paths_info(self, repo_id, paths, *, expand=False, revision=None, + repo_type=None): # fmt: skip + self.listings.append((repo_id, list(paths), expand, revision, repo_type)) + return [ + SimpleNamespace(path=path, last_commit=SimpleNamespace(oid=commit)) + for path, commit in self.last_commits.items() + if path in paths + ] + + +REPO = "policyengine/populace-uk-private" + + +def _folder(release, build): + return f"releases/{release}/{build}" + + +def _releases_record(withdrawn=()): + def release(role, build): + return { + "role": role, + "current": None, + "builds": { + build: { + "published_at": "2026-11-09T15:41:23+00:00", + "withdrawn": build in withdrawn, + } }, - "second": { - "kind": "microdata", "path": "other.H5", "revision": "r2", - "sha256": hashlib.sha256(b"other").hexdigest(), + } + + return json.dumps( + { + "schema_version": 1, + "default": handoff.NATIONAL_RELEASE, + "releases": { + handoff.NATIONAL_RELEASE: release("national", NATIONAL), + handoff.DENSE_RELEASE: release("local_area", DENSE), }, - "table": {"kind": "microdata", "path": "notes.csv", "revision": "r3", - "sha256": "0" * 64}, - "receipt": {"kind": "evidence", "path": "dense.h5", "revision": "r4", - "sha256": "0" * 64}, } - } # fmt: skip - (tmp_path / "release_manifest.json").write_text(json.dumps(manifest)) + ).encode() + + +def _folder_manifest(release, build, **changes): + manifest = { + "release": release, + "build": build, + "built_at": "2026-11-09T15:00:00+00:00", + "built_with_model_package": {"name": "policyengine-uk", "version": "2.179.2"}, + "built_with_core_package": {"name": "policyengine-core", "version": "3.34.10"}, + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": "==2.179.2"} + ], + "artifacts": {}, + } + return json.dumps({**manifest, **changes}).encode() + - def download(repo, path, **kwargs): - name = path.rsplit("/", 1)[-1] - return str( - tmp_path / ("release_manifest.json" if name.endswith(".json") else name) +def _national_hub(tmp_path, *, withdrawn=(), manifest=None, at=NATIONAL_COMMIT): + folder = _folder(handoff.NATIONAL_RELEASE, NATIONAL) + files = { + (REPO, "releases.json", "main"): _releases_record(withdrawn), + (REPO, f"{folder}/release_manifest.json", at): manifest + or _folder_manifest(handoff.NATIONAL_RELEASE, NATIONAL), + } + return FakeHub( + tmp_path, files, {f"{folder}/release_manifest.json": NATIONAL_COMMIT} + ) + + +def test_a_listed_build_is_read_at_the_commit_that_published_its_folder(tmp_path): + hub = _national_hub(tmp_path) + build = handoff.read_published_build(handoff.NATIONAL_RELEASE, NATIONAL, api=hub) + assert build == handoff.PublishedBuild( + release=handoff.NATIONAL_RELEASE, + build=NATIONAL, + commit=NATIONAL_COMMIT, + model="2.179.2", + core="3.34.10", + claims=("==2.179.2",), + ) + folder = _folder(handoff.NATIONAL_RELEASE, NATIONAL) + assert hub.listings == [ + (REPO, [f"{folder}/release_manifest.json"], True, "main", "dataset") + ] + record, manifest = hub.downloads + # A record cached before a withdrawal must not offer the build. + assert record[:3] == (REPO, "releases.json", "main") + assert record[3].get("force_download") is True + assert manifest[:3] == (REPO, f"{folder}/release_manifest.json", NATIONAL_COMMIT) + + +def test_an_operators_commit_replaces_the_publishing_commit(tmp_path): + other = "5" * 40 + hub = _national_hub(tmp_path, at=other) + build = handoff.read_published_build( + handoff.NATIONAL_RELEASE, NATIONAL, commit=other, api=hub + ) + assert build.commit == other + assert hub.listings == [] + + +@pytest.mark.parametrize( + ("hub_changes", "build", "message"), + [ + ({"withdrawn": (NATIONAL,)}, NATIONAL, "has been withdrawn"), + ({}, NATIONAL + "-x", "does not list build"), + ( + {"manifest": _folder_manifest(handoff.NATIONAL_RELEASE, DENSE)}, + NATIONAL, + f"names release 'microcosm-uk-2024-25-national' and build '{DENSE}'", + ), + ( + { + "manifest": _folder_manifest( + handoff.NATIONAL_RELEASE, NATIONAL, built_with_core_package={} + ) + }, + NATIONAL, + "no built_with_core_package version", + ), + ( + {"manifest": json.dumps({"build": {"cut_tag": NATIONAL_TAG}}).encode()}, + NATIONAL, + "names release None", + ), + ], +) +def test_a_build_policyengine_py_would_refuse_is_refused_first( + tmp_path, hub_changes, build, message +): + hub = _national_hub(tmp_path, **hub_changes) + with pytest.raises(handoff.CertifyError, match=re.escape(message)): + handoff.read_published_build(handoff.NATIONAL_RELEASE, build, api=hub) + + +def test_a_build_with_no_folder_on_main_is_refused(tmp_path): + hub = _national_hub(tmp_path) + hub.last_commits = {} + with pytest.raises(handoff.CertifyError, match="has no releases/"): + handoff.read_published_build(handoff.NATIONAL_RELEASE, NATIONAL, api=hub) + hub = _national_hub(tmp_path, at="6" * 40) + with pytest.raises(handoff.CertifyError, match="could not read"): + handoff.read_published_build( + handoff.NATIONAL_RELEASE, NATIONAL, commit="7" * 40, api=hub ) - monkeypatch.setitem( - sys.modules, "huggingface_hub", types.SimpleNamespace(hf_hub_download=download) + +def _dense_hub(tmp_path, artifacts, data): + folder = _folder(handoff.DENSE_RELEASE, DENSE) + manifest = _folder_manifest(handoff.DENSE_RELEASE, DENSE, artifacts=artifacts) + return FakeHub( + tmp_path, + {(REPO, f"{folder}/release_manifest.json", DENSE_COMMIT): manifest, **data}, ) + + +def test_every_regional_microdata_file_is_fetched_and_checked(tmp_path): + folder = _folder(handoff.DENSE_RELEASE, DENSE) + digest = {name: hashlib.sha256(name.encode()).hexdigest() + for name in ("dense", "other", "far")} # fmt: skip + artifacts = { + # The build's own files are bare names, alone or after the folder, + # with no revision: they are read in the folder at the build's commit. + "microcosm_uk_2024_25_dense": { + "kind": "microdata", "path": "dense.h5", "repo_id": REPO, + "role": "dataset", "sha256": digest["dense"], + }, + "second": { + "kind": "microdata", "path": f"{folder}/other.H5", "repo_id": REPO, + "sha256": digest["other"], + }, + # A file in another repository keeps its own path and revision. + "elsewhere": { + "kind": "microdata", "path": "x/far.h5", + "repo_id": "policyengine/another", "revision": "r9", + "sha256": digest["far"], + }, + "table": {"kind": "microdata", "path": "notes.csv", "repo_id": REPO, + "sha256": "0" * 64}, + "receipt": {"kind": "evidence", "path": "dense.h5", "repo_id": REPO, + "sha256": "0" * 64}, + } # fmt: skip + data = { + (REPO, f"{folder}/dense.h5", DENSE_COMMIT): b"dense", + (REPO, f"{folder}/other.H5", DENSE_COMMIT): b"other", + ("policyengine/another", "x/far.h5", "r9"): b"far", + } + hub = _dense_hub(tmp_path, artifacts, data) + dense = _build(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT) found = handoff.fetch_regional_microdata( - DENSE, handoff.DENSE_RELEASE, timings=tmp_path / "t.jsonl" + dense, timings=tmp_path / "t.jsonl", api=hub ) - assert found == { - "microcosm_uk_2024_25_dense": tmp_path / "dense.h5", - "second": tmp_path / "other.H5", + assert sorted(found) == ["elsewhere", "microcosm_uk_2024_25_dense", "second"] + assert {key: found[key].read_bytes() for key in found} == { + "microcosm_uk_2024_25_dense": b"dense", + "second": b"other", + "elsewhere": b"far", } - (tmp_path / "other.H5").write_bytes(b"changed") + assert [download[:3] for download in hub.downloads] == [ + (REPO, f"{folder}/release_manifest.json", DENSE_COMMIT), + ("policyengine/another", "x/far.h5", "r9"), + (REPO, f"{folder}/dense.h5", DENSE_COMMIT), + (REPO, f"{folder}/other.H5", DENSE_COMMIT), + ] + hub.files[(REPO, f"{folder}/other.H5", DENSE_COMMIT)] = b"changed" with pytest.raises(handoff.CertifyError, match="not the manifest's"): - handoff.fetch_regional_microdata( - DENSE, handoff.DENSE_RELEASE, timings=tmp_path / "t.jsonl" - ) + handoff.fetch_regional_microdata(dense, timings=tmp_path / "t.jsonl", api=hub) + + +@pytest.mark.parametrize( + ("artifact", "message"), + [ + ({"path": "sub/dense.h5", "repo_id": REPO}, "not a file directly inside"), + ( + { + "path": f"releases/microcosm-uk-2024-25-dense/{DENSE}/../x/dense.h5", + "repo_id": REPO, + }, + "not a file directly inside", + ), # fmt: skip + ({"path": "far.h5", "repo_id": "policyengine/another"}, "names no revision"), + ({"path": "dense.h5", "repo_id": REPO, "sha256": None}, "no sha256"), + ], +) +def test_a_regional_file_outside_its_pin_is_refused(tmp_path, artifact, message): + entry = {"kind": "microdata", "sha256": "0" * 64, **artifact} + hub = _dense_hub(tmp_path, {"microcosm_uk_2024_25_dense": entry}, {}) + dense = _build(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT) + with pytest.raises(handoff.CertifyError, match=message): + handoff.fetch_regional_microdata(dense, timings=tmp_path / "t.jsonl", api=hub) + assert len(hub.downloads) == 1 def test_the_audit_argv_passes_every_file_and_limitation(tmp_path): @@ -408,7 +845,8 @@ def test_build_relative_evidence_is_read(tmp_path): def test_the_pr_body_lists_the_audited_area_input_surface(): body = handoff.pr_body( { - "national_tag": NATIONAL, + "national_build": NATIONAL, + "national_commit": NATIONAL_COMMIT, "model": "2.147.2", "core": "3.33.3", "regional_summary": "`--keep-regional-release`", @@ -435,7 +873,7 @@ def test_the_resource_limits_are_the_operators_to_set(monkeypatch, tmp_path): monkeypatch.setattr(handoff.os, "getloadavg", lambda: (12.0, 0.0, 0.0)) args = handoff.parse( - ["--national-tag", NATIONAL, "--drop-regional-release", "--pepy-repo", "p"] + ["--national-build", NATIONAL, "--drop-regional-release", "--pepy-repo", "p"] ) assert args.max_load1 is None assert handoff.resource_guard(tmp_path, min_free_bytes=0)["load1"] == 12.0 @@ -599,7 +1037,7 @@ def test_any_json_receipt_summarizes_or_fails_operationally(receipt): def test_the_certification_commit_credits_only_named_co_authors(): - assert handoff.commit_message(NATIONAL) == f"Certify Microcosm UK cut {NATIONAL}" + assert handoff.commit_message(NATIONAL) == f"Certify Microcosm UK build {NATIONAL}" message = handoff.commit_message( NATIONAL, co_authors=["A Person ", "B "] ) @@ -616,7 +1054,7 @@ def test_a_co_author_must_be_one_name_and_email(author): with pytest.raises(SystemExit): handoff.parse( [ - "--national-tag", + "--national-build", NATIONAL, "--drop-regional-release", "--pepy-repo", @@ -629,7 +1067,8 @@ def test_a_co_author_must_be_one_name_and_email(author): def test_the_pr_body_footer_is_the_operators_choice(): context = { - "national_tag": NATIONAL, + "national_build": NATIONAL, + "national_commit": NATIONAL_COMMIT, "model": "2.162.3", "core": "3.33.3", "regional_summary": "`--drop-regional-release`", diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py index 5b2ae8c55d..f0a1db5457 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py @@ -14,8 +14,10 @@ from tools import certify_uk_cut_in_policyengine_py as runner -TAG = "microcosm-uk-2024-25-national-20261023T075039Z-a133f37a" -DENSE_TAG = "microcosm-uk-2024-25-dense-20261019T000432Z-ee5c2dbe" +BUILD = "uk-frs-calibration-attempt-20261023T075039Z-a133f37a" +DENSE_BUILD = "uk-local-candidate-f100-s42-20261019T000432Z-ee5c2dbe" +NATIONAL_COMMIT = "a133f37a" * 5 +DENSE_COMMIT = "ee5c2dbe" * 5 EVIDENCE = { "schema_version": 2, "model_version": "2.147.2", @@ -28,37 +30,25 @@ } +def published(release, build, model): + """A build in its own folder, pinned at its publishing commit.""" + commit = NATIONAL_COMMIT if release == runner.NATIONAL_RELEASE else DENSE_COMMIT + return runner.PublishedBuild(release, build, commit, model, "3.0", ()) + + class RunnerTests(unittest.TestCase): def test_hugging_face_token_is_explicit_and_not_logged(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = Path(tmp) / "manifest.json" - manifest.write_text( - json.dumps( - { - "build": { - "cut_tag": TAG, - "built_with_model_package": {"version": "2.147.2"}, - "built_with_core_package": {"version": "3.0"}, - } - } - ) - ) - download = Mock(return_value=str(manifest)) - with ( - patch.dict( - sys.modules, - { - "huggingface_hub": types.SimpleNamespace( - hf_hub_download=download - ) - }, - ), - patch.dict(os.environ, {"HUGGING_FACE_TOKEN": "private-value"}), - ): - self.assertEqual( - runner.read_cut(TAG, runner.NATIONAL_RELEASE).model, "2.147.2" - ) - self.assertEqual(download.call_args.kwargs["token"], "private-value") + client = Mock() + with ( + patch.dict( + sys.modules, {"huggingface_hub": types.SimpleNamespace(HfApi=client)} + ), + patch.dict(os.environ, {"HUGGING_FACE_TOKEN": "private-value"}), + patch("builtins.print") as printed, + ): + self.assertIs(runner.hub_api(), client.return_value) + client.assert_called_once_with(token="private-value") + printed.assert_not_called() def test_shell_records_failed_commands(self): with tempfile.TemporaryDirectory() as tmp: @@ -222,8 +212,8 @@ def test_temp_preflight_refuses_before_network_or_model_work(self): with tempfile.TemporaryDirectory() as tmp: args = runner.parse( [ - "--national-tag", - TAG, + "--national-build", + BUILD, "--drop-regional-release", "--pepy-repo", tmp, @@ -238,7 +228,7 @@ def test_temp_preflight_refuses_before_network_or_model_work(self): "check_test_temp_directory", side_effect=runner.CertifyError("temporary directory inside Git"), ), - patch.object(runner, "read_cut") as manifest, + patch.object(runner, "read_published_build") as manifest, patch.object(runner, "fetch_regional_microdata") as microdata, patch.object(runner.subprocess, "run") as spawn, ): @@ -253,8 +243,8 @@ def test_workers_are_limited(self): with self.assertRaises(SystemExit): runner.parse( [ - "--national-tag", - TAG, + "--national-build", + BUILD, "--drop-regional-release", "--pepy-repo", "pepy", @@ -265,8 +255,8 @@ def test_workers_are_limited(self): self.assertEqual( runner.parse( [ - "--national-tag", - TAG, + "--national-build", + BUILD, "--drop-regional-release", "--pepy-repo", "pepy", @@ -279,8 +269,8 @@ def test_workers_are_limited(self): def test_pr_base_accepts_explicit_stack_target(self): common = [ - "--national-tag", - TAG, + "--national-build", + BUILD, "--drop-regional-release", "--pepy-repo", "pepy", @@ -295,8 +285,8 @@ def test_local_base_is_resolved_once_and_used_for_old_bundle(self): with tempfile.TemporaryDirectory() as tmp: args = runner.parse( [ - "--national-tag", - TAG, + "--national-build", + BUILD, "--drop-regional-release", "--dry-run", "--base-ref", @@ -317,8 +307,8 @@ def test_local_base_is_resolved_once_and_used_for_old_bundle(self): patch.object(runner.subprocess, "run") as spawn, patch.object( runner, - "read_cut", - return_value=runner.CutVersions(TAG, "2.147.2", "3.0", ()), + "read_published_build", + return_value=published(runner.NATIONAL_RELEASE, BUILD, "2.147.2"), ), ): self.assertEqual(runner.certify(args), 0) @@ -338,7 +328,7 @@ def test_local_base_is_resolved_once_and_used_for_old_bundle(self): def test_certification_changes_preserve_auxiliary_untracked_files(self): manifest = "src/policyengine/data/bundle/manifest.json" - changelog = f"changelog.d/certify-uk-{TAG}.changed.md" + changelog = f"changelog.d/certify-uk-{BUILD}.changed.md" with patch.object( runner.subprocess, "check_output", @@ -349,7 +339,7 @@ def test_certification_changes_preserve_auxiliary_untracked_files(self): "tests/fixtures/household_calculator_snapshots/operator-helper.json\0", ], ): - paths = runner.certification_changes(Path.cwd(), TAG) + paths = runner.certification_changes(Path.cwd(), BUILD) self.assertEqual(paths, sorted(["pyproject.toml", manifest, changelog])) def test_certification_changes_refuse_unrelated_tracked_edits(self): @@ -359,7 +349,7 @@ def test_certification_changes_refuse_unrelated_tracked_edits(self): return_value="src/policyengine/core/simulation.py\0", ): with self.assertRaisesRegex(runner.CertifyError, "unrelated tracked"): - runner.certification_changes(Path.cwd(), TAG) + runner.certification_changes(Path.cwd(), BUILD) def test_resume_validates_identity_and_preserves_unfinished_generated_files(self): for problem in ( @@ -370,7 +360,8 @@ def test_resume_validates_identity_and_preserves_unfinished_generated_files(self "head", "merge", "tracked", - "cut", + "build", + "tag", ): with self.subTest(problem=problem), tempfile.TemporaryDirectory() as tmp: root = Path(tmp) @@ -381,19 +372,26 @@ def test_resume_validates_identity_and_preserves_unfinished_generated_files(self relative = "src/policyengine/data/bundle/manifest.json" path = worktree / relative path.parent.mkdir(parents=True) + folder = f"releases/{runner.NATIONAL_RELEASE}/{BUILD}" + data_package = { + "release_manifest_path": f"{folder}/release_manifest.json", + "release_manifest_revision": NATIONAL_COMMIT, + } + if problem == "build": + data_package["release_manifest_path"] = data_package[ + "release_manifest_path" + ].replace(BUILD, DENSE_BUILD) + if problem == "tag": + # A modified manifest from a tagged handoff of the same build. + data_package = { + "release_manifest_path": ( + f"releases/{runner.NATIONAL_RELEASE}/release_manifest.json" + ), + "release_manifest_revision": BUILD, + } path.write_text( json.dumps( - { - "data_releases": { - "uk": { - "data_package": { - "release_manifest_revision": "another-cut" - if problem == "cut" - else TAG - } - } - } - } + {"data_releases": {"uk": {"data_package": data_package}}} ) ) original = path.read_bytes() @@ -444,12 +442,12 @@ def output( if problem: with self.assertRaises(runner.CertifyError): runner.validate_resume_worktree( - repo, worktree, branch, base, TAG + repo, worktree, branch, base, BUILD ) else: self.assertEqual( runner.validate_resume_worktree( - repo, worktree, branch, base, TAG + repo, worktree, branch, base, BUILD ), [relative], ) @@ -465,6 +463,7 @@ def run_mock_pipeline( call_details=None, resume=False, evidence=None, + old_record=None, ): if receipt is None and uc_code == 0: receipt = { @@ -479,7 +478,11 @@ def run_mock_pipeline( self.addCleanup(tmp.cleanup) root = Path(tmp.name) worktree = root / "certification" - bundle = {"data_releases": {"uk": {"default_dataset": "candidate"}}} + bundle = { + "data_releases": { + "uk": {"default_dataset": "candidate", **(old_record or {})} + } + } if resume: path = worktree / "src/policyengine/data/bundle/manifest.json" path.parent.mkdir(parents=True) @@ -487,8 +490,8 @@ def run_mock_pipeline( route = ["--drop-regional-release"] if evidence is not None: route = [ - "--dense-tag", - DENSE_TAG, + "--dense-build", + DENSE_BUILD, "--accept-regional-model-mismatch", "recorded rehearsal mismatch", "--audited-by", @@ -498,8 +501,8 @@ def run_mock_pipeline( ] args = runner.parse( [ - "--national-tag", - TAG, + "--national-build", + BUILD, *route, "--base-ref", "local", @@ -513,9 +516,9 @@ def run_mock_pipeline( ] ) calls = [] - cuts = { - TAG: runner.CutVersions(TAG, "2.147.2", "3.0", ()), - DENSE_TAG: runner.CutVersions(DENSE_TAG, "2.132.6", "3.0", ()), + builds = { + BUILD: published(runner.NATIONAL_RELEASE, BUILD, "2.147.2"), + DENSE_BUILD: published(runner.DENSE_RELEASE, DENSE_BUILD, "2.132.6"), } def command(argv, **kwargs): @@ -561,7 +564,11 @@ def shell(argv, **kwargs): side_effect=["microcosm", "immutable-sha", json.dumps(bundle)], ), patch.object(runner.subprocess, "run", side_effect=command), - patch.object(runner, "read_cut", side_effect=lambda tag, _: cuts[tag]), + patch.object( + runner, + "read_published_build", + side_effect=lambda release, build, **kwargs: builds[build], + ), patch.object(runner, "regional_audit_support", return_value=None), patch.object( runner, @@ -622,6 +629,65 @@ def test_an_accepted_mismatch_audits_then_certifies_with_its_evidence(self): self.assertIn("local_bus_uncapped_single_fare", body) self.assertIn("audited by A Reviewer", body) + def test_certify_data_gets_each_builds_folder_manifest_at_its_commit(self): + details = [] + result, calls, root = self.run_mock_pipeline( + evidence=EVIDENCE, call_details=details + ) + self.assertEqual(result, 0) + by_step = {kwargs.get("step"): argv for argv, kwargs in details} + certify = by_step["certify-data"] + self.assertEqual( + certify[certify.index("--manifest-uri") + 1], + "hf://dataset/policyengine/populace-uk-private@" + f"{NATIONAL_COMMIT}/releases/microcosm-uk-2024-25-national/{BUILD}/" + "release_manifest.json", + ) + self.assertEqual( + certify[certify.index("--regional-manifest-uri") + 1], + runner.manifest_uri(runner.DENSE_RELEASE, DENSE_BUILD, DENSE_COMMIT), + ) + worktree = next(c for c in calls if c[:3] == ["git", "worktree", "add"]) + self.assertEqual(worktree[worktree.index("-b") + 1], "certify-uk-a133f37a") + commit = next(argv for argv, _ in details if argv[:2] == ["git", "commit"]) + self.assertEqual( + commit[commit.index("-m") + 1], f"Certify Microcosm UK build {BUILD}" + ) + body = (root / "certification.pr-body.md").read_text() + self.assertIn(f"Microcosm UK national build `{BUILD}`", body) + self.assertIn(f"`{NATIONAL_COMMIT}`", body) + + def test_old_builds_sharing_a_commit_leave_their_constants_to_a_person(self): + """policyengine.py's rewrite moves every quoted copy of the old national + commit, the old local-area build's included, so the body asks for a + check by hand.""" + + shared = "5" * 40 + old_record = { + "data_package": {"release_manifest_revision": shared}, + "regional_source_manifest_uri": runner.manifest_uri( + runner.DENSE_RELEASE, "uk-local-candidate-old", shared + ), + } + with patch.object(runner, "rewrite_regional_constants", return_value=[]): + result, _, root = self.run_mock_pipeline( + evidence=EVIDENCE, old_record=old_record + ) + self.assertEqual(result, 0) + body = (root / "certification.pr-body.md").read_text() + self.assertIn(f"shared commit `{shared}`", body) + with patch.object(runner, "rewrite_regional_constants", return_value=[]): + _, _, root = self.run_mock_pipeline( + evidence=EVIDENCE, + old_record={ + **old_record, + "data_package": {"release_manifest_revision": "6" * 40}, + }, + ) + self.assertNotIn( + "shared commit", (root / "certification.pr-body.md").read_text() + ) + def test_package_steps_get_no_hugging_face_token(self): details = [] self.run_mock_pipeline(evidence=EVIDENCE, call_details=details) From 3ba64272a3c54df1863f2873e2d43eb48b32c512 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:26:32 +0400 Subject: [PATCH 02/10] Certify a UK build from its own folder in the policyengine.py tool tools/certify_uk_cut_in_policyengine_py.py read a UK national build only at a Hugging Face tag and checked build.cut_tag. UK builds have been published into releases/// folders with no tag since #1537, and policyengine.py refuses a tagged manifest from a repository with releases.json, so the tool could certify nothing (#1762). The tool now takes --national-build and --dense-build, refuses a build that releases.json at main (read afresh) does not list or has withdrawn, pins each build at the commit that published its folder (the last commit of its manifest on main) unless --national-data-commit or --dense-data-commit names another, checks that the manifest there names the build, and hands certify-data each build's folder manifest at that commit. The kept regional release is read at the folder and commit the bundle pins, so its model check and accepted-mismatch audit run again; a kept tagged release in the build repository is refused. Regional microdata is read from the build's folder at its commit. The regional constant rewrite moves the local-area build's commit as well as its name, and leaves the commit to a person, named in the pull request body, when the previous local-area build shared a commit with a national build. The changelog fragment, branch, writer check, resume check, commit message and pull request body name the build. run_uk_cut.py's closing message and docs/release-contract.md name the new flag and the build-folder certification. The test file's other-repository case no longer names the retired UK data repository, which the live-tree check forbids, and one test name now says what it checks. Co-Authored-By: Claude Opus 5.5 --- ...-certification-tool-build-folders.fixed.md | 1 + docs/release-contract.md | 5 +- docs/uk-cut-anyone.md | 53 +- .../test_certify_uk_cut_in_policyengine_py.py | 6 +- tools/certify_uk_cut_in_policyengine_py.py | 575 +++++++++++++----- tools/run_uk_cut.py | 5 +- 6 files changed, 473 insertions(+), 172 deletions(-) create mode 100644 changelog.d/1762-uk-certification-tool-build-folders.fixed.md diff --git a/changelog.d/1762-uk-certification-tool-build-folders.fixed.md b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md new file mode 100644 index 0000000000..31de807a96 --- /dev/null +++ b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md @@ -0,0 +1 @@ +`tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build published into its own folder. It takes the national build by name (`--national-build`) and a local-area build the same way (`--dense-build`), refuses a build that `releases.json` at `main` does not list or has withdrawn, pins each build at the commit that published its folder (or one named with `--national-data-commit` or `--dense-data-commit`), and hands policyengine.py's `certify-data` each build's folder manifest at that commit. `--keep-regional-release` reads the kept local-area build at the folder and commit the bundle pins, the regional microdata is read from the build's folder, and the certified-constant rewrite moves the local-area build's commit as well as its name. Tags (`--national-tag`, `--dense-tag`) are no longer accepted, since policyengine.py refuses a tagged manifest from a repository with `releases.json`. diff --git a/docs/release-contract.md b/docs/release-contract.md index 21fc8aa486..0cc471d725 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -1095,7 +1095,10 @@ work. 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. + folder. Its UK national and local-area builds have been pinned that way + since policyengine.py#766 (2026-11-23), and + `tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build only + from its folder (#1762). - *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 diff --git a/docs/uk-cut-anyone.md b/docs/uk-cut-anyone.md index ce82d62e4e..9cbdc4fa2a 100644 --- a/docs/uk-cut-anyone.md +++ b/docs/uk-cut-anyone.md @@ -388,12 +388,29 @@ anyone verify; that is tracked in microcosm#1406. ```bash uv run --no-sync python tools/certify_uk_cut_in_policyengine_py.py \ - --national-tag microcosm-uk-2024-25-national-- \ - (--dense-tag | --keep-regional-release | --area-coded-national-uri | --drop-regional-release) \ + --national-build uk-frs-calibration-attempt-- \ + (--dense-build | --keep-regional-release | --area-coded-national-uri | --drop-regional-release) \ --pepy-repo \ + [--national-data-commit ] [--dense-data-commit ] \ [--max-load1 ] [--min-free-gb ] [--push --open-pr] ``` +Builds are named as `releases.json` names them, the national build in +`microcosm-uk-2024-25-national` and the local-area build in +`microcosm-uk-2024-25-dense`. `policyengine/populace-uk-private` publishes +each build into its own folder, `releases///`, with no tag, +and policyengine.py refuses a tagged manifest from a repository with +`releases.json` (policyengine.py#683), so the script takes no tag. A build +need not be current: a certificate pins one build. + +Each build is certified from its folder at the commit that published it, +which the script asks the Hub for: the last commit of the build's +`release_manifest.json` on `main`, since a build folder never changes. To pin +another commit that holds the folder, such as the `commit` that +`microcosm-publish-release-build` printed, pass `--national-data-commit` or +`--dense-data-commit` (a full 40-character commit). `--keep-regional-release` +reads the local-area build at the folder and commit the current bundle pins. + Each heavy step first checks the host. The disk floor defaults to 55 GB (`--min-free-gb`). There is no load limit unless you set one with `--max-load1`, because a sensible limit depends on the machine. @@ -415,26 +432,35 @@ git identity that commits. An agent session adds its own credit: commit trailer, and `--pr-body-footer "🤖 Generated with [Claude Code](https://claude.com/claude-code)"` for the body. -The script does the mechanical part of what policyengine.py#685 did by hand, -on a new branch from policyengine.py's main. +The script does the mechanical part of what policyengine.py#685 and #766 did +by hand, on a new branch from policyengine.py's main. **Before writing anything:** -- It refuses if another writer is already certifying the cut: an open pull - request that names the tag, or any open pull request or branch whose name +- It refuses if another writer is already certifying the build: an open pull + request that names the build, or any open pull request or branch whose name contains `certify-uk-`, including suffixed ones such as `certify-uk-a133f37a-national`. If it cannot read either listing, it refuses rather than passing. -- It reads both manifests at their tags. -- It refuses a regional cut built on another policyengine-uk, naming the - routes. +- It refuses a build that `releases.json` at `main`, downloaded afresh, does + not list or has withdrawn, as `certify-data` would. +- It reads each build's manifest from its folder at its commit, and refuses + one that names another release or build. +- It refuses a regional build made with another policyengine-uk, naming the + routes, and a kept regional release in `populace-uk-private` that is not a + build in its own folder. **Then:** -1. `certify-data` at the cut's own model and core. +1. `certify-data` at the national build's own model and core, with each + build's folder manifest at its commit + (`hf://dataset/policyengine/populace-uk-private@/releases///release_manifest.json`). 2. `uv lock` and `release_lock.py`. 3. `generate --include-tros`. -4. policyengine.py's own certified-constant rewrite, plus the local-area tag. +4. policyengine.py's own certified-constant rewrite, plus the local-area + build's name and commit. If the previous local-area build shared a commit + with a national build, its commit constants are left for a person, and the + pull request body says so. 5. The household snapshots. 6. `check --published-spm --include-tros --strict-tros`. 7. The UC floor. @@ -492,8 +518,9 @@ rehearsal probe agrees. through any of these inputs would be wrong. - `tools/certify_uk_cut_in_policyengine_py.py` measures this whenever a mismatch is accepted, with policyengine.py's own audit: - - it downloads every regional microdata H5 at its manifest pin and checks - its sha256; + - it downloads every regional microdata H5 from the build's folder at the + build's commit (a file in another repository at its own revision), and + checks its sha256; - in the certification worktree it installs the target policyengine-uk and core, and runs `scripts/audit_regional_input_surface.py`, which reads only column names and measures them against the regional cut's build diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py index ef51d8e9a6..39deae94ed 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py @@ -160,7 +160,7 @@ def test_only_a_folder_manifest_in_the_build_repository_names_a_build(): ) for other in ( tagged, - uri.replace("populace-uk-private", "policyengine-uk-data-private"), + uri.replace("populace-uk-private", "another-repository"), uri.replace("release_manifest.json", "build_manifest.json"), "hf://model/x@1/r", "", @@ -440,7 +440,9 @@ def test_a_named_build_and_its_commit_reach_certify_data(monkeypatch, tmp_path, assert plan["branch"] == "certify-uk-a858c100" -def test_a_kept_tagged_regional_release_refuses_before_any_read(monkeypatch, tmp_path): +def test_a_kept_tagged_regional_release_is_refused_before_it_is_read( + monkeypatch, tmp_path +): """policyengine.py refuses a tagged manifest from a repository with releases.json, so keeping one could never certify.""" diff --git a/tools/certify_uk_cut_in_policyengine_py.py b/tools/certify_uk_cut_in_policyengine_py.py index 56167253e1..f48fd8e765 100644 --- a/tools/certify_uk_cut_in_policyengine_py.py +++ b/tools/certify_uk_cut_in_policyengine_py.py @@ -1,16 +1,18 @@ -"""Certify a published Microcosm UK cut into policyengine.py, on a fresh branch. +"""Certify a published Microcosm UK build into policyengine.py, on a fresh branch. -policyengine.py serves the UK cut its bundle manifest certifies; moving that -pin is a policyengine.py pull request and release. This script does the -mechanical part of that pull request the way policyengine.py#685 did it by -hand (``docs/engineering/skills/data-certification.md`` there), in a new +policyengine.py serves the UK build its bundle manifest certifies; moving +that pin is a policyengine.py pull request and release. This script does the +mechanical part of that pull request the way policyengine.py#685 and #766 did +it by hand (``docs/engineering/skills/data-certification.md`` there), in a new worktree branched from policyengine.py's ``origin/main``: -1. refuse if someone is already certifying this cut (one writer per cut); -2. read the national (and regional) release manifests at their tags and - check, before anything is written, that the regional route can certify; -3. ``scripts/bundle.py certify-data`` with the national tag and the chosen - regional route, at the cut's own policyengine-uk and core; +1. refuse if someone is already certifying this build (one writer per build); +2. read the national (and local-area) build from its own folder, + ``releases///``, and check, before anything is written, + that the regional route can certify; +3. ``scripts/bundle.py certify-data`` with the national build's folder + manifest and the chosen regional route, at the build's own policyengine-uk + and core; 4. ``uv lock`` and ``scripts/release_lock.py``; 5. ``bundle.py generate --include-tros``, the certified-constant rewrite of policyengine.py's own qualification library, the household snapshots, @@ -23,9 +25,18 @@ It pushes and opens a draft pull request only with ``--push`` and ``--open-pr``. It never merges and never releases. +A build is named by its name in ``releases.json`` (``--national-build``, +``--dense-build``), which must list it at ``main`` and not have withdrawn it, +as policyengine.py's certification requires (policyengine.py#683). The +repository publishes no tags, and policyengine.py refuses a tagged manifest +from a repository with ``releases.json``. Each build is pinned at the commit +that published its folder: the last commit of its ``release_manifest.json`` on +``main``, since a build folder never changes. ``--national-data-commit`` and +``--dense-data-commit`` pin another commit that holds the folder instead. + Regional routes (pick one): -``--dense-tag TAG`` a Microcosm local-area cut (ship together) +``--dense-build BUILD`` a Microcosm local-area build (ship together) ``--keep-regional-release`` the bundle's current regional release ``--area-coded-national-uri`` an enhanced-FRS release that claims the version ``--drop-regional-release`` no area routing (sim-api's UK default then @@ -35,10 +46,11 @@ certification unless policyengine.py accepts a recorded mismatch: ``--accept-regional-model-mismatch REASON`` with ``--audited-by WHO`` and at least one ``--regional-limitation TEXT``. The regional microdata is downloaded -at its manifest pin, policyengine.py's own ``scripts/audit_regional_input_surface.py`` -(policyengine.py#699) audits its stored columns against the build and target -models, and ``certify-data`` takes that evidence; any dropped column refuses -(see ``docs/uk-cut-anyone.md``). +from its build's folder at the build's commit, policyengine.py's own +``scripts/audit_regional_input_surface.py`` (policyengine.py#699) audits its +stored columns against the build and target models, and ``certify-data`` +takes that evidence; any dropped column refuses (see +``docs/uk-cut-anyone.md``). Needs ``HF_TOKEN`` (read ``policyengine/populace-uk-private``), PyPI, and ``gh`` for the writer check and the pull request. @@ -58,22 +70,32 @@ import sys import tempfile import time -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from contextlib import contextmanager from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path -from typing import Any +from typing import Any, NamedTuple +from microcosm.data.build_folder_manifests import require_offered_build from microcosm.data.gate_signing_keys import UK_GATE_SIGNING_KEY_ENV +from microcosm.data.releases_record import build_folder PEPY_REPO = "PolicyEngine/policyengine.py" -CUT_REPO = "policyengine/populace-uk-private" +BUILD_REPO = "policyengine/populace-uk-private" NATIONAL_RELEASE = "microcosm-uk-2024-25-national" DENSE_RELEASE = "microcosm-uk-2024-25-dense" PEPY_PYTHON = "3.13" # certify-uk-release.yaml's interpreter -TAG_PATTERN = re.compile( - r"^microcosm-uk-2024-25-(national|dense)-\d{8}T\d{6}Z-[0-9a-f]{8}$" +RELEASE_MANIFEST = "release_manifest.json" +#: A release or build name the emitter accepts for a folder, the rule +#: ``microcosm.data.releases_record`` and policyengine.py repeat. +BUILD_NAME_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") +#: A full Hub commit ID. A branch moves, and a short ID can be ambiguous. +COMMIT_PATTERN = re.compile(r"^[0-9a-f]{40}$") +#: A build's folder manifest in the build repository, as certify-data takes it. +FOLDER_MANIFEST_URI = re.compile( + rf"^hf://dataset/{re.escape(BUILD_REPO)}@(?P[^/@]+)" + rf"/releases/(?P[^/]+)/(?P[^/]+)/{re.escape(RELEASE_MANIFEST)}$" ) CONSTANT_PATTERN = r'(?P
["@/-]){old}(?P["/])'
 CONSTANT_FILES = (
@@ -87,49 +109,146 @@ class CertifyError(RuntimeError):
     """A refusal the operator must act on."""
 
 
-def manifest_uri(tag: str, release: str) -> str:
-    return f"hf://dataset/{CUT_REPO}@{tag}/releases/{release}/release_manifest.json"
+def manifest_uri(release: str, build: str, commit: str) -> str:
+    """The build's folder manifest at ``commit``, as policyengine.py certifies it."""
 
+    folder = build_folder(release, build)
+    return f"hf://dataset/{BUILD_REPO}@{commit}/{folder}/{RELEASE_MANIFEST}"
+
+
+class BuildPin(NamedTuple):
+    """A build in its own folder, and the commit it is read at."""
+
+    release: str
+    build: str
+    commit: str
 
-def check_tag(tag: str, kind: str) -> str:
-    match = TAG_PATTERN.match(tag)
-    if not match or match.group(1) != kind:
-        raise CertifyError(
-            f"{tag!r} is not a {kind} cut tag; certify cut tags only, never @main."
-        )
-    return tag
+
+def folder_reference(uri: str | None) -> BuildPin | None:
+    """The build a folder manifest URI in the build repository names, or
+    ``None`` for any other URI (a tagged manifest, another repository)."""
+
+    match = FOLDER_MANIFEST_URI.match(uri or "")
+    if match is None:
+        return None
+    return BuildPin(match["release"], match["build"], match["commit"])
 
 
 @dataclass(frozen=True)
-class CutVersions:
-    tag: str
+class PublishedBuild:
+    """A build read from its own folder, and what it was built with."""
+
+    release: str
+    build: str
+    commit: str
     model: str
     core: str
     claims: tuple[str, ...]
 
+    @property
+    def folder(self) -> str:
+        return build_folder(self.release, self.build)
+
+    @property
+    def pin(self) -> BuildPin:
+        return BuildPin(self.release, self.build, self.commit)
+
+    @property
+    def manifest_uri(self) -> str:
+        return manifest_uri(self.release, self.build, self.commit)
+
+
+def hub_token() -> str | None:
+    return os.environ.get("HUGGING_FACE_TOKEN") or os.environ.get("HF_TOKEN")
+
+
+def hub_api() -> Any:
+    """A Hub client that reads with this process's token."""
 
-def read_cut(tag: str, release: str) -> CutVersions:
     # Set before importing the hub: its HTTP timeout constants are import-time.
     os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "120")
     os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "60")
-    from huggingface_hub import hf_hub_download
-
-    path = hf_hub_download(
-        CUT_REPO,
-        f"releases/{release}/release_manifest.json",
-        repo_type="dataset",
-        revision=tag,
-        token=os.environ.get("HUGGING_FACE_TOKEN") or os.environ.get("HF_TOKEN"),
-        etag_timeout=60,
+    from huggingface_hub import HfApi
+
+    return HfApi(token=hub_token())
+
+
+def publishing_commit(api: Any, release: str, build: str) -> str:
+    """The commit that published the build's folder.
+
+    A build folder never changes after it is published, so the last commit
+    of its manifest on ``main`` is the one that published it.
+    """
+
+    path = f"{build_folder(release, build)}/{RELEASE_MANIFEST}"
+    infos = api.get_paths_info(
+        BUILD_REPO, [path], expand=True, revision="main", repo_type="dataset"
     )
-    manifest = json.loads(Path(path).read_text())
-    build = manifest.get("build") or {}
-    if build.get("cut_tag") != tag:
-        raise CertifyError(f"{tag}: the manifest names cut {build.get('cut_tag')!r}.")
-    return CutVersions(
-        tag=tag,
-        model=build["built_with_model_package"]["version"],
-        core=build["built_with_core_package"]["version"],
+    for info in infos:
+        commit = getattr(getattr(info, "last_commit", None), "oid", None)
+        if getattr(info, "path", None) == path and COMMIT_PATTERN.match(
+            str(commit or "")
+        ):
+            return str(commit)
+    raise CertifyError(
+        f"{BUILD_REPO} has no {path} on main, so build {build!r} of {release!r} "
+        "has no folder to certify from."
+    )
+
+
+def read_published_build(
+    release: str, build: str, *, commit: str | None = None, api: Any = None
+) -> PublishedBuild:
+    """Build ``build`` of ``release``, read from its own folder.
+
+    ``releases.json`` at ``main``, downloaded afresh, must list the build and
+    not have withdrawn it. The build is pinned at ``commit``, or else at the
+    commit that published its folder, and its manifest there must name the
+    release and the build and record the packages it was built with.
+    """
+
+    api = hub_api() if api is None else api
+    try:
+        require_offered_build(
+            api,
+            repo_id=BUILD_REPO,
+            release=release,
+            build=build,
+            label="build",
+            fresh=True,
+        )
+    except ValueError as error:
+        raise CertifyError(str(error)) from error
+    commit = commit or publishing_commit(api, release, build)
+    path = f"{build_folder(release, build)}/{RELEASE_MANIFEST}"
+    try:
+        local = api.hf_hub_download(
+            repo_id=BUILD_REPO,
+            filename=path,
+            repo_type="dataset",
+            revision=commit,
+            etag_timeout=60,
+        )
+        manifest = json.loads(Path(local).read_text())
+    except Exception as error:
+        raise CertifyError(f"could not read {path} at {commit}: {error}") from error
+    named = (manifest.get("release"), manifest.get("build"))
+    if named != (release, build):
+        raise CertifyError(
+            f"{path} at {commit} names release {named[0]!r} and build {named[1]!r}."
+        )
+    versions = {}
+    for field in ("built_with_model_package", "built_with_core_package"):
+        version = (manifest.get(field) or {}).get("version")
+        if not isinstance(version, str) or not version:
+            raise CertifyError(f"{path} at {commit} records no {field} version.")
+        versions[field] = version
+    return PublishedBuild(
+        release=release,
+        build=build,
+        commit=commit,
+        model=versions["built_with_model_package"],
+        core=versions["built_with_core_package"],
         claims=tuple(
             claim["specifier"]
             for claim in manifest.get("compatible_model_packages", ())
@@ -138,18 +257,25 @@ def read_cut(tag: str, release: str) -> CutVersions:
     )
 
 
-def covers(cut: CutVersions, version: str) -> bool:
+def covers(build: PublishedBuild, version: str) -> bool:
     """policyengine.py's rule: built with the version, or an exact claim of it."""
 
-    return cut.model == version or f"=={version}" in cut.claims
+    return build.model == version or f"=={version}" in build.claims
 
 
-def regional_flags(args: argparse.Namespace, bundle_record: dict) -> list[str]:
-    if args.dense_tag:
-        return [
-            "--regional-manifest-uri",
-            manifest_uri(check_tag(args.dense_tag, "dense"), DENSE_RELEASE),
-        ]
+def regional_flags(
+    args: argparse.Namespace, bundle_record: dict, dense: PublishedBuild | None
+) -> list[str]:
+    """certify-data's regional flags for the route the operator chose.
+
+    ``dense`` is the local-area build ``--dense-build`` names, as
+    :func:`read_published_build` read it; the other routes ignore it.
+    """
+
+    if args.dense_build:
+        if dense is None:
+            raise CertifyError(f"local-area build {args.dense_build!r} was not read.")
+        return ["--regional-manifest-uri", dense.manifest_uri]
     if args.keep_regional_release:
         uri = bundle_record.get("regional_source_manifest_uri")
         if not uri:
@@ -165,14 +291,25 @@ def regional_flags(args: argparse.Namespace, bundle_record: dict) -> list[str]:
     return ["--drop-regional-release"]
 
 
-def regional_tag(flags: list[str]) -> str | None:
-    if "--regional-manifest-uri" not in flags:
-        return None
-    uri = flags[flags.index("--regional-manifest-uri") + 1]
-    match = re.search(r"@([^/]+)/", uri)
-    return (
-        match.group(1) if match and match.group(1).startswith(DENSE_RELEASE) else None
-    )
+def kept_regional_pin(bundle_record: dict) -> BuildPin | None:
+    """The local-area build ``--keep-regional-release`` keeps, or ``None``
+    when the bundle routes regions to another repository's release.
+
+    policyengine.py refuses a tagged manifest from the build repository, which
+    has ``releases.json``, so keeping one is refused here first.
+    """
+
+    uri = bundle_record.get("regional_source_manifest_uri")
+    if not uri:
+        raise CertifyError("the bundle routes no regional release to keep.")
+    pin = folder_reference(uri)
+    if pin is None and f"/{BUILD_REPO}@" in uri:
+        raise CertifyError(
+            f"the bundle's regional release {uri} is not a build in its own "
+            f"folder, and policyengine.py certifies only those from {BUILD_REPO}; "
+            "name a local-area build with --dense-build."
+        )
+    return pin
 
 
 #: Free disk each heavy step needs by default: the certified environment,
@@ -223,7 +360,7 @@ def check_test_temp_directory(directory: Path | None = None) -> Path:
     return directory
 
 
-def certification_path(relative: str, national_tag: str) -> bool:
+def certification_path(relative: str, national_build: str) -> bool:
     """Files generated by this handoff, excluding local data and operator files."""
     snapshots = {
         "uk_couple_two_kids",
@@ -241,7 +378,7 @@ def certification_path(relative: str, national_tag: str) -> bool:
         "pyproject.toml",
         "uv.lock",
         *CONSTANT_FILES,
-        f"changelog.d/certify-uk-{national_tag}.changed.md",
+        f"changelog.d/certify-uk-{national_build}.changed.md",
         "src/policyengine/data/bundle/manifest.json",
         "src/policyengine/data/bundle/uk.trace.tro.jsonld",
         "src/policyengine/data/bundle/us.trace.tro.jsonld",
@@ -252,13 +389,15 @@ def certification_path(relative: str, national_tag: str) -> bool:
     }
 
 
-def certification_changes(worktree: Path, national_tag: str) -> list[str]:
+def certification_changes(worktree: Path, national_build: str) -> list[str]:
     """Preserve operator files and refuse unrelated tracked/index changes."""
     tracked = subprocess.check_output(
         ["git", "diff", "--name-only", "-z", "HEAD"], cwd=worktree, text=True
     ).split("\0")
     unexpected = [
-        path for path in tracked if path and not certification_path(path, national_tag)
+        path
+        for path in tracked
+        if path and not certification_path(path, national_build)
     ]
     if unexpected:
         raise CertifyError(
@@ -270,7 +409,7 @@ def certification_changes(worktree: Path, national_tag: str) -> list[str]:
         cwd=worktree,
         text=True,
     ).split("\0")
-    changelog = f"changelog.d/certify-uk-{national_tag}.changed.md"
+    changelog = f"changelog.d/certify-uk-{national_build}.changed.md"
     return sorted(
         {path for path in tracked if path}
         | {path for path in untracked if path == changelog}
@@ -278,7 +417,7 @@ def certification_changes(worktree: Path, national_tag: str) -> list[str]:
 
 
 def validate_resume_worktree(
-    repo: Path, worktree: Path, branch: str, base_commit: str, national_tag: str
+    repo: Path, worktree: Path, branch: str, base_commit: str, national_build: str
 ) -> list[str]:
     """Adopt only an unfinished, registered handoff at the exact resolved base."""
     if not worktree.is_dir():
@@ -340,15 +479,20 @@ def validate_resume_worktree(
         raise CertifyError(
             "resume worktree has unresolved merges; no files were changed."
         )
-    paths = certification_changes(worktree, national_tag)
+    paths = certification_changes(worktree, national_build)
     manifest_path = "src/policyengine/data/bundle/manifest.json"
     if manifest_path in paths:
         record = json.loads((worktree / manifest_path).read_text())["data_releases"][
             "uk"
         ]
-        revision = (record.get("data_package") or {}).get("release_manifest_revision")
-        if revision != national_tag:
-            raise CertifyError("resume worktree's modified manifest names another cut.")
+        certified = (record.get("data_package") or {}).get("release_manifest_path")
+        expected = (
+            f"{build_folder(NATIONAL_RELEASE, national_build)}/{RELEASE_MANIFEST}"
+        )
+        if certified != expected:
+            raise CertifyError(
+                "resume worktree's modified manifest certifies another build."
+            )
     return paths
 
 
@@ -530,17 +674,17 @@ def __call__(
         return result
 
 
-def writer_check(national_tag: str, pepy_repo: Path) -> list[str]:
-    """Open pull requests or branches already certifying this cut.
+def writer_check(national_build: str, pepy_repo: Path) -> list[str]:
+    """Open pull requests or branches already certifying this build.
 
-    A writer is an open pull request that names the tag, or any open pull
+    A writer is an open pull request that names the build, or any open pull
     request or remote branch whose name contains ``certify-uk-``: this
     handoff's own branch, a suffixed one such as
     ``certify-uk-a133f37a-national``, or one under a namespace. A listing
     that cannot be read refuses rather than passing.
     """
 
-    marker = f"certify-uk-{national_tag.rsplit('-', 1)[-1]}"
+    marker = f"certify-uk-{national_build.rsplit('-', 1)[-1]}"
     found = []
     result = subprocess.run(
         [
@@ -559,7 +703,7 @@ def writer_check(national_tag: str, pepy_repo: Path) -> list[str]:
         )
     for pr in json.loads(result.stdout or "[]"):
         text = f"{pr.get('title') or ''}\n{pr.get('body') or ''}"
-        if national_tag in text or marker in (pr.get("headRefName") or ""):
+        if national_build in text or marker in (pr.get("headRefName") or ""):
             found.append(f"#{pr['number']} {pr['title']} ({pr['headRefName']})")
     remote = subprocess.run(
         ["git", "ls-remote", "--heads", "origin"],
@@ -582,18 +726,28 @@ def writer_check(national_tag: str, pepy_repo: Path) -> list[str]:
 
 
 def rewrite_regional_constants(
-    root: Path, old: str | None, new: str | None
+    root: Path, old: BuildPin | None, new: BuildPin | None
 ) -> list[str]:
-    """Replace the old local-area cut tag in the certified-constant files."""
+    """Replace the old local-area build's name and commit with the new one's
+    in the certified-constant files, where each is a quoted literal."""
 
-    if not old or not new or old == new:
+    if old is None or new is None:
         return []
-    pattern = re.compile(CONSTANT_PATTERN.format(old=re.escape(old)))
+    replacements = [
+        (before, after)
+        for before, after in ((old.build, new.build), (old.commit, new.commit))
+        if before != after
+    ]
     changed = []
-    for relative in CONSTANT_FILES:
+    for relative in CONSTANT_FILES if replacements else ():
         path = root / relative
-        text = path.read_text()
-        updated = pattern.sub(lambda m: m.group("pre") + new + m.group("post"), text)
+        text = updated = path.read_text()
+        for before, after in replacements:
+            pattern = re.compile(CONSTANT_PATTERN.format(old=re.escape(before)))
+            updated = pattern.sub(
+                lambda m, after=after: m.group("pre") + after + m.group("post"),
+                updated,
+            )
         if updated != text:
             path.write_text(updated)
             changed.append(relative)
@@ -634,27 +788,61 @@ def regional_audit_support(repo: Path, base_commit: str) -> str | None:
     return None
 
 
+def artifact_pin(
+    build: PublishedBuild, name: str, artifact: Mapping[str, Any]
+) -> tuple[str, str, str]:
+    """Where one of a build's artifacts is read, as policyengine.py pins it:
+    the repository, the path and the revision.
+
+    A file in the build repository is a bare file name, alone or after the
+    build's folder, read in the folder at the build's commit. A file in
+    another repository keeps its own path and must name its own revision.
+    """
+
+    repo = artifact.get("repo_id") or BUILD_REPO
+    path = str(artifact.get("path") or "")
+    if repo != BUILD_REPO:
+        revision = artifact.get("revision")
+        if not isinstance(revision, str) or not revision:
+            raise CertifyError(
+                f"{build.build}: {name} is in {repo} and names no revision."
+            )
+        return repo, path, revision
+    file_name = path.removeprefix(f"{build.folder}/")
+    if (
+        not file_name
+        or file_name in {".", ".."}
+        or "/" in file_name
+        or "\\" in file_name
+    ):
+        raise CertifyError(
+            f"{build.build}: {name} ({path}) is not a file directly inside "
+            f"{build.folder}/."
+        )
+    return repo, f"{build.folder}/{file_name}", build.commit
+
+
 def fetch_regional_microdata(
-    tag: str, release: str, *, timings: Path
+    build: PublishedBuild, *, timings: Path, api: Any = None
 ) -> dict[str, Path]:
-    """Every microdata H5 of a regional cut, by manifest name, checked by sha256.
+    """Every microdata H5 of a local-area build, by manifest name, checked by
+    sha256.
 
-    These are the files policyengine.py's audit reads; it re-checks each
-    digest against the manifest itself.
+    The manifest is read from the build's folder at its commit, and each file
+    where policyengine.py pins it (:func:`artifact_pin`). These are the files
+    policyengine.py's audit reads; it re-checks each digest against the
+    manifest itself.
     """
 
-    from huggingface_hub import hf_hub_download
-
-    token = os.environ.get("HUGGING_FACE_TOKEN") or os.environ.get("HF_TOKEN")
+    api = hub_api() if api is None else api
     with timed_step("regional-microdata", timings) as record:
         manifest = json.loads(
             Path(
-                hf_hub_download(
-                    CUT_REPO,
-                    f"releases/{release}/release_manifest.json",
+                api.hf_hub_download(
+                    repo_id=BUILD_REPO,
+                    filename=f"{build.folder}/{RELEASE_MANIFEST}",
                     repo_type="dataset",
-                    revision=tag,
-                    token=token,
+                    revision=build.commit,
                 )
             ).read_text()
         )
@@ -665,30 +853,31 @@ def fetch_regional_microdata(
             and str(artifact.get("path", "")).lower().endswith(".h5")
         }
         if not microdata:
-            raise CertifyError(f"{tag}: the manifest lists no microdata H5.")
-        paths: dict[str, Path] = {}
+            raise CertifyError(f"{build.build}: the manifest lists no microdata H5.")
+        pins = {}
         for name, artifact in sorted(microdata.items()):
-            if not artifact.get("sha256") or not artifact.get("revision"):
-                raise CertifyError(
-                    f"{tag}: {name} is not pinned by revision and sha256."
-                )
+            if not artifact.get("sha256"):
+                raise CertifyError(f"{build.build}: {name} has no sha256.")
+            pins[name] = artifact_pin(build, name, artifact)
+        paths: dict[str, Path] = {}
+        for name, (repo, file_path, revision) in pins.items():
             path = Path(
-                hf_hub_download(
-                    artifact.get("repo_id") or CUT_REPO,
-                    artifact["path"],
+                api.hf_hub_download(
+                    repo_id=repo,
+                    filename=file_path,
                     repo_type="dataset",
-                    revision=artifact["revision"],
-                    token=token,
+                    revision=revision,
                 )
             )
             digest = hashlib.sha256()
             with path.open("rb") as handle:
                 for chunk in iter(lambda: handle.read(1 << 22), b""):
                     digest.update(chunk)
-            if digest.hexdigest() != artifact["sha256"]:
+            expected = microdata[name]["sha256"]
+            if digest.hexdigest() != expected:
                 raise CertifyError(
-                    f"{artifact['path']} at {artifact['revision']} hashes to "
-                    f"{digest.hexdigest()}, not the manifest's {artifact['sha256']}."
+                    f"{file_path} at {revision} hashes to {digest.hexdigest()}, "
+                    f"not the manifest's {expected}."
                 )
             paths[name] = path
         record.update(artifacts=sorted(paths))
@@ -812,8 +1001,9 @@ def uc_floor_summary(receipt: object) -> tuple[bool, str]:
 
 def pr_body(context: dict[str, Any]) -> str:
     lines = [
-        f"Certifies Microcosm UK national cut `{context['national_tag']}` "
-        f"(policyengine-uk {context['model']}, core {context['core']}).",
+        f"Certifies Microcosm UK national build `{context['national_build']}` "
+        f"(policyengine-uk {context['model']}, core {context['core']}), from its "
+        f"folder at commit `{context['national_commit']}`.",
         "",
         "**Mechanical handoff; wrapper qualification pending** unless reviewed "
         "receipts cover this exact candidate pair, commit and bundle. Microcosm's "
@@ -849,10 +1039,21 @@ def pr_body(context: dict[str, Any]) -> str:
     ]
     if context.get("uc_floor_passed") is False:
         lines.append(
-            "- [ ] **UC floor acceptance.** This cut has a measured floor failure "
+            "- [ ] **UC floor acceptance.** This build has a measured floor failure "
             "and needs explicit acceptance in its pull request "
             "(data-certification.md, recorded exceptions). Accepted by: ___"
         )
+    if context.get("shared_old_commit"):
+        regional = context.get("regional_commit")
+        lines.append(
+            "- [ ] **Local-area revision constants.** The previous local-area "
+            f"build shared commit `{context['shared_old_commit']}` with a national "
+            "build, so rewriting quoted literals cannot tell the two builds' "
+            "constants apart, and its commit was not rewritten. Check that each "
+            "national revision constant names "
+            f"`{context['national_commit']}` and each local-area one names "
+            + (f"`{regional}`." if regional else "the local-area build's commit.")
+        )
     if context.get("dropped_overlays"):
         lines.append(
             "- [ ] **Dataset overlays dropped by certification:** "
@@ -891,10 +1092,10 @@ def pr_body(context: dict[str, Any]) -> str:
 CO_AUTHOR_PATTERN = re.compile(r"^[^<>\n]+ <[^<>\s@]+@[^<>\s]+>$")
 
 
-def commit_message(national_tag: str, *, co_authors: Sequence[str] = ()) -> str:
+def commit_message(national_build: str, *, co_authors: Sequence[str] = ()) -> str:
     """The certification commit's message, crediting only the named co-authors."""
 
-    message = f"Certify Microcosm UK cut {national_tag}"
+    message = f"Certify Microcosm UK build {national_build}"
     if co_authors:
         trailers = "\n".join(f"Co-Authored-By: {author}" for author in co_authors)
         message += f"\n\n{trailers}"
@@ -911,9 +1112,24 @@ def readable(text: str | None) -> bool:
 
 def parse(argv: list[str] | None) -> argparse.Namespace:
     parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
-    parser.add_argument("--national-tag", required=True)
+    parser.add_argument(
+        "--national-build",
+        required=True,
+        metavar="BUILD",
+        help=f"the national build's name in releases.json ({NATIONAL_RELEASE})",
+    )
+    parser.add_argument(
+        "--national-data-commit",
+        metavar="COMMIT",
+        help="pin the national build at this commit instead of the one that "
+        "published its folder",
+    )
     route = parser.add_mutually_exclusive_group(required=True)
-    route.add_argument("--dense-tag")
+    route.add_argument(
+        "--dense-build",
+        metavar="BUILD",
+        help=f"route regions to this local-area build of {DENSE_RELEASE}",
+    )
     route.add_argument("--keep-regional-release", action="store_true")
     route.add_argument("--area-coded-national-uri")
     route.add_argument("--drop-regional-release", action="store_true")
@@ -921,7 +1137,7 @@ def parse(argv: list[str] | None) -> argparse.Namespace:
         "--accept-regional-model-mismatch",
         metavar="REASON",
         help=(
-            "route regions to a regional cut built on another policyengine-uk, "
+            "route regions to a regional build made with another policyengine-uk, "
             "recording who accepted it and why; certifies only with "
             "policyengine.py's audited input-surface evidence (#699)"
         ),
@@ -941,8 +1157,14 @@ def parse(argv: list[str] | None) -> argparse.Namespace:
         metavar="TEXT",
         help="with an accepted mismatch: a limitation to record (repeatable)",
     )
-    parser.add_argument("--model-version", help="default: the cut's build-time model")
-    parser.add_argument("--core-version", help="default: the cut's build-time core")
+    parser.add_argument(
+        "--dense-data-commit",
+        metavar="COMMIT",
+        help="with --dense-build: pin the local-area build at this commit instead "
+        "of the one that published its folder",
+    )
+    parser.add_argument("--model-version", help="default: the build's own model")
+    parser.add_argument("--core-version", help="default: the build's own core")
     parser.add_argument(
         "--pepy-repo",
         type=Path,
@@ -1019,7 +1241,20 @@ def parse(argv: list[str] | None) -> argparse.Namespace:
         )
     if not 1 <= args.test_workers <= 4:
         parser.error("--test-workers must be between 1 and 4.")
-    check_tag(args.national_tag, "national")
+    for flag, name in (
+        ("--national-build", args.national_build),
+        ("--dense-build", args.dense_build),
+    ):
+        if name is not None and not BUILD_NAME_PATTERN.match(name):
+            parser.error(f"{flag} {name!r} is not a build name.")
+    for flag, commit in (
+        ("--national-data-commit", args.national_data_commit),
+        ("--dense-data-commit", args.dense_data_commit),
+    ):
+        if commit is not None and not COMMIT_PATTERN.match(commit):
+            parser.error(f"{flag} must be a full 40-character commit, not {commit!r}.")
+    if args.dense_data_commit is not None and args.dense_build is None:
+        parser.error("--dense-data-commit goes with --dense-build.")
     return args
 
 
@@ -1041,7 +1276,7 @@ def certify(args: argparse.Namespace) -> int:
         "max_load1": args.max_load1,
         "min_free_bytes": int(args.min_free_gb * 1e9),
     }
-    suffix = args.national_tag.rsplit("-", 1)[-1]
+    suffix = args.national_build.rsplit("-", 1)[-1]
     branch = f"certify-uk-{suffix}"
     worktree = args.worktree or repo.parent / "_worktrees" / f"pepy-{branch}"
     log = worktree.parent / f"{worktree.name}.certify.log"
@@ -1076,7 +1311,7 @@ def certify(args: argparse.Namespace) -> int:
     if args.resume_worktree:
         with timed_step("resume-worktree-validation", timings):
             replay_paths = validate_resume_worktree(
-                repo, worktree, branch, base_commit, args.national_tag
+                repo, worktree, branch, base_commit, args.national_build
             )
     elif worktree.exists():
         raise CertifyError(
@@ -1088,22 +1323,25 @@ def certify(args: argparse.Namespace) -> int:
         print(f"writer check skipped: {args.skip_writer_check}")
     else:
         with timed_step("writer-check", timings):
-            others = writer_check(args.national_tag, repo)
+            others = writer_check(args.national_build, repo)
         if others:
             raise CertifyError(
-                "this cut is already being certified: "
+                "this build is already being certified: "
                 + "; ".join(others)
                 + ". Coordinate with its owner instead of opening a second PR."
             )
 
     with timed_step("national-manifest", timings):
-        national = read_cut(args.national_tag, NATIONAL_RELEASE)
+        national = read_published_build(
+            NATIONAL_RELEASE, args.national_build, commit=args.national_data_commit
+        )
     model = args.model_version or national.model
     core = args.core_version or national.core
     if not covers(national, model):
         raise CertifyError(
-            f"the national cut was built with policyengine-uk {national.model} and "
-            f"claims {list(national.claims)}; it cannot be certified for {model}."
+            f"the national build was built with policyengine-uk {national.model} "
+            f"and claims {list(national.claims)}; it cannot be certified for "
+            f"{model}."
         )
     with timed_step("old-bundle", timings):
         old_bundle = json.loads(
@@ -1118,23 +1356,32 @@ def certify(args: argparse.Namespace) -> int:
             )
         )
     record = old_bundle["data_releases"]["uk"]
-    flags = regional_flags(args, record)
-    new_regional = regional_tag(flags)
-    regional_summary = shlex.join(flags)
     dense, mismatch, regional_artifacts = None, False, {}
-    if new_regional is not None:
+    kept = kept_regional_pin(record) if args.keep_regional_release else None
+    if args.dense_build or kept is not None:
         with timed_step("regional-manifest", timings):
-            dense = read_cut(new_regional, DENSE_RELEASE)
+            if args.dense_build:
+                dense = read_published_build(
+                    DENSE_RELEASE, args.dense_build, commit=args.dense_data_commit
+                )
+            else:
+                dense = read_published_build(
+                    kept.release, kept.build, commit=kept.commit
+                )
+    flags = regional_flags(args, record, dense)
+    regional_summary = shlex.join(flags)
+    if dense is not None:
         if not covers(dense, model):
             if not args.accept_regional_model_mismatch:
                 raise CertifyError(
-                    f"the regional cut {new_regional} was built with policyengine-uk "
-                    f"{dense.model} and claims {list(dense.claims)}, so certification "
-                    f"for {model} will refuse it. Routes: a dense cut on {model} "
-                    "(--dense-tag), --drop-regional-release, an enhanced-FRS release "
-                    "that claims the version (--area-coded-national-uri), or an "
-                    "accepted, recorded mismatch (--accept-regional-model-mismatch) "
-                    "with policyengine.py's audited evidence."
+                    f"the regional build {dense.build} was built with "
+                    f"policyengine-uk {dense.model} and claims {list(dense.claims)}, "
+                    f"so certification for {model} will refuse it. Routes: a "
+                    f"local-area build on {model} (--dense-build), "
+                    "--drop-regional-release, an enhanced-FRS release that claims "
+                    "the version (--area-coded-national-uri), or an accepted, "
+                    "recorded mismatch (--accept-regional-model-mismatch) with "
+                    "policyengine.py's audited evidence."
                 )
             problem = regional_audit_support(repo, base_commit)
             if problem is not None:
@@ -1146,17 +1393,30 @@ def certify(args: argparse.Namespace) -> int:
             mismatch = True
             regional_summary += f" (regional built on {dense.model}; mismatch accepted)"
             if not args.dry_run:
-                regional_artifacts = fetch_regional_microdata(
-                    new_regional, DENSE_RELEASE, timings=timings
-                )
-    old_regional = regional_tag(
-        ["--regional-manifest-uri", record.get("regional_source_manifest_uri") or ""]
+                regional_artifacts = fetch_regional_microdata(dense, timings=timings)
+    old_regional = folder_reference(record.get("regional_source_manifest_uri"))
+    old_national_commit = (record.get("data_package") or {}).get(
+        "release_manifest_revision"
+    )
+    # The constants are rewritten as quoted literals: policyengine.py's rewrite
+    # moves the old national commit, then the regional rewrite moves the old
+    # local-area commit. When the old local-area commit is also the old or the
+    # new national commit, and the new builds' commits differ, neither rewrite
+    # can tell the two builds' constants apart.
+    shared_old_commit = (
+        old_regional.commit
+        if old_regional is not None
+        and dense is not None
+        and old_regional.commit in {old_national_commit, national.commit}
+        and dense.commit != national.commit
+        else None
     )
 
     plan = {
         "base_ref": base_ref,
         "base_commit": base_commit,
-        "national_tag": args.national_tag,
+        "national_build": national.build,
+        "national_manifest_uri": national.manifest_uri,
         "model": model,
         "core": core,
         "regional": regional_summary,
@@ -1233,7 +1493,7 @@ def certify(args: argparse.Namespace) -> int:
         [
             python, "scripts/bundle.py", "certify-data", "--country", "uk",
             "--data-producer", "populace",
-            "--manifest-uri", manifest_uri(args.national_tag, NATIONAL_RELEASE),
+            "--manifest-uri", national.manifest_uri,
             *flags,
             "--model-version", model, "--core-version", core,
         ], step="certify-data",
@@ -1269,6 +1529,10 @@ def certify(args: argparse.Namespace) -> int:
     )  # fmt: skip
     constants = json.loads(rewrite.stdout.strip().splitlines()[-1] or "[]")
     with timed_step("regional-constant-rewrite", timings):
+        new_regional = None if dense is None else dense.pin
+        if new_regional is not None and shared_old_commit is not None:
+            # Its commit constants are left for a person (see the body).
+            new_regional = new_regional._replace(commit=shared_old_commit)
         constants += rewrite_regional_constants(worktree, old_regional, new_regional)
     run(
         pytest_command(python, ["tests/test_household_calculator_snapshot.py", "-q"]),
@@ -1333,7 +1597,10 @@ def certify(args: argparse.Namespace) -> int:
         if tests_returncode and not tests_failed:
             tests_failed = [f"pytest exited {tests_returncode}: {tests_summary}"]
     context = {
-        "national_tag": args.national_tag,
+        "national_build": national.build,
+        "national_commit": national.commit,
+        "regional_commit": None if dense is None else dense.commit,
+        "shared_old_commit": shared_old_commit,
         "model": model,
         "core": core,
         "regional_summary": f"`{regional_summary}`",
@@ -1353,12 +1620,12 @@ def certify(args: argparse.Namespace) -> int:
     body = worktree.parent / f"{worktree.name}.pr-body.md"
     body.write_text(pr_body(context))
     with timed_step("generated-file-validation", timings):
-        staged_paths = certification_changes(worktree, args.national_tag)
+        staged_paths = certification_changes(worktree, national.build)
     if staged_paths:
         run(["git", "add", "--", *staged_paths], step="stage-certification")
     run(
         ["git", "commit", "-q", "-m",
-         commit_message(args.national_tag, co_authors=args.co_author)]
+         commit_message(national.build, co_authors=args.co_author)]
     )  # fmt: skip
     print(f"\ncommitted on {branch} in {worktree}; PR body draft: {body}")
     if args.push:
@@ -1367,7 +1634,7 @@ def certify(args: argparse.Namespace) -> int:
         run(
             ["gh", "pr", "create", "--draft", "--repo", PEPY_REPO, "--base", args.pr_base,
              "--head", branch, "--title",
-             f"Certify Microcosm UK cut {args.national_tag}", "--body-file", str(body)]
+             f"Certify Microcosm UK build {national.build}", "--body-file", str(body)]
         )  # fmt: skip
     return 0 if not tests_returncode else 1
 
diff --git a/tools/run_uk_cut.py b/tools/run_uk_cut.py
index 9f4720ddf4..6cdeaf6d4f 100644
--- a/tools/run_uk_cut.py
+++ b/tools/run_uk_cut.py
@@ -2220,8 +2220,9 @@ def main(argv: Sequence[str] | None = None) -> int:
         print(
             "Next (each a separate, deliberate call):\n"
             f"  promote: {promote_command(paths, tag)}\n"
-            "  certify in policyengine.py: tools/certify_uk_cut_in_policyengine_py.py "
-            f"--national-tag {tag} ..."
+            "  certify in policyengine.py once it is published: "
+            "tools/certify_uk_cut_in_policyengine_py.py --national-build  ..."
         )
         return 0
     except CutError as error:

From beeee7b7254b7f3c84e881430685175a3a0c47c9 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Thu, 26 Nov 2026 18:52:50 +0400
Subject: [PATCH 03/10] Test the round 1 review's findings for the UK
 certification tool

Review round 1 of #1764 found that a Hub failure while reading releases.json
or asking which commit published a folder ended in a traceback instead of a
refusal, that a commit override was accepted from any Hub ref instead of only
from main's history, and that a resumed worktree was no longer checked
against the commits being certified. These tests describe the refusals. The
shared-commit test now checks the pins handed to the regional constant
rewrite, including the case where the old local-area commit is the new
national commit.

Co-Authored-By: Claude Opus 5.5 
---
 .../test_certify_uk_cut_in_policyengine_py.py | 87 +++++++++++++++++--
 ...st_certify_uk_cut_rehearsal_regressions.py | 86 +++++++++++-------
 2 files changed, 138 insertions(+), 35 deletions(-)

diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
index 39deae94ed..042505588a 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
@@ -532,19 +532,25 @@ def run(argv, **kwargs):
 class FakeHub:
     """The Hub calls the tool makes, answered from ``files``.
 
-    ``files`` maps ``(repo_id, path, revision)`` to bytes, and
-    ``last_commits`` maps a path to its last commit on ``main``.
+    ``files`` maps ``(repo_id, path, revision)`` to bytes, ``last_commits``
+    maps a path to its last commit on ``main``, and ``history`` lists the
+    commits in ``main``'s history. ``failures`` maps a file name, or
+    ``"paths-info"``, to the exception the Hub raises for it.
     """
 
-    def __init__(self, root, files, last_commits=None):
+    def __init__(self, root, files, last_commits=None, history=()):
         self.root, self.files = root, files
         self.last_commits = last_commits or {}
+        self.history = list(history)
+        self.failures = {}
         self.downloads, self.listings = [], []
 
     def hf_hub_download(self, repo_id, filename, *, repo_type=None, revision=None,
                         **options):  # fmt: skip
         assert repo_type == "dataset"
         self.downloads.append((repo_id, filename, revision, options))
+        if filename in self.failures:
+            raise self.failures[filename]
         key = (repo_id, filename, revision)
         if key not in self.files:
             raise FileNotFoundError(f"{repo_id} has no {filename} at {revision}")
@@ -555,12 +561,18 @@ def hf_hub_download(self, repo_id, filename, *, repo_type=None, revision=None,
     def get_paths_info(self, repo_id, paths, *, expand=False, revision=None,
                        repo_type=None):  # fmt: skip
         self.listings.append((repo_id, list(paths), expand, revision, repo_type))
+        if "paths-info" in self.failures:
+            raise self.failures["paths-info"]
         return [
             SimpleNamespace(path=path, last_commit=SimpleNamespace(oid=commit))
             for path, commit in self.last_commits.items()
             if path in paths
         ]
 
+    def list_repo_commits(self, repo_id, *, repo_type=None, revision=None):
+        assert (repo_id, repo_type, revision) == (REPO, "dataset", "main")
+        return [SimpleNamespace(commit_id=commit) for commit in self.history]
+
 
 REPO = "policyengine/populace-uk-private"
 
@@ -609,7 +621,9 @@ def _folder_manifest(release, build, **changes):
     return json.dumps({**manifest, **changes}).encode()
 
 
-def _national_hub(tmp_path, *, withdrawn=(), manifest=None, at=NATIONAL_COMMIT):
+def _national_hub(
+    tmp_path, *, withdrawn=(), manifest=None, at=NATIONAL_COMMIT, history=None
+):
     folder = _folder(handoff.NATIONAL_RELEASE, NATIONAL)
     files = {
         (REPO, "releases.json", "main"): _releases_record(withdrawn),
@@ -617,7 +631,10 @@ def _national_hub(tmp_path, *, withdrawn=(), manifest=None, at=NATIONAL_COMMIT):
         or _folder_manifest(handoff.NATIONAL_RELEASE, NATIONAL),
     }
     return FakeHub(
-        tmp_path, files, {f"{folder}/release_manifest.json": NATIONAL_COMMIT}
+        tmp_path,
+        files,
+        {f"{folder}/release_manifest.json": NATIONAL_COMMIT},
+        history=[NATIONAL_COMMIT, at] if history is None else history,
     )
 
 
@@ -653,6 +670,64 @@ def test_an_operators_commit_replaces_the_publishing_commit(tmp_path):
     assert hub.listings == []
 
 
+def test_an_operators_commit_must_be_in_mains_history(tmp_path):
+    """A commit on another ref, such as a Hub pull request's, may hold an
+    edited copy of the folder that main never held."""
+
+    other = "5" * 40
+    hub = _national_hub(tmp_path, at=other, history=[NATIONAL_COMMIT])
+    with pytest.raises(handoff.CertifyError, match="is not in main's history"):
+        handoff.read_published_build(
+            handoff.NATIONAL_RELEASE, NATIONAL, commit=other, api=hub
+        )
+    assert [download[1] for download in hub.downloads] == ["releases.json"]
+
+
+@pytest.mark.parametrize(
+    ("failing", "message"),
+    [
+        ("releases.json", "could not read releases.json"),
+        ("paths-info", "could not ask the Hub which commit published"),
+    ],
+)
+def test_a_hub_failure_is_a_refusal(tmp_path, failing, message):
+    hub = _national_hub(tmp_path)
+    hub.failures[failing] = RuntimeError("503 Service Unavailable")
+    with pytest.raises(handoff.CertifyError, match=message) as refusal:
+        handoff.read_published_build(handoff.NATIONAL_RELEASE, NATIONAL, api=hub)
+    assert "503 Service Unavailable" in str(refusal.value)
+
+
+def _bundle_at(worktree, revision, regional_uri):
+    path = worktree / "src/policyengine/data/bundle/manifest.json"
+    path.parent.mkdir(parents=True, exist_ok=True)
+    record = {
+        "data_package": {"release_manifest_revision": revision},
+        "regional_source_manifest_uri": regional_uri,
+    }
+    path.write_text(json.dumps({"data_releases": {"uk": record}}))
+    return "src/policyengine/data/bundle/manifest.json"
+
+
+def test_a_resumed_worktree_must_certify_the_same_commits(tmp_path):
+    """A resume at another commit would keep the first attempt's constants
+    while certify-data writes the new commit into the bundle."""
+
+    national = _build(handoff.NATIONAL_RELEASE, NATIONAL, NATIONAL_COMMIT)
+    dense = _build(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT)
+    relative = _bundle_at(tmp_path, NATIONAL_COMMIT, dense.manifest_uri)
+    handoff.check_resumed_pins(tmp_path, [relative], national, dense)
+    handoff.check_resumed_pins(tmp_path, [relative], national, None)
+    # A worktree whose bundle is not yet modified holds nothing to compare.
+    moved = _replace(national, commit="5" * 40)
+    handoff.check_resumed_pins(tmp_path, [], moved, dense)
+    with pytest.raises(handoff.CertifyError, match="national build at"):
+        handoff.check_resumed_pins(tmp_path, [relative], moved, dense)
+    other = _replace(dense, commit="6" * 40)
+    with pytest.raises(handoff.CertifyError, match="local-area build"):
+        handoff.check_resumed_pins(tmp_path, [relative], national, other)
+
+
 @pytest.mark.parametrize(
     ("hub_changes", "build", "message"),
     [
@@ -692,7 +767,7 @@ def test_a_build_with_no_folder_on_main_is_refused(tmp_path):
     hub.last_commits = {}
     with pytest.raises(handoff.CertifyError, match="has no releases/"):
         handoff.read_published_build(handoff.NATIONAL_RELEASE, NATIONAL, api=hub)
-    hub = _national_hub(tmp_path, at="6" * 40)
+    hub = _national_hub(tmp_path, at="6" * 40, history=["7" * 40])
     with pytest.raises(handoff.CertifyError, match="could not read"):
         handoff.read_published_build(
             handoff.NATIONAL_RELEASE, NATIONAL, commit="7" * 40, api=hub
diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
index f0a1db5457..35724a01d2 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
@@ -464,6 +464,7 @@ def run_mock_pipeline(
         resume=False,
         evidence=None,
         old_record=None,
+        replayed=(),
     ):
         if receipt is None and uc_code == 0:
             receipt = {
@@ -581,7 +582,9 @@ def shell(argv, **kwargs):
                 "check_test_temp_directory",
                 return_value=root / "isolated-test-temp",
             ),
-            patch.object(runner, "validate_resume_worktree", return_value=[]),
+            patch.object(
+                runner, "validate_resume_worktree", return_value=list(replayed)
+            ),
             patch.object(
                 runner,
                 "certification_changes",
@@ -658,35 +661,60 @@ def test_certify_data_gets_each_builds_folder_manifest_at_its_commit(self):
         self.assertIn(f"`{NATIONAL_COMMIT}`", body)
 
     def test_old_builds_sharing_a_commit_leave_their_constants_to_a_person(self):
-        """policyengine.py's rewrite moves every quoted copy of the old national
-        commit, the old local-area build's included, so the body asks for a
-        check by hand."""
-
-        shared = "5" * 40
-        old_record = {
-            "data_package": {"release_manifest_revision": shared},
-            "regional_source_manifest_uri": runner.manifest_uri(
-                runner.DENSE_RELEASE, "uk-local-candidate-old", shared
-            ),
-        }
-        with patch.object(runner, "rewrite_regional_constants", return_value=[]):
-            result, _, root = self.run_mock_pipeline(
-                evidence=EVIDENCE, old_record=old_record
-            )
-        self.assertEqual(result, 0)
-        body = (root / "certification.pr-body.md").read_text()
-        self.assertIn(f"shared commit `{shared}`", body)
-        with patch.object(runner, "rewrite_regional_constants", return_value=[]):
-            _, _, root = self.run_mock_pipeline(
-                evidence=EVIDENCE,
-                old_record={
-                    **old_record,
-                    "data_package": {"release_manifest_revision": "6" * 40},
-                },
-            )
-        self.assertNotIn(
-            "shared commit", (root / "certification.pr-body.md").read_text()
+        """The constants are rewritten as quoted literals, so when the old
+        local-area commit is also the old or the new national commit, its
+        commit is left unrewritten and the body asks for a check by hand."""
+
+        old_build = "uk-local-candidate-old"
+        cases = (
+            # (old national commit, old local-area commit, shared?)
+            ("5" * 40, "5" * 40, True),
+            ("6" * 40, NATIONAL_COMMIT, True),
+            ("6" * 40, "5" * 40, False),
         )
+        for old_national, old_regional, shared in cases:
+            with self.subTest(old_national=old_national, old_regional=old_regional):
+                old_record = {
+                    "data_package": {"release_manifest_revision": old_national},
+                    "regional_source_manifest_uri": runner.manifest_uri(
+                        runner.DENSE_RELEASE, old_build, old_regional
+                    ),
+                }
+                with patch.object(
+                    runner, "rewrite_regional_constants", return_value=[]
+                ) as rewrite:
+                    result, _, root = self.run_mock_pipeline(
+                        evidence=EVIDENCE, old_record=old_record
+                    )
+                self.assertEqual(result, 0)
+                _, old_pin, new_pin = rewrite.call_args.args
+                self.assertEqual(
+                    old_pin,
+                    runner.BuildPin(runner.DENSE_RELEASE, old_build, old_regional),
+                )
+                self.assertEqual(
+                    new_pin,
+                    runner.BuildPin(
+                        runner.DENSE_RELEASE,
+                        DENSE_BUILD,
+                        old_regional if shared else DENSE_COMMIT,
+                    ),
+                )
+                body = (root / "certification.pr-body.md").read_text()
+                self.assertEqual(f"shared commit `{old_regional}`" in body, shared)
+
+    def test_a_resume_at_another_commit_refuses_before_any_command(self):
+        """The resumed bundle names the first attempt's national commit, so a
+        resume that resolves another one is refused before anything runs."""
+
+        details = []
+        with self.assertRaisesRegex(runner.CertifyError, "national build at"):
+            self.run_mock_pipeline(
+                resume=True,
+                replayed=["src/policyengine/data/bundle/manifest.json"],
+                call_details=details,
+            )
+        self.assertEqual(details, [])
 
     def test_package_steps_get_no_hugging_face_token(self):
         details = []

From 0b043382ce536db4229f171cdd1458e5b807bdaa Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Thu, 26 Nov 2026 18:55:03 +0400
Subject: [PATCH 04/10] Refuse Hub failures, off-main commits and resumes at
 other commits

Fixes from review round 1 of #1764, all rated low:

- A Hub failure while reading releases.json or asking which commit
  published a folder is now a refusal naming the request, not a traceback.
- A --national-data-commit or --dense-data-commit override must be in
  main's history (list_repo_commits at main); a commit on another ref may
  hold an edited copy of the folder.
- A resumed worktree whose modified bundle pins another national commit,
  or routes regions to another local-area build, is refused before anything
  runs (check_resumed_pins).

Also: the pull request body's shared-commit item says the tool left the
local-area commit to a person, which is true in both shared cases; one
helper builds a build's folder manifest path; and docs/release-contract.md
names policyengine.py#759 (merged 2026-11-16), which first pinned the UK
builds by folder.

Co-Authored-By: Claude Opus 5.5 
---
 docs/release-contract.md                   |   2 +-
 tools/certify_uk_cut_in_policyengine_py.py | 114 ++++++++++++++++++---
 2 files changed, 98 insertions(+), 18 deletions(-)

diff --git a/docs/release-contract.md b/docs/release-contract.md
index 0cc471d725..a1496eff59 100644
--- a/docs/release-contract.md
+++ b/docs/release-contract.md
@@ -1096,7 +1096,7 @@ work.
   - *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. Its UK national and local-area builds have been pinned that way
-    since policyengine.py#766 (2026-11-23), and
+    since policyengine.py#759 (merged 2026-11-16), and
     `tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build only
     from its folder (#1762).
   - *The default.* The loader takes each country's default release from the
diff --git a/tools/certify_uk_cut_in_policyengine_py.py b/tools/certify_uk_cut_in_policyengine_py.py
index f48fd8e765..c9e87260f5 100644
--- a/tools/certify_uk_cut_in_policyengine_py.py
+++ b/tools/certify_uk_cut_in_policyengine_py.py
@@ -109,11 +109,17 @@ class CertifyError(RuntimeError):
     """A refusal the operator must act on."""
 
 
+def folder_manifest_path(release: str, build: str) -> str:
+    """The build's manifest in the build repository, inside its own folder."""
+
+    return f"{build_folder(release, build)}/{RELEASE_MANIFEST}"
+
+
 def manifest_uri(release: str, build: str, commit: str) -> str:
     """The build's folder manifest at ``commit``, as policyengine.py certifies it."""
 
-    folder = build_folder(release, build)
-    return f"hf://dataset/{BUILD_REPO}@{commit}/{folder}/{RELEASE_MANIFEST}"
+    path = folder_manifest_path(release, build)
+    return f"hf://dataset/{BUILD_REPO}@{commit}/{path}"
 
 
 class BuildPin(NamedTuple):
@@ -149,6 +155,10 @@ class PublishedBuild:
     def folder(self) -> str:
         return build_folder(self.release, self.build)
 
+    @property
+    def manifest_path(self) -> str:
+        return folder_manifest_path(self.release, self.build)
+
     @property
     def pin(self) -> BuildPin:
         return BuildPin(self.release, self.build, self.commit)
@@ -180,10 +190,15 @@ def publishing_commit(api: Any, release: str, build: str) -> str:
     of its manifest on ``main`` is the one that published it.
     """
 
-    path = f"{build_folder(release, build)}/{RELEASE_MANIFEST}"
-    infos = api.get_paths_info(
-        BUILD_REPO, [path], expand=True, revision="main", repo_type="dataset"
-    )
+    path = folder_manifest_path(release, build)
+    try:
+        infos = api.get_paths_info(
+            BUILD_REPO, [path], expand=True, revision="main", repo_type="dataset"
+        )
+    except Exception as error:
+        raise CertifyError(
+            f"could not ask the Hub which commit published {path}: {error}"
+        ) from error
     for info in infos:
         commit = getattr(getattr(info, "last_commit", None), "oid", None)
         if getattr(info, "path", None) == path and COMMIT_PATTERN.match(
@@ -196,15 +211,38 @@ def publishing_commit(api: Any, release: str, build: str) -> str:
     )
 
 
+def require_on_main(api: Any, commit: str) -> None:
+    """Refuse a commit outside ``main``'s history.
+
+    A build folder never changes on ``main``, but a commit on another ref,
+    such as a Hub pull request's, may hold an edited copy of it.
+    """
+
+    try:
+        history = api.list_repo_commits(
+            BUILD_REPO, repo_type="dataset", revision="main"
+        )
+    except Exception as error:
+        raise CertifyError(
+            f"could not list main's history in {BUILD_REPO}: {error}"
+        ) from error
+    if not any(entry.commit_id == commit for entry in history):
+        raise CertifyError(
+            f"commit {commit} is not in main's history in {BUILD_REPO}; pin a "
+            "commit on main that holds the build's folder."
+        )
+
+
 def read_published_build(
     release: str, build: str, *, commit: str | None = None, api: Any = None
 ) -> PublishedBuild:
     """Build ``build`` of ``release``, read from its own folder.
 
     ``releases.json`` at ``main``, downloaded afresh, must list the build and
-    not have withdrawn it. The build is pinned at ``commit``, or else at the
-    commit that published its folder, and its manifest there must name the
-    release and the build and record the packages it was built with.
+    not have withdrawn it. The build is pinned at ``commit``, which must be in
+    ``main``'s history, or else at the commit that published its folder, and
+    its manifest there must name the release and the build and record the
+    packages it was built with. A Hub failure is a refusal.
     """
 
     api = hub_api() if api is None else api
@@ -219,8 +257,16 @@ def read_published_build(
         )
     except ValueError as error:
         raise CertifyError(str(error)) from error
-    commit = commit or publishing_commit(api, release, build)
-    path = f"{build_folder(release, build)}/{RELEASE_MANIFEST}"
+    except Exception as error:
+        # Anything but an absent record: the Hub could not be asked.
+        raise CertifyError(
+            f"could not read releases.json at main in {BUILD_REPO}: {error}"
+        ) from error
+    if commit is None:
+        commit = publishing_commit(api, release, build)
+    else:
+        require_on_main(api, commit)
+    path = folder_manifest_path(release, build)
     try:
         local = api.hf_hub_download(
             repo_id=BUILD_REPO,
@@ -486,9 +532,7 @@ def validate_resume_worktree(
             "uk"
         ]
         certified = (record.get("data_package") or {}).get("release_manifest_path")
-        expected = (
-            f"{build_folder(NATIONAL_RELEASE, national_build)}/{RELEASE_MANIFEST}"
-        )
+        expected = folder_manifest_path(NATIONAL_RELEASE, national_build)
         if certified != expected:
             raise CertifyError(
                 "resume worktree's modified manifest certifies another build."
@@ -496,6 +540,40 @@ def validate_resume_worktree(
     return paths
 
 
+BUNDLE_MANIFEST = "src/policyengine/data/bundle/manifest.json"
+
+
+def check_resumed_pins(
+    worktree: Path,
+    replayed: Sequence[str],
+    national: PublishedBuild,
+    dense: PublishedBuild | None,
+) -> None:
+    """Refuse a resumed worktree whose modified bundle pins other commits.
+
+    The first attempt's constant rewrite moved the certified constants to its
+    commits, so a resume that certifies other ones would leave them behind.
+    """
+
+    if BUNDLE_MANIFEST not in replayed:
+        return
+    record = json.loads((worktree / BUNDLE_MANIFEST).read_text())["data_releases"]["uk"]
+    revision = (record.get("data_package") or {}).get("release_manifest_revision")
+    if revision != national.commit:
+        raise CertifyError(
+            "resume worktree's modified manifest pins the national build at "
+            f"{revision!r}, not {national.commit}; use a fresh worktree to "
+            "certify another commit."
+        )
+    regional = record.get("regional_source_manifest_uri")
+    if dense is not None and regional != dense.manifest_uri:
+        raise CertifyError(
+            f"resume worktree's modified manifest routes regions to {regional!r}, "
+            f"not the local-area build at {dense.manifest_uri}; use a fresh "
+            "worktree to certify another one."
+        )
+
+
 def record_timing(path: Path, record: dict[str, Any]) -> None:
     path.parent.mkdir(parents=True, exist_ok=True)
     with path.open("a") as handle:
@@ -840,7 +918,7 @@ def fetch_regional_microdata(
             Path(
                 api.hf_hub_download(
                     repo_id=BUILD_REPO,
-                    filename=f"{build.folder}/{RELEASE_MANIFEST}",
+                    filename=build.manifest_path,
                     repo_type="dataset",
                     revision=build.commit,
                 )
@@ -1049,8 +1127,8 @@ def pr_body(context: dict[str, Any]) -> str:
             "- [ ] **Local-area revision constants.** The previous local-area "
             f"build shared commit `{context['shared_old_commit']}` with a national "
             "build, so rewriting quoted literals cannot tell the two builds' "
-            "constants apart, and its commit was not rewritten. Check that each "
-            "national revision constant names "
+            "constants apart, and this tool left the local-area commit to a "
+            "person. Check that each national revision constant names "
             f"`{context['national_commit']}` and each local-area one names "
             + (f"`{regional}`." if regional else "the local-area build's commit.")
         )
@@ -1412,6 +1490,8 @@ def certify(args: argparse.Namespace) -> int:
         else None
     )
 
+    check_resumed_pins(worktree, replay_paths, national, dense)
+
     plan = {
         "base_ref": base_ref,
         "base_commit": base_commit,

From 7b7c0f89ee7e4ba034c588166443560849edb541 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Thu, 26 Nov 2026 20:50:04 +0400
Subject: [PATCH 05/10] Test the round 2 review's findings for the UK
 certification tool

Review round 2 of #1764 found that a Hub failure while downloading the
regional microdata still ended in a traceback, that a resume at another
commit downloaded every regional H5 before it was refused, and that a
malformed releases.json was refused without naming the file. These tests
describe the refusals, and add the missing case of a failing history
listing.

Co-Authored-By: Claude Opus 5.5 
---
 .../test_certify_uk_cut_in_policyengine_py.py | 39 +++++++++++++++++++
 ...st_certify_uk_cut_rehearsal_regressions.py | 24 +++++++++++-
 2 files changed, 62 insertions(+), 1 deletion(-)

diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
index 042505588a..efc1ca5e67 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
@@ -571,6 +571,8 @@ def get_paths_info(self, repo_id, paths, *, expand=False, revision=None,
 
     def list_repo_commits(self, repo_id, *, repo_type=None, revision=None):
         assert (repo_id, repo_type, revision) == (REPO, "dataset", "main")
+        if "commits" in self.failures:
+            raise self.failures["commits"]
         return [SimpleNamespace(commit_id=commit) for commit in self.history]
 
 
@@ -698,6 +700,27 @@ def test_a_hub_failure_is_a_refusal(tmp_path, failing, message):
     assert "503 Service Unavailable" in str(refusal.value)
 
 
+def test_a_failing_history_listing_is_a_refusal(tmp_path):
+    other = "5" * 40
+    hub = _national_hub(tmp_path, at=other)
+    hub.failures["commits"] = RuntimeError("503 Service Unavailable")
+    with pytest.raises(handoff.CertifyError, match="could not list main's history"):
+        handoff.read_published_build(
+            handoff.NATIONAL_RELEASE, NATIONAL, commit=other, api=hub
+        )
+
+
+def test_an_unreadable_releases_record_is_named_in_the_refusal(tmp_path):
+    hub = _national_hub(tmp_path)
+    hub.files[(REPO, "releases.json", "main")] = b"not json"
+    with pytest.raises(
+        handoff.CertifyError,
+        match="releases.json at main in policyengine/populace-uk-private: it is "
+        "not a readable JSON document",
+    ):
+        handoff.read_published_build(handoff.NATIONAL_RELEASE, NATIONAL, api=hub)
+
+
 def _bundle_at(worktree, revision, regional_uri):
     path = worktree / "src/policyengine/data/bundle/manifest.json"
     path.parent.mkdir(parents=True, exist_ok=True)
@@ -836,6 +859,22 @@ def test_every_regional_microdata_file_is_fetched_and_checked(tmp_path):
         handoff.fetch_regional_microdata(dense, timings=tmp_path / "t.jsonl", api=hub)
 
 
+def test_a_failing_regional_download_is_a_refusal(tmp_path):
+    folder = _folder(handoff.DENSE_RELEASE, DENSE)
+    entry = {"kind": "microdata", "path": "dense.h5", "repo_id": REPO,
+             "sha256": "0" * 64}  # fmt: skip
+    hub = _dense_hub(tmp_path, {"microcosm_uk_2024_25_dense": entry}, {})
+    hub.failures[f"{folder}/dense.h5"] = RuntimeError("503 Service Unavailable")
+    dense = _build(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT)
+    with pytest.raises(handoff.CertifyError, match="could not download") as refusal:
+        handoff.fetch_regional_microdata(dense, timings=tmp_path / "t.jsonl", api=hub)
+    assert f"{folder}/dense.h5 at {DENSE_COMMIT}" in str(refusal.value)
+    hub = _dense_hub(tmp_path, {}, {})
+    hub.failures[f"{folder}/release_manifest.json"] = RuntimeError("timed out")
+    with pytest.raises(handoff.CertifyError, match="could not download"):
+        handoff.fetch_regional_microdata(dense, timings=tmp_path / "t.jsonl", api=hub)
+
+
 @pytest.mark.parametrize(
     ("artifact", "message"),
     [
diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
index 35724a01d2..977e6bc11c 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
@@ -465,6 +465,7 @@ def run_mock_pipeline(
         evidence=None,
         old_record=None,
         replayed=(),
+        fetched=None,
     ):
         if receipt is None and uc_code == 0:
             receipt = {
@@ -574,7 +575,10 @@ def shell(argv, **kwargs):
             patch.object(
                 runner,
                 "fetch_regional_microdata",
-                return_value={"microcosm_uk_2024_25_dense": root / "dense.h5"},
+                side_effect=lambda build, **kwargs: (
+                    (fetched.append(build) if fetched is not None else None)
+                    or {"microcosm_uk_2024_25_dense": root / "dense.h5"}
+                ),
             ),
             patch.object(runner.Shell, "__call__", side_effect=shell),
             patch.object(
@@ -703,6 +707,24 @@ def test_old_builds_sharing_a_commit_leave_their_constants_to_a_person(self):
                 body = (root / "certification.pr-body.md").read_text()
                 self.assertEqual(f"shared commit `{old_regional}`" in body, shared)
 
+    def test_a_resume_at_another_commit_refuses_before_any_download(self):
+        """An accepted mismatch downloads every regional H5; a resume that
+        would be refused must not download them first."""
+
+        details, fetched = [], []
+        with self.assertRaisesRegex(
+            runner.CertifyError, f"national build at '{'5' * 40}'"
+        ):
+            self.run_mock_pipeline(
+                resume=True,
+                replayed=["src/policyengine/data/bundle/manifest.json"],
+                old_record={"data_package": {"release_manifest_revision": "5" * 40}},
+                evidence=EVIDENCE,
+                call_details=details,
+                fetched=fetched,
+            )
+        self.assertEqual((details, fetched), ([], []))
+
     def test_a_resume_at_another_commit_refuses_before_any_command(self):
         """The resumed bundle names the first attempt's national commit, so a
         resume that resolves another one is refused before anything runs."""

From af3a1b5746708004c0bd661a5c0f0a6158947666 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Thu, 26 Nov 2026 20:51:15 +0400
Subject: [PATCH 06/10] Refuse regional download failures and check a resume
 before downloading

Fixes from review round 2 of #1764:

- A Hub failure while downloading the regional manifest or an H5 is a
  refusal naming the file, its revision and its repository (low).
- check_resumed_pins runs as soon as the builds are read, before the
  accepted-mismatch route downloads every regional H5.
- A releases.json refusal that doesn't name the file, such as a parse
  error, is prefixed with releases.json and the repository.
- docs/uk-cut-anyone.md and the changelog fragment say that an override
  must be in main's history and that a resume at other commits is refused.

Co-Authored-By: Claude Opus 5.5 
---
 ...-certification-tool-build-folders.fixed.md |  2 +-
 docs/uk-cut-anyone.md                         |  8 +++-
 tools/certify_uk_cut_in_policyengine_py.py    | 43 +++++++++++--------
 3 files changed, 32 insertions(+), 21 deletions(-)

diff --git a/changelog.d/1762-uk-certification-tool-build-folders.fixed.md b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
index 31de807a96..ed440d0999 100644
--- a/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
+++ b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
@@ -1 +1 @@
-`tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build published into its own folder. It takes the national build by name (`--national-build`) and a local-area build the same way (`--dense-build`), refuses a build that `releases.json` at `main` does not list or has withdrawn, pins each build at the commit that published its folder (or one named with `--national-data-commit` or `--dense-data-commit`), and hands policyengine.py's `certify-data` each build's folder manifest at that commit. `--keep-regional-release` reads the kept local-area build at the folder and commit the bundle pins, the regional microdata is read from the build's folder, and the certified-constant rewrite moves the local-area build's commit as well as its name. Tags (`--national-tag`, `--dense-tag`) are no longer accepted, since policyengine.py refuses a tagged manifest from a repository with `releases.json`.
+`tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build published into its own folder. It takes the national build by name (`--national-build`) and a local-area build the same way (`--dense-build`), refuses a build that `releases.json` at `main` does not list or has withdrawn, pins each build at the commit that published its folder (or a commit in `main`'s history named with `--national-data-commit` or `--dense-data-commit`), and hands policyengine.py's `certify-data` each build's folder manifest at that commit. `--keep-regional-release` reads the kept local-area build at the folder and commit the bundle pins, the regional microdata is read from the build's folder, and the certified-constant rewrite moves the local-area build's commit as well as its name. A Hub failure is a refusal, and a resumed worktree that pins other commits is refused. Tags (`--national-tag`, `--dense-tag`) are no longer accepted, since policyengine.py refuses a tagged manifest from a repository with `releases.json`.
diff --git a/docs/uk-cut-anyone.md b/docs/uk-cut-anyone.md
index 9cbdc4fa2a..21350faf6c 100644
--- a/docs/uk-cut-anyone.md
+++ b/docs/uk-cut-anyone.md
@@ -408,8 +408,12 @@ which the script asks the Hub for: the last commit of the build's
 `release_manifest.json` on `main`, since a build folder never changes. To pin
 another commit that holds the folder, such as the `commit` that
 `microcosm-publish-release-build` printed, pass `--national-data-commit` or
-`--dense-data-commit` (a full 40-character commit). `--keep-regional-release`
-reads the local-area build at the folder and commit the current bundle pins.
+`--dense-data-commit`: a full 40-character commit in `main`'s history, since a
+commit on another ref may hold an edited copy of the folder.
+`--keep-regional-release` reads the local-area build at the folder and commit
+the current bundle pins. `--resume-worktree` refuses a worktree whose modified
+bundle pins other commits than this run's, because the first attempt's
+constant rewrite already moved the constants to its own.
 
 Each heavy step first checks the host. The disk floor defaults to 55 GB
 (`--min-free-gb`). There is no load limit unless you set one with
diff --git a/tools/certify_uk_cut_in_policyengine_py.py b/tools/certify_uk_cut_in_policyengine_py.py
index c9e87260f5..3c23106baf 100644
--- a/tools/certify_uk_cut_in_policyengine_py.py
+++ b/tools/certify_uk_cut_in_policyengine_py.py
@@ -256,7 +256,11 @@ def read_published_build(
             fresh=True,
         )
     except ValueError as error:
-        raise CertifyError(str(error)) from error
+        # A listing refusal names releases.json; a parse error does not.
+        message = str(error)
+        if "releases.json" not in message:
+            message = f"releases.json at main in {BUILD_REPO}: {message}"
+        raise CertifyError(message) from error
     except Exception as error:
         # Anything but an absent record: the Hub could not be asked.
         raise CertifyError(
@@ -913,16 +917,25 @@ def fetch_regional_microdata(
     """
 
     api = hub_api() if api is None else api
-    with timed_step("regional-microdata", timings) as record:
-        manifest = json.loads(
-            Path(
+
+    def download(repo: str, file_path: str, revision: str) -> Path:
+        try:
+            return Path(
                 api.hf_hub_download(
-                    repo_id=BUILD_REPO,
-                    filename=build.manifest_path,
+                    repo_id=repo,
+                    filename=file_path,
                     repo_type="dataset",
-                    revision=build.commit,
+                    revision=revision,
                 )
-            ).read_text()
+            )
+        except Exception as error:
+            raise CertifyError(
+                f"could not download {file_path} at {revision} from {repo}: {error}"
+            ) from error
+
+    with timed_step("regional-microdata", timings) as record:
+        manifest = json.loads(
+            download(BUILD_REPO, build.manifest_path, build.commit).read_text()
         )
         microdata = {
             name: artifact
@@ -939,14 +952,7 @@ def fetch_regional_microdata(
             pins[name] = artifact_pin(build, name, artifact)
         paths: dict[str, Path] = {}
         for name, (repo, file_path, revision) in pins.items():
-            path = Path(
-                api.hf_hub_download(
-                    repo_id=repo,
-                    filename=file_path,
-                    repo_type="dataset",
-                    revision=revision,
-                )
-            )
+            path = download(repo, file_path, revision)
             digest = hashlib.sha256()
             with path.open("rb") as handle:
                 for chunk in iter(lambda: handle.read(1 << 22), b""):
@@ -1446,6 +1452,9 @@ def certify(args: argparse.Namespace) -> int:
                 dense = read_published_build(
                     kept.release, kept.build, commit=kept.commit
                 )
+    # Before the regional microdata is downloaded: a refused resume must not
+    # download it first.
+    check_resumed_pins(worktree, replay_paths, national, dense)
     flags = regional_flags(args, record, dense)
     regional_summary = shlex.join(flags)
     if dense is not None:
@@ -1490,8 +1499,6 @@ def certify(args: argparse.Namespace) -> int:
         else None
     )
 
-    check_resumed_pins(worktree, replay_paths, national, dense)
-
     plan = {
         "base_ref": base_ref,
         "base_commit": base_commit,

From 2fc1ab9d07197a77e538d7f50553b0040f03aea0 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Thu, 26 Nov 2026 21:17:04 +0400
Subject: [PATCH 07/10] Test the round 3 review's findings for the UK
 certification tool

Review round 3 of #1764 found that a resume switching from a local-area
build to the drop or area-coded route was not refused, although the first
attempt's constant rewrite had moved the local-area constants, and that
the tool never checked that the policyengine.py base reads build folders
(policyengine.py#683), so an accepted mismatch on such a base downloaded
every regional file and set up a worktree before refusing. These tests
describe both refusals.

Co-Authored-By: Claude Opus 5.5 
---
 .../test_certify_uk_cut_in_policyengine_py.py | 67 ++++++++++++++++---
 ...st_certify_uk_cut_rehearsal_regressions.py | 25 ++++++-
 2 files changed, 83 insertions(+), 9 deletions(-)

diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
index efc1ca5e67..667aa22731 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
@@ -512,6 +512,47 @@ def test_a_mismatch_needs_readable_text_in_every_field(flag, text):
     assert handoff.readable("ok") and not handoff.readable(text)
 
 
+def test_the_build_folder_support_check_reads_the_base(monkeypatch, tmp_path):
+    answers, seen = {"grep": 0}, []
+
+    def run(argv, **kwargs):
+        assert kwargs["cwd"] == tmp_path
+        seen.append(argv)
+        return handoff.subprocess.CompletedProcess(argv, answers["grep"], b"", b"")
+
+    monkeypatch.setattr(handoff.subprocess, "run", run)
+    assert handoff.build_folder_support(tmp_path, "c" * 40) is None
+    assert seen == [
+        ["git", "grep", "-q", "-e", "def read_build_folder", "c" * 40, "--",
+         "src/policyengine/provenance/manifest.py"]
+    ]  # fmt: skip
+    answers["grep"] = 1
+    assert "read_build_folder" in handoff.build_folder_support(tmp_path, "c" * 40)
+
+
+def test_a_base_that_cannot_read_build_folders_refuses_before_any_read(
+    monkeypatch, tmp_path
+):
+    """A .py base without #683 certifies only tags, which the build repository
+    no longer has, and an accepted mismatch would download every regional
+    file and set up a worktree before refusing."""
+
+    reads, downloads = _dense_route(monkeypatch, tmp_path)
+
+    def run(argv, **kwargs):
+        code = 1 if "def read_build_folder" in argv else 0
+        return subprocess.CompletedProcess(argv, code, "", "")
+
+    monkeypatch.setattr(handoff.subprocess, "run", run)
+    args = handoff.parse(
+        ["--national-build", NATIONAL, "--dense-build", DENSE, "--dry-run",
+         "--pepy-repo", str(tmp_path), *MISMATCH]
+    )  # fmt: skip
+    with pytest.raises(handoff.CertifyError, match="policyengine.py#683"):
+        handoff.certify(args)
+    assert (reads, downloads) == ([], [])
+
+
 def test_the_audit_support_check_reads_the_base(monkeypatch, tmp_path):
     answers = {"cat-file": 0, "grep": 0}
 
@@ -733,22 +774,32 @@ def _bundle_at(worktree, revision, regional_uri):
 
 
 def test_a_resumed_worktree_must_certify_the_same_commits(tmp_path):
-    """A resume at another commit would keep the first attempt's constants
-    while certify-data writes the new commit into the bundle."""
+    """A resume at another commit, or with another regional route, would keep
+    the first attempt's constants while certify-data writes this run's pins
+    into the bundle."""
 
     national = _build(handoff.NATIONAL_RELEASE, NATIONAL, NATIONAL_COMMIT)
     dense = _build(handoff.DENSE_RELEASE, DENSE, DENSE_COMMIT)
     relative = _bundle_at(tmp_path, NATIONAL_COMMIT, dense.manifest_uri)
-    handoff.check_resumed_pins(tmp_path, [relative], national, dense)
-    handoff.check_resumed_pins(tmp_path, [relative], national, None)
+    handoff.check_resumed_pins(tmp_path, [relative], national, dense.manifest_uri)
     # A worktree whose bundle is not yet modified holds nothing to compare.
     moved = _replace(national, commit="5" * 40)
-    handoff.check_resumed_pins(tmp_path, [], moved, dense)
+    handoff.check_resumed_pins(tmp_path, [], moved, dense.manifest_uri)
     with pytest.raises(handoff.CertifyError, match="national build at"):
-        handoff.check_resumed_pins(tmp_path, [relative], moved, dense)
+        handoff.check_resumed_pins(tmp_path, [relative], moved, dense.manifest_uri)
     other = _replace(dense, commit="6" * 40)
-    with pytest.raises(handoff.CertifyError, match="local-area build"):
-        handoff.check_resumed_pins(tmp_path, [relative], national, other)
+    # Another local-area build, an area-coded release, or no routing at all.
+    for regional in (
+        other.manifest_uri,
+        "hf://dataset/policyengine/another@1/releases/r/release_manifest.json",
+        None,
+    ):
+        with pytest.raises(handoff.CertifyError, match="routes regions to"):
+            handoff.check_resumed_pins(tmp_path, [relative], national, regional)
+    relative = _bundle_at(tmp_path, NATIONAL_COMMIT, None)
+    handoff.check_resumed_pins(tmp_path, [relative], national, None)
+    with pytest.raises(handoff.CertifyError, match="routes regions to None"):
+        handoff.check_resumed_pins(tmp_path, [relative], national, dense.manifest_uri)
 
 
 @pytest.mark.parametrize(
diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
index 977e6bc11c..91648f32af 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
@@ -311,8 +311,14 @@ def test_local_base_is_resolved_once_and_used_for_old_bundle(self):
                     return_value=published(runner.NATIONAL_RELEASE, BUILD, "2.147.2"),
                 ),
             ):
+                spawn.return_value = subprocess.CompletedProcess([], 0, "", "")
                 self.assertEqual(runner.certify(args), 0)
-            spawn.assert_not_called()
+            # The one command a dry run spawns asks whether the resolved base
+            # reads build folders.
+            (argv,), _ = spawn.call_args
+            self.assertEqual(spawn.call_count, 1)
+            self.assertEqual(argv[:2], ["git", "grep"])
+            self.assertIn("immutable-sha", argv)
             self.assertEqual(
                 read.call_args_list[1].args[0],
                 ["git", "rev-parse", "--verify", "stack-local^{commit}"],
@@ -725,6 +731,23 @@ def test_a_resume_at_another_commit_refuses_before_any_download(self):
             )
         self.assertEqual((details, fetched), ([], []))
 
+    def test_a_resume_that_stops_routing_regions_refuses(self):
+        """The first attempt routed regions to a local-area build, and its
+        constant rewrite moved the local-area constants to that build; a
+        resume that drops the routing would keep them."""
+
+        with self.assertRaisesRegex(runner.CertifyError, "routes regions to"):
+            self.run_mock_pipeline(
+                resume=True,
+                replayed=["src/policyengine/data/bundle/manifest.json"],
+                old_record={
+                    "data_package": {"release_manifest_revision": NATIONAL_COMMIT},
+                    "regional_source_manifest_uri": runner.manifest_uri(
+                        runner.DENSE_RELEASE, DENSE_BUILD, DENSE_COMMIT
+                    ),
+                },
+            )
+
     def test_a_resume_at_another_commit_refuses_before_any_command(self):
         """The resumed bundle names the first attempt's national commit, so a
         resume that resolves another one is refused before anything runs."""

From 586d23a1ffdb79b702ae2b40e6d5fbcb74085f8d Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Thu, 26 Nov 2026 21:18:55 +0400
Subject: [PATCH 08/10] Refuse a base without build folders and a resume on
 another route

Fixes from review round 3 of #1764, both rated low:

- The tool refuses a policyengine.py base that cannot read builds in their
  own folders (no read_build_folder, policyengine.py#683) right after
  resolving it, before anything is downloaded or written.
- check_resumed_pins compares the resumed bundle's regional URI with the one
  this run passes to certify-data, or with none on the drop route, so a
  resume that switches from a local-area build to the drop or area-coded
  route is refused too.

Also: the operator guide drops the stale advice to test on a branch until
policyengine.py#699 merged (it merged on 2026-10-27) and states the base
requirement and the resume rule; the changelog fragment says the same; one
constant names .py's bundle manifest path; and a code comment is corrected.

Co-Authored-By: Claude Opus 5.5 
---
 ...-certification-tool-build-folders.fixed.md |  2 +-
 docs/uk-cut-anyone.md                         | 13 ++--
 tools/certify_uk_cut_in_policyengine_py.py    | 74 ++++++++++++++-----
 3 files changed, 64 insertions(+), 25 deletions(-)

diff --git a/changelog.d/1762-uk-certification-tool-build-folders.fixed.md b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
index ed440d0999..0e0b2d0457 100644
--- a/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
+++ b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
@@ -1 +1 @@
-`tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build published into its own folder. It takes the national build by name (`--national-build`) and a local-area build the same way (`--dense-build`), refuses a build that `releases.json` at `main` does not list or has withdrawn, pins each build at the commit that published its folder (or a commit in `main`'s history named with `--national-data-commit` or `--dense-data-commit`), and hands policyengine.py's `certify-data` each build's folder manifest at that commit. `--keep-regional-release` reads the kept local-area build at the folder and commit the bundle pins, the regional microdata is read from the build's folder, and the certified-constant rewrite moves the local-area build's commit as well as its name. A Hub failure is a refusal, and a resumed worktree that pins other commits is refused. Tags (`--national-tag`, `--dense-tag`) are no longer accepted, since policyengine.py refuses a tagged manifest from a repository with `releases.json`.
+`tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build published into its own folder. It takes the national build by name (`--national-build`) and a local-area build the same way (`--dense-build`), refuses a build that `releases.json` at `main` does not list or has withdrawn, pins each build at the commit that published its folder (or a commit in `main`'s history named with `--national-data-commit` or `--dense-data-commit`), and hands policyengine.py's `certify-data` each build's folder manifest at that commit. `--keep-regional-release` reads the kept local-area build at the folder and commit the bundle pins, the regional microdata is read from the build's folder, and the certified-constant rewrite moves the local-area build's commit as well as its name. A Hub failure is a refusal, a policyengine.py base that cannot read build folders (policyengine.py#683) is refused before anything is downloaded, and a resumed worktree that pins another national commit or regional route is refused. Tags (`--national-tag`, `--dense-tag`) are no longer accepted, since policyengine.py refuses a tagged manifest from a repository with `releases.json`.
diff --git a/docs/uk-cut-anyone.md b/docs/uk-cut-anyone.md
index 21350faf6c..89294aa5af 100644
--- a/docs/uk-cut-anyone.md
+++ b/docs/uk-cut-anyone.md
@@ -412,8 +412,13 @@ another commit that holds the folder, such as the `commit` that
 commit on another ref may hold an edited copy of the folder.
 `--keep-regional-release` reads the local-area build at the folder and commit
 the current bundle pins. `--resume-worktree` refuses a worktree whose modified
-bundle pins other commits than this run's, because the first attempt's
-constant rewrite already moved the constants to its own.
+bundle pins another national commit, or routes regions elsewhere than this
+run would (including none), because the first attempt's constant rewrite
+already moved the constants to its own builds.
+
+The policyengine.py base (`--base-ref`) must read builds in their own folders
+(`read_build_folder`, policyengine.py#683); a base without it refuses before
+anything is downloaded.
 
 Each heavy step first checks the host. The disk floor defaults to 55 GB
 (`--min-free-gb`). There is no load limit unless you set one with
@@ -424,9 +429,7 @@ For an accepted mismatch (see [Regions](#regions-the-dense-cut)), add
 `--audited-by ""` (it appears in policyengine.py's public
 bundle) and at least one `--regional-limitation ""`. The base needs
 policyengine.py#699's audit, and a base without it refuses before anything
-is downloaded. Until #699 merges, test the route with `--base-ref
-origin/accept-regional-model-mismatch --pr-base accept-regional-model-mismatch`.
-The audit and `certify-data` also need `uv` and PyPI: both read the build
+is downloaded. The audit and `certify-data` also need `uv` and PyPI: both read the build
 model through a pinned `uv` probe, and `certify-data` re-reads both models
 rather than trusting the evidence's lists.
 
diff --git a/tools/certify_uk_cut_in_policyengine_py.py b/tools/certify_uk_cut_in_policyengine_py.py
index 3c23106baf..df55a7ddb7 100644
--- a/tools/certify_uk_cut_in_policyengine_py.py
+++ b/tools/certify_uk_cut_in_policyengine_py.py
@@ -98,6 +98,8 @@
     rf"/releases/(?P[^/]+)/(?P[^/]+)/{re.escape(RELEASE_MANIFEST)}$"
 )
 CONSTANT_PATTERN = r'(?P
["@/-]){old}(?P["/])'
+#: policyengine.py's bundle manifest, which certify-data rewrites.
+BUNDLE_MANIFEST = "src/policyengine/data/bundle/manifest.json"
 CONSTANT_FILES = (
     "tests/test_models.py",
     "tests/test_release_manifests.py",
@@ -256,7 +258,7 @@ def read_published_build(
             fresh=True,
         )
     except ValueError as error:
-        # A listing refusal names releases.json; a parse error does not.
+        # Name releases.json where the refusal does not already.
         message = str(error)
         if "releases.json" not in message:
             message = f"releases.json at main in {BUILD_REPO}: {message}"
@@ -429,7 +431,7 @@ def certification_path(relative: str, national_build: str) -> bool:
         "uv.lock",
         *CONSTANT_FILES,
         f"changelog.d/certify-uk-{national_build}.changed.md",
-        "src/policyengine/data/bundle/manifest.json",
+        BUNDLE_MANIFEST,
         "src/policyengine/data/bundle/uk.trace.tro.jsonld",
         "src/policyengine/data/bundle/us.trace.tro.jsonld",
         *(
@@ -530,7 +532,7 @@ def validate_resume_worktree(
             "resume worktree has unresolved merges; no files were changed."
         )
     paths = certification_changes(worktree, national_build)
-    manifest_path = "src/policyengine/data/bundle/manifest.json"
+    manifest_path = BUNDLE_MANIFEST
     if manifest_path in paths:
         record = json.loads((worktree / manifest_path).read_text())["data_releases"][
             "uk"
@@ -544,19 +546,20 @@ def validate_resume_worktree(
     return paths
 
 
-BUNDLE_MANIFEST = "src/policyengine/data/bundle/manifest.json"
-
-
 def check_resumed_pins(
     worktree: Path,
     replayed: Sequence[str],
     national: PublishedBuild,
-    dense: PublishedBuild | None,
+    regional_uri: str | None,
 ) -> None:
-    """Refuse a resumed worktree whose modified bundle pins other commits.
+    """Refuse a resumed worktree whose modified bundle pins other builds.
 
+    ``regional_uri`` is the regional manifest URI this run passes to
+    certify-data, which writes it as the bundle's
+    ``regional_source_manifest_uri``, or ``None`` for no regional routing.
     The first attempt's constant rewrite moved the certified constants to its
-    commits, so a resume that certifies other ones would leave them behind.
+    own national commit and local-area build, so a resume that certifies
+    others would leave them behind.
     """
 
     if BUNDLE_MANIFEST not in replayed:
@@ -570,11 +573,11 @@ def check_resumed_pins(
             "certify another commit."
         )
     regional = record.get("regional_source_manifest_uri")
-    if dense is not None and regional != dense.manifest_uri:
+    if regional != regional_uri:
         raise CertifyError(
             f"resume worktree's modified manifest routes regions to {regional!r}, "
-            f"not the local-area build at {dense.manifest_uri}; use a fresh "
-            "worktree to certify another one."
+            f"not {regional_uri!r} as this run would; use a fresh worktree to "
+            "change the regional route."
         )
 
 
@@ -843,6 +846,26 @@ def rewrite_regional_constants(
 REGIONAL_EVIDENCE_SCHEMA = 2
 
 
+#: The policyengine.py module that reads a build in its own folder (policyengine.py#683).
+PEPY_MANIFEST_MODULE = "src/policyengine/provenance/manifest.py"
+
+
+def build_folder_support(repo: Path, base_commit: str) -> str | None:
+    """Why the base cannot certify a build in its own folder, or ``None`` if
+    it can: the base needs .py's ``read_build_folder``."""
+
+    found = subprocess.run(
+        ["git", "grep", "-q", "-e", "def read_build_folder", base_commit, "--",
+         PEPY_MANIFEST_MODULE],
+        cwd=repo,
+        capture_output=True,
+        check=False,
+    )  # fmt: skip
+    if found.returncode != 0:
+        return f"its {PEPY_MANIFEST_MODULE} has no read_build_folder"
+    return None
+
+
 def regional_audit_support(repo: Path, base_commit: str) -> str | None:
     """Why the base cannot certify an accepted mismatch, or ``None`` if it can.
 
@@ -1390,6 +1413,14 @@ def certify(args: argparse.Namespace) -> int:
             cwd=repo,
             text=True,
         ).strip()
+    with timed_step("base-build-folder-support", timings):
+        problem = build_folder_support(repo, base_commit)
+    if problem is not None:
+        raise CertifyError(
+            f"policyengine.py at {base_ref} ({base_commit[:9]}) cannot certify a "
+            f"build in its own folder: {problem} (policyengine.py#683). Use a "
+            "--base-ref that has it."
+        )
 
     replay_paths = []
     if args.resume_worktree:
@@ -1433,7 +1464,7 @@ def certify(args: argparse.Namespace) -> int:
                 [
                     "git",
                     "show",
-                    f"{base_commit}:src/policyengine/data/bundle/manifest.json",
+                    f"{base_commit}:{BUNDLE_MANIFEST}",
                 ],
                 cwd=repo,
                 text=True,
@@ -1452,11 +1483,18 @@ def certify(args: argparse.Namespace) -> int:
                 dense = read_published_build(
                     kept.release, kept.build, commit=kept.commit
                 )
-    # Before the regional microdata is downloaded: a refused resume must not
-    # download it first.
-    check_resumed_pins(worktree, replay_paths, national, dense)
     flags = regional_flags(args, record, dense)
     regional_summary = shlex.join(flags)
+    # Before the regional microdata is downloaded: a refused resume must not
+    # download it first.
+    check_resumed_pins(
+        worktree,
+        replay_paths,
+        national,
+        flags[flags.index("--regional-manifest-uri") + 1]
+        if "--regional-manifest-uri" in flags
+        else None,
+    )
     if dense is not None:
         if not covers(dense, model):
             if not args.accept_regional_model_mismatch:
@@ -1598,9 +1636,7 @@ def certify(args: argparse.Namespace) -> int:
     run(sync, step="certified-sync", credentials=False)
     run([python, "scripts/release_lock.py"], step="release-lock")
     run([python, "scripts/bundle.py", "generate", "--include-tros"], step="TROs")
-    new_bundle = json.loads(
-        (worktree / "src/policyengine/data/bundle/manifest.json").read_text()
-    )
+    new_bundle = json.loads((worktree / BUNDLE_MANIFEST).read_text())
     new_record = new_bundle["data_releases"]["uk"]
     rewrite = run(
         [

From 091e76263c5bda23e73ac4d287595efc49ebe03d Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 27 Nov 2026 16:34:46 +0400
Subject: [PATCH 09/10] Test the certificate's core binding and the pull
 request body's commands
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

María's review of #1764: the tool always passed --core-version to
certify-data, so its certificate named one policyengine-core
(core_binding: certified) and moved the bundle's shared core pin, where
policyengine.py's default certificate follows that pin (bundle_pin). These
tests describe the default, an operator's --core-version, a pull request
body whose commands carry no local paths or bundle records, and a list of
rewritten constant files without repeats.

Co-Authored-By: Claude Opus 5.5 
---
 .../test_certify_uk_cut_in_policyengine_py.py | 38 +++++++++++
 ...st_certify_uk_cut_rehearsal_regressions.py | 63 ++++++++++++++++++-
 2 files changed, 99 insertions(+), 2 deletions(-)

diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
index 667aa22731..0436515b0f 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_in_policyengine_py.py
@@ -7,6 +7,7 @@
 import hashlib
 import json
 import re
+import shlex
 import subprocess
 from types import SimpleNamespace
 
@@ -950,6 +951,43 @@ def test_a_regional_file_outside_its_pin_is_refused(tmp_path, artifact, message)
     assert len(hub.downloads) == 1
 
 
+def test_a_command_is_shown_without_local_paths_or_records(tmp_path):
+    worktree = tmp_path / "_worktrees" / "pepy-certify-uk-a858c100"
+    record = json.dumps({"data_releases": {"uk": {}}})
+    argv = [
+        str(worktree / ".venv/bin/python"), "-c", "print(1)", record,
+        "--output", f"{worktree.parent}/{worktree.name}.uc_floor.json",
+        "--artifact", f"dense={tmp_path}/.cache/huggingface/x.h5", "-q",
+    ]  # fmt: skip
+    assert handoff.public_command(argv, worktree, home=tmp_path) == shlex.join(
+        [
+            ".venv/bin/python", "-c", "print(1)",
+            f"",
+            "--output", "../pepy-certify-uk-a858c100.uc_floor.json",
+            "--artifact", "dense=~/.cache/huggingface/x.h5", "-q",
+        ]
+    )  # fmt: skip
+
+
+def test_the_pr_body_shows_each_command_without_local_paths_or_records(tmp_path):
+    """--open-pr posts the body as it is: no operator paths, and not the old
+    and new bundle records the constant rewrite is passed."""
+
+    worktree = tmp_path / "_worktrees" / "pepy-certify-uk-a858c100"
+    shell = handoff.Shell(worktree, worktree.parent / "run.log", dry_run=True)
+    record = json.dumps({"data_releases": {"uk": {"default_dataset": "x"}}})
+    shell([str(worktree / ".venv/bin/python"), "-c", "code", record, record])
+    shell(["uv", "lock"])
+    assert shell.public_commands(home=tmp_path) == [
+        shlex.join(
+            [".venv/bin/python", "-c", "code",
+             f"",
+             f""]
+        ),
+        "uv lock",
+    ]  # fmt: skip
+
+
 def test_the_audit_argv_passes_every_file_and_limitation(tmp_path):
     argv = handoff.regional_audit_argv(
         "py",
diff --git a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
index 91648f32af..38e147e28b 100644
--- a/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
+++ b/packages/microcosm-build/tests/engine_free/uk/test_certify_uk_cut_rehearsal_regressions.py
@@ -472,6 +472,9 @@ def run_mock_pipeline(
         old_record=None,
         replayed=(),
         fetched=None,
+        bundle_packages=None,
+        extra_args=(),
+        rewritten=(),
     ):
         if receipt is None and uc_code == 0:
             receipt = {
@@ -489,7 +492,8 @@ def run_mock_pipeline(
         bundle = {
             "data_releases": {
                 "uk": {"default_dataset": "candidate", **(old_record or {})}
-            }
+            },
+            **({"packages": bundle_packages} if bundle_packages else {}),
         }
         if resume:
             path = worktree / "src/policyengine/data/bundle/manifest.json"
@@ -521,6 +525,7 @@ def run_mock_pipeline(
                 "--skip-writer-check",
                 "offline regression",
                 *(["--resume-worktree"] if resume else []),
+                *extra_args,
             ]
         )
         calls = []
@@ -542,7 +547,9 @@ def shell(argv, **kwargs):
             if call_details is not None:
                 call_details.append((argv, kwargs))
             if "constant-rewrite" == kwargs.get("step"):
-                return subprocess.CompletedProcess(argv, 0, "[]", "")
+                return subprocess.CompletedProcess(
+                    argv, 0, json.dumps(list(rewritten)), ""
+                )
             if "audit-help" == kwargs.get("step"):
                 flags = (
                     "--regional-manifest-uri --artifact --model-version "
@@ -761,6 +768,58 @@ def test_a_resume_at_another_commit_refuses_before_any_command(self):
             )
         self.assertEqual(details, [])
 
+    def test_certify_data_follows_the_bundles_core_pin_by_default(self):
+        """.py's default certificate follows the bundle's shared core pin
+        (core_binding: bundle_pin). --core-version would bind the UK to one
+        core and move the pin, so a later core move for another country
+        would need a UK re-certification first."""
+
+        details = []
+        result, _, root = self.run_mock_pipeline(
+            evidence=EVIDENCE,
+            call_details=details,
+            bundle_packages={"policyengine-core": {"version": "3.1"}},
+        )
+        self.assertEqual(result, 0)
+        by_step = {kwargs.get("step"): argv for argv, kwargs in details}
+        self.assertNotIn("--core-version", by_step["certify-data"])
+        # The audit runs the target pair the bundle will serve.
+        self.assertIn("policyengine-core==3.1", by_step["audit-model-install"])
+        first = (root / "certification.pr-body.md").read_text().splitlines()[0]
+        self.assertIn("policyengine-core 3.1", first)
+        self.assertIn("`core_binding: bundle_pin`", first)
+
+    def test_an_operators_core_version_binds_the_certificate(self):
+        details = []
+        _, _, root = self.run_mock_pipeline(
+            evidence=EVIDENCE,
+            call_details=details,
+            bundle_packages={"policyengine-core": {"version": "3.1"}},
+            extra_args=["--core-version", "3.2"],
+        )
+        by_step = {kwargs.get("step"): argv for argv, kwargs in details}
+        certify = by_step["certify-data"]
+        self.assertEqual(certify[certify.index("--core-version") + 1], "3.2")
+        self.assertIn("policyengine-core==3.2", by_step["audit-model-install"])
+        first = (root / "certification.pr-body.md").read_text().splitlines()[0]
+        self.assertIn("`core_binding: certified`", first)
+
+    def test_each_rewritten_constant_file_is_listed_once(self):
+        with patch.object(
+            runner,
+            "rewrite_regional_constants",
+            return_value=["tests/test_uk_regions.py", "tests/test_models.py"],
+        ):
+            _, _, root = self.run_mock_pipeline(
+                evidence=EVIDENCE,
+                rewritten=["tests/test_models.py", "tests/test_uk_regions.py"],
+            )
+        self.assertIn(
+            "Certified-constant files rewritten: tests/test_models.py, "
+            "tests/test_uk_regions.py\n",
+            (root / "certification.pr-body.md").read_text(),
+        )
+
     def test_package_steps_get_no_hugging_face_token(self):
         details = []
         self.run_mock_pipeline(evidence=EVIDENCE, call_details=details)

From f32bc33826852ebe78437476798896c02cce289f Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 27 Nov 2026 16:37:44 +0400
Subject: [PATCH 10/10] Follow the bundle's core pin unless the operator names
 a core
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

From María's review of #1764. The tool always passed --core-version to
certify-data, so the certificate named one policyengine-core
(core_binding: certified) and moved the bundle's shared core pin, and a
later move of the pin for another country would have needed a UK
re-certification first. policyengine.py's default, which it has used for the
UK since 21 October, is a certificate that follows the pin (bundle_pin).

- certify-data gets --core-version only when the operator passes one.
- The accepted-mismatch audit installs the core the bundle will serve: the
  operator's, else the bundle's pin, else the build's own.
- The plan and the pull request body say which core the certificate covers
  and how it binds it.
- The body's commands show paths relative to the worktree, ../ beside it
  and ~/ under the home directory, and each JSON object argument (the
  bundle records the constant rewrite is passed) by its size, since
  --open-pr posts the body as it is.
- Each rewritten constant file is listed once.

Co-Authored-By: Claude Opus 5.5 
---
 ...-certification-tool-build-folders.fixed.md |  2 +-
 docs/uk-cut-anyone.md                         | 14 ++-
 tools/certify_uk_cut_in_policyengine_py.py    | 86 +++++++++++++++++--
 3 files changed, 92 insertions(+), 10 deletions(-)

diff --git a/changelog.d/1762-uk-certification-tool-build-folders.fixed.md b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
index 0e0b2d0457..02c909aebd 100644
--- a/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
+++ b/changelog.d/1762-uk-certification-tool-build-folders.fixed.md
@@ -1 +1 @@
-`tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build published into its own folder. It takes the national build by name (`--national-build`) and a local-area build the same way (`--dense-build`), refuses a build that `releases.json` at `main` does not list or has withdrawn, pins each build at the commit that published its folder (or a commit in `main`'s history named with `--national-data-commit` or `--dense-data-commit`), and hands policyengine.py's `certify-data` each build's folder manifest at that commit. `--keep-regional-release` reads the kept local-area build at the folder and commit the bundle pins, the regional microdata is read from the build's folder, and the certified-constant rewrite moves the local-area build's commit as well as its name. A Hub failure is a refusal, a policyengine.py base that cannot read build folders (policyengine.py#683) is refused before anything is downloaded, and a resumed worktree that pins another national commit or regional route is refused. Tags (`--national-tag`, `--dense-tag`) are no longer accepted, since policyengine.py refuses a tagged manifest from a repository with `releases.json`.
+`tools/certify_uk_cut_in_policyengine_py.py` certifies a UK build published into its own folder. It takes the national build by name (`--national-build`) and a local-area build the same way (`--dense-build`), refuses a build that `releases.json` at `main` does not list or has withdrawn, pins each build at the commit that published its folder (or a commit in `main`'s history named with `--national-data-commit` or `--dense-data-commit`), and hands policyengine.py's `certify-data` each build's folder manifest at that commit. `--keep-regional-release` reads the kept local-area build at the folder and commit the bundle pins, the regional microdata is read from the build's folder, and the certified-constant rewrite moves the local-area build's commit as well as its name. A Hub failure is a refusal, a policyengine.py base that cannot read build folders (policyengine.py#683) is refused before anything is downloaded, and a resumed worktree that pins another national commit or regional route is refused. Tags (`--national-tag`, `--dense-tag`) are no longer accepted, since policyengine.py refuses a tagged manifest from a repository with `releases.json`. The certificate follows the bundle's shared core pin (`core_binding: bundle_pin`, policyengine.py's default) unless `--core-version` names a core to bind, and the pull request body shows its commands without the operator's paths or the bundle records the constant rewrite is passed.
diff --git a/docs/uk-cut-anyone.md b/docs/uk-cut-anyone.md
index 89294aa5af..32e9e649c9 100644
--- a/docs/uk-cut-anyone.md
+++ b/docs/uk-cut-anyone.md
@@ -459,9 +459,15 @@ by hand, on a new branch from policyengine.py's main.
 
 **Then:**
 
-1. `certify-data` at the national build's own model and core, with each
-   build's folder manifest at its commit
+1. `certify-data` at the national build's own model, with each build's
+   folder manifest at its commit
    (`hf://dataset/policyengine/populace-uk-private@/releases///release_manifest.json`).
+   The certificate follows the bundle's shared core pin
+   (`core_binding: bundle_pin`), policyengine.py's default, so the pin can
+   move with another country without re-certifying the UK. `--core-version`
+   binds the certificate to one core and moves the pin to it
+   (`core_binding: certified`); use it only when the release must not run on
+   any other core.
 2. `uv lock` and `release_lock.py`.
 3. `generate --include-tros`.
 4. policyengine.py's own certified-constant rewrite, plus the local-area
@@ -475,7 +481,9 @@ by hand, on a new branch from policyengine.py's main.
 
 It commits. It pushes and opens a draft only when asked. The pull request
 body lists what needs a person: the UC floor acceptance, any dataset overlays
-certification dropped, warnings and failing tests.
+certification dropped, warnings and failing tests. Its commands show paths
+relative to the worktree and the home directory, and the bundle records the
+constant rewrite is passed only by their size.
 
 ## Regions: the dense cut
 
diff --git a/tools/certify_uk_cut_in_policyengine_py.py b/tools/certify_uk_cut_in_policyengine_py.py
index df55a7ddb7..a62b37f25e 100644
--- a/tools/certify_uk_cut_in_policyengine_py.py
+++ b/tools/certify_uk_cut_in_policyengine_py.py
@@ -587,6 +587,44 @@ def record_timing(path: Path, record: dict[str, Any]) -> None:
         handle.write(json.dumps(record) + "\n")
 
 
+def is_json_object(argument: str) -> bool:
+    if not argument.startswith("{"):
+        return False
+    try:
+        return isinstance(json.loads(argument), dict)
+    except ValueError:
+        return False
+
+
+def public_command(
+    argv: Sequence[str], worktree: Path, *, home: Path | None = None
+) -> str:
+    """A command as the pull request body shows it.
+
+    A path in the worktree is shown relative to it, since its commands run
+    there; one beside it starts ``../``, and one under the home directory
+    ``~/``, so the body names no operator's folders. A JSON object argument,
+    such as the bundle records the constant rewrite is passed, is shown as
+    its size.
+    """
+
+    home = Path.home() if home is None else home
+    prefixes = (
+        (f"{worktree}/", ""),
+        (f"{worktree.parent}/", "../"),
+        (f"{home}/", "~/"),
+    )
+    shown = []
+    for argument in argv:
+        if is_json_object(argument):
+            shown.append(f"")
+            continue
+        for prefix, replacement in prefixes:
+            argument = argument.replace(prefix, replacement)
+        shown.append(argument)
+    return shlex.join(shown)
+
+
 def pytest_command(
     python: str, arguments: list[str], *, startup_timeout: float = 300.0
 ) -> list[str]:
@@ -705,6 +743,12 @@ def __init__(
         self.timings = timings or log.with_suffix(".timings.jsonl")
         self.limits = {"max_load1": max_load1, "min_free_bytes": min_free_bytes}
         self.commands: list[str] = []
+        self.argvs: list[list[str]] = []
+
+    def public_commands(self, *, home: Path | None = None) -> list[str]:
+        """Each command run, as the pull request body shows it."""
+
+        return [public_command(argv, self.cwd, home=home) for argv in self.argvs]
 
     def __call__(
         self,
@@ -717,6 +761,7 @@ def __call__(
     ) -> subprocess.CompletedProcess:
         line = shlex.join(argv)
         self.commands.append(line)
+        self.argvs.append(list(argv))
         print(f"$ {line}", flush=True)
         if self.dry_run:
             return subprocess.CompletedProcess(argv, 0, "", "")
@@ -1106,10 +1151,24 @@ def uc_floor_summary(receipt: object) -> tuple[bool, str]:
     )
 
 
+def core_summary(context: Mapping[str, Any]) -> str:
+    """The core the certificate covers, and how it binds it."""
+
+    binding = context.get("core_binding")
+    if binding == "bundle_pin":
+        return (
+            f"policyengine-core {context['core']}, the bundle's pin "
+            "(`core_binding: bundle_pin`)"
+        )
+    if binding == "certified":
+        return f"policyengine-core {context['core']} (`core_binding: certified`)"
+    return f"core {context['core']}"
+
+
 def pr_body(context: dict[str, Any]) -> str:
     lines = [
         f"Certifies Microcosm UK national build `{context['national_build']}` "
-        f"(policyengine-uk {context['model']}, core {context['core']}), from its "
+        f"(policyengine-uk {context['model']}, {core_summary(context)}), from its "
         f"folder at commit `{context['national_commit']}`.",
         "",
         "**Mechanical handoff; wrapper qualification pending** unless reviewed "
@@ -1271,7 +1330,12 @@ def parse(argv: list[str] | None) -> argparse.Namespace:
         "of the one that published its folder",
     )
     parser.add_argument("--model-version", help="default: the build's own model")
-    parser.add_argument("--core-version", help="default: the build's own core")
+    parser.add_argument(
+        "--core-version",
+        help="bind the certificate to this policyengine-core and move the "
+        "bundle's core pin to it (core_binding: certified); default: the "
+        "certificate follows the bundle's core pin (bundle_pin)",
+    )
     parser.add_argument(
         "--pepy-repo",
         type=Path,
@@ -1451,7 +1515,6 @@ def certify(args: argparse.Namespace) -> int:
             NATIONAL_RELEASE, args.national_build, commit=args.national_data_commit
         )
     model = args.model_version or national.model
-    core = args.core_version or national.core
     if not covers(national, model):
         raise CertifyError(
             f"the national build was built with policyengine-uk {national.model} "
@@ -1471,6 +1534,14 @@ def certify(args: argparse.Namespace) -> int:
             )
         )
     record = old_bundle["data_releases"]["uk"]
+    # .py's default certificate follows the bundle's shared core pin
+    # (core_binding: bundle_pin); --core-version binds it to one core and
+    # moves the pin (certified). The audit runs the core the bundle will serve.
+    core_binding = "certified" if args.core_version else "bundle_pin"
+    pinned_core = (
+        (old_bundle.get("packages") or {}).get("policyengine-core") or {}
+    ).get("version")
+    core = args.core_version or pinned_core or national.core
     dense, mismatch, regional_artifacts = None, False, {}
     kept = kept_regional_pin(record) if args.keep_regional_release else None
     if args.dense_build or kept is not None:
@@ -1544,6 +1615,7 @@ def certify(args: argparse.Namespace) -> int:
         "national_manifest_uri": national.manifest_uri,
         "model": model,
         "core": core,
+        "core_binding": core_binding,
         "regional": regional_summary,
         "branch": branch,
         "worktree": str(worktree),
@@ -1620,7 +1692,8 @@ def certify(args: argparse.Namespace) -> int:
             "--data-producer", "populace",
             "--manifest-uri", national.manifest_uri,
             *flags,
-            "--model-version", model, "--core-version", core,
+            "--model-version", model,
+            *(["--core-version", core] if args.core_version else []),
         ], step="certify-data",
     )  # fmt: skip
     warnings = [
@@ -1726,15 +1799,16 @@ def certify(args: argparse.Namespace) -> int:
         "shared_old_commit": shared_old_commit,
         "model": model,
         "core": core,
+        "core_binding": core_binding,
         "regional_summary": f"`{regional_summary}`",
         "basis": (new_record.get("certification") or {}).get("compatibility_basis"),
         "microcosm_commit": microcosm_commit,
-        "commands": run.commands,
+        "commands": run.public_commands(),
         "uc_floor": f"`{uc_summary}`",
         "uc_floor_passed": uc_passed,
         "tests": tests_summary,
         "tests_failed": tests_failed,
-        "constants": ", ".join(constants),
+        "constants": ", ".join(dict.fromkeys(constants)),
         "dropped_overlays": overlay_diff(old_bundle, new_bundle),
         "warnings": warnings,
         "footer": args.pr_body_footer,