From bd3a4ad17220713b507b568375894160d9546eae Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:33:21 +0400 Subject: [PATCH 01/25] Add failing tests for the build compatibility check Tests for a scripts/bundle.py check-compatibility command that checks one Microcosm build against one model version, the record it writes, certify-data certifying on that record, and load-time acceptance of only the recorded build, model and core. They fail before the change: the modules they import do not exist yet. Co-Authored-By: Claude Opus 5.5 --- tests/test_compatibility_certification.py | 904 +++++++++++++++++++++ tests/test_compatibility_check.py | 938 ++++++++++++++++++++++ 2 files changed, 1842 insertions(+) create mode 100644 tests/test_compatibility_certification.py create mode 100644 tests/test_compatibility_check.py diff --git a/tests/test_compatibility_certification.py b/tests/test_compatibility_certification.py new file mode 100644 index 00000000..2010b1e6 --- /dev/null +++ b/tests/test_compatibility_certification.py @@ -0,0 +1,904 @@ +"""Tests for certifying a data build on a compatibility check record. + +A record from ``bundle.py check-compatibility`` binds one build (by its +manifest's SHA-256), one model wheel (by PyPI's SHA-256) and one core. +``certify-data`` certifies that exact combination on the basis +``compatibility_checked_exact_pair`` and stores the record beside the bundle; +loading a model accepts the certificate only for that build, model and core. +""" + +import importlib.util +import json +import sys +from pathlib import Path +from types import ModuleType +from unittest.mock import MagicMock, patch + +import pytest + +from policyengine.provenance.certification import ( + CertificationError, + certify_data_release, + model_compatibility_basis, + parse_manifest_uri, + validate_release_manifest, +) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + CompatibilityRecord, + bundled_compatibility_records, + compatibility_records_path, + matching_compatibility_record, + read_compatibility_records, + write_compatibility_records, +) +from policyengine.provenance.manifest import ( + CLAIM_BASED_COMPATIBILITY, + DataCertification, + DataReleaseManifest, + DataReleaseManifestUnavailableError, + _runtime_core_is_certified, + certify_data_release_compatibility, + get_data_release_manifest, + get_release_manifest, +) + +UK_TAG = "microcosm-uk-2024-25-national-20261122T100732Z-b891aa69" +UK_MANIFEST_URI = ( + "hf://dataset/policyengine/populace-uk-private" + f"@{UK_TAG}/releases/{UK_TAG}/release_manifest.json" +) +UK_DENSE_TAG = "microcosm-uk-2024-25-dense-20261123T075147Z-7081d968" +UK_DENSE_URI = ( + "hf://dataset/policyengine/populace-uk-private" + f"@{UK_DENSE_TAG}/releases/{UK_DENSE_TAG}/release_manifest.json" +) +BUILD_MODEL = "2.179.2" +TARGET_MODEL = "2.180.0" +CORE = "3.34.10" +OTHER_CORE = "3.35.0" +MANIFEST_SHA256 = "e" * 64 +DENSE_MANIFEST_SHA256 = "f" * 64 +WHEEL_SHA256 = "d" * 64 +WHEEL_URL = ( + "https://files.pythonhosted.org/packages/aa/bb/" + f"policyengine_uk-{TARGET_MODEL}-py3-none-any.whl" +) + + +def _manifest_payload( + *, + tag: str = UK_TAG, + built_with: str = BUILD_MODEL, + model_claims: tuple[str, ...] = (f"=={BUILD_MODEL}",), + core_claims: tuple[str, ...] = (f"=={CORE}",), +) -> dict: + return { + "schema_version": 1, + "data_package": {"name": "microcosm-data", "version": "0.1.0"}, + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": claim} for claim in model_claims + ], + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": claim} for claim in core_claims + ], + "default_datasets": {"national": "microcosm_uk_2024_25"}, + "build": { + "build_id": tag, + "built_at": "2026-11-22T17:14:41+00:00", + "built_with_model_package": { + "name": "policyengine-uk", + "version": built_with, + }, + "built_with_core_package": {"name": "policyengine-core", "version": CORE}, + }, + "artifacts": { + "microcosm_uk_2024_25": { + "kind": "microdata", + "path": "microcosm_uk_2024_25.h5", + "repo_id": "policyengine/populace-uk-private", + "revision": tag, + "sha256": "a" * 64, + }, + "calibration_diagnostics": { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": "policyengine/populace-uk-private", + "revision": tag, + "sha256": "c" * 64, + }, + }, + } + + +def _manifest(**kwargs) -> DataReleaseManifest: + return DataReleaseManifest.model_validate(_manifest_payload(**kwargs)) + + +def _dense_manifest(built_with: str = BUILD_MODEL) -> DataReleaseManifest: + return DataReleaseManifest.model_validate( + { + "schema_version": 1, + "data_package": {"name": "microcosm-data", "version": "0.1.0"}, + "dataset_role": "non_default_local_area", + "is_default": False, + "default_datasets": {}, + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": f"=={built_with}"} + ], + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": f"=={CORE}"} + ], + "build": { + "build_id": UK_DENSE_TAG, + "built_at": "2026-11-23T07:51:47+00:00", + "built_with_model_package": { + "name": "policyengine-uk", + "version": built_with, + }, + "built_with_core_package": { + "name": "policyengine-core", + "version": CORE, + }, + }, + "artifacts": { + "microcosm_uk_2024_25_dense": { + "kind": "microdata", + "path": "microcosm_uk_2024_25_dense.h5", + "repo_id": "policyengine/populace-uk-private", + "revision": UK_DENSE_TAG, + "sha256": "b" * 64, + } + }, + } + ) + + +def _record(**overrides) -> CompatibilityRecord: + model_package = { + "name": "policyengine-uk", + "version": TARGET_MODEL, + "wheel_sha256": WHEEL_SHA256, + "wheel_url": WHEEL_URL, + **overrides.pop("model_package", {}), + } + payload = { + "country": "uk", + "manifest_uri": UK_MANIFEST_URI, + "manifest_sha256": MANIFEST_SHA256, + "release": None, + "build": UK_TAG, + "built_with_model_version": BUILD_MODEL, + "built_with_core_version": CORE, + "model_package": model_package, + "core_version": CORE, + "policyengine_version": "6.20.5", + "sample": { + "method": "sha256_rank_v1", + "salt": "policyengine-compatibility-sample-v1", + "size": 2000, + }, + "headline_variables": ["household_net_income", "income_tax"], + "artifacts": { + "microcosm_uk_2024_25": { + "path": "microcosm_uk_2024_25.h5", + "revision": UK_TAG, + "sha256": "a" * 64, + "year": 2024, + "households": 20_000, + "sample_households": 2000, + "sample_household_ids_sha256": "9" * 64, + "totals": {"household_net_income": 1.0e9, "income_tax": 1.0e8}, + } + }, + "never_modelled_columns": [], + "defaulted_inputs": [], + "checked_at": "2026-12-03T00:00:00Z", + **overrides, + } + return CompatibilityRecord.model_validate(payload) + + +def _dense_record(**overrides) -> CompatibilityRecord: + return _record( + manifest_uri=UK_DENSE_URI, + manifest_sha256=DENSE_MANIFEST_SHA256, + build=UK_DENSE_TAG, + artifacts={ + "microcosm_uk_2024_25_dense": { + "path": "microcosm_uk_2024_25_dense.h5", + "revision": UK_DENSE_TAG, + "sha256": "b" * 64, + "year": 2024, + "households": 400_000, + "sample_households": 2000, + "sample_household_ids_sha256": "8" * 64, + "totals": {"household_net_income": 1.0e9, "income_tax": 1.0e8}, + } + }, + **overrides, + ) + + +class TestValidateWithRecord: + def test__given_record_for_a_newer_model__then_certifies_the_exact_pair(self): + basis, warnings = validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + assert any("compatibility check" in warning for warning in warnings) + + def test__given_publisher_claim_and_record__then_record_basis_replaces_it(self): + basis, _ = validate_release_manifest( + _manifest(model_claims=(">=2.179,<3",)), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_core_outside_claims__then_record_covers_it(self): + basis, _ = validate_release_manifest( + _manifest(core_claims=("==3.33.0",)), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_record_and_qualified_pair__then_refuses(self): + with pytest.raises(CertificationError, match="qualified"): + validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + qualified_pair_id="pair-1", + compatibility_record=_record(), + ) + + def test__given_other_core__then_refuses(self): + with pytest.raises(CertificationError, match=OTHER_CORE): + validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + core_version=OTHER_CORE, + compatibility_record=_record(), + ) + + def test__given_no_core__then_refuses(self): + with pytest.raises(CertificationError, match="core_version"): + validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + compatibility_record=_record(), + ) + + def test__given_record_for_another_model__then_refuses(self): + with pytest.raises(CertificationError, match="2.181.0"): + validate_release_manifest( + _manifest(), + "policyengine-uk", + "2.181.0", + core_version=CORE, + compatibility_record=_record(), + ) + + def test__given_record_for_the_builds_own_model__then_refuses(self): + with pytest.raises(CertificationError, match="built with"): + validate_release_manifest( + _manifest(built_with=TARGET_MODEL), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + def test__given_regional_record__then_regional_basis_is_the_exact_pair(self): + basis, warnings = model_compatibility_basis( + _dense_manifest(), + "policyengine-uk", + TARGET_MODEL, + compatibility_record=_dense_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + assert warnings + + +def _bundle(tmp_path: Path) -> Path: + bundle_path = tmp_path / "data" / "bundle" / "manifest.json" + bundle_path.parent.mkdir(parents=True) + bundle_path.write_text( + json.dumps( + { + "schema_version": 2, + "bundle_version": "9.9.9", + "policyengine_version": "9.9.9", + "packages": { + "policyengine": {"name": "policyengine", "version": "9.9.9"}, + "policyengine-core": { + "name": "policyengine-core", + "version": "3.30.0", + }, + "policyengine-uk": { + "name": "policyengine-uk", + "version": BUILD_MODEL, + }, + }, + "extras": {}, + "countries": {"uk": {"model_package": "policyengine-uk"}}, + "data_releases": {}, + } + ) + + "\n" + ) + return bundle_path + + +def _certify(bundle_path: Path, *, manifests=None, wheel_sha256=WHEEL_SHA256, **kwargs): + manifests = manifests or { + UK_MANIFEST_URI: (_manifest(), MANIFEST_SHA256), + UK_DENSE_URI: (_dense_manifest(), DENSE_MANIFEST_SHA256), + } + + def fetch(uri, token=None): + manifest, sha256 = manifests[uri] + return manifest.model_copy(deep=True), sha256, parse_manifest_uri(uri) + + with ( + patch("policyengine.provenance.certification.fetch_release_manifest", fetch), + patch( + "policyengine.provenance.certification.require_tagged_layout", + return_value=None, + ), + patch("policyengine.provenance.certification.head_artifact", return_value=True), + patch( + "policyengine.provenance.certification.head_release_file", + return_value=True, + ), + patch( + "policyengine.provenance.certification.head_artifact_reference", + return_value=True, + ), + patch( + "policyengine.provenance.certification.fetch_pypi_wheel_metadata", + return_value={"sha256": wheel_sha256, "url": WHEEL_URL}, + ), + patch( + "policyengine.provenance.certification.policyengine_version", + return_value="9.9.9", + ), + ): + return certify_data_release( + country="uk", + data_producer="populace", + manifest_uri=UK_MANIFEST_URI, + model_version=TARGET_MODEL, + bundle_path=bundle_path, + **kwargs, + ) + + +class TestCertifyWithRecord: + def test__given_record__then_certifies_exact_pair_and_stores_record(self, tmp_path): + bundle_path = _bundle(tmp_path) + record = _record() + + _certify(bundle_path, compatibility_record=record) + + bundle = json.loads(bundle_path.read_text()) + certification = bundle["data_releases"]["uk"]["certification"] + assert certification["compatibility_basis"] == BASIS_COMPATIBILITY_CHECKED + assert certification["certified_for_model_version"] == TARGET_MODEL + assert certification["certified_for_core_version"] == CORE + assert certification["core_binding"] == "certified" + assert certification["data_build_id"] == UK_TAG + assert bundle["packages"]["policyengine-core"]["version"] == CORE + assert bundle["packages"]["policyengine-uk"]["version"] == TARGET_MODEL + records_path = tmp_path / "data" / "compatibility" / "uk.json" + assert records_path == compatibility_records_path(tmp_path / "data", "uk") + assert read_compatibility_records(records_path, "uk") == [record] + + def test__given_record_for_other_manifest_bytes__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="manifest_sha256"): + _certify( + _bundle(tmp_path), + compatibility_record=_record(manifest_sha256="1" * 64), + ) + + def test__given_record_for_other_wheel__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="wheel_sha256"): + _certify( + _bundle(tmp_path), + compatibility_record=_record(), + wheel_sha256="2" * 64, + ) + + def test__given_record_for_other_build__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="build"): + _certify( + _bundle(tmp_path), + compatibility_record=_record(build="another-build"), + ) + + def test__given_record_as_json__then_reads_it(self, tmp_path): + bundle_path = _bundle(tmp_path) + + _certify(bundle_path, compatibility_record=_record().model_dump(mode="json")) + + bundle = json.loads(bundle_path.read_text()) + assert ( + bundle["data_releases"]["uk"]["certification"]["compatibility_basis"] + == BASIS_COMPATIBILITY_CHECKED + ) + + def test__given_certification_without_record__then_removes_stored_records( + self, tmp_path + ): + bundle_path = _bundle(tmp_path) + records_path = compatibility_records_path(tmp_path / "data", "uk") + write_compatibility_records(records_path, "uk", [_record()]) + + _certify( + bundle_path, + manifests={ + UK_MANIFEST_URI: (_manifest(built_with=TARGET_MODEL), MANIFEST_SHA256) + }, + ) + + assert not records_path.exists() + + def test__given_regional_record__then_routes_regions_on_the_exact_pair( + self, tmp_path + ): + bundle_path = _bundle(tmp_path) + manifests = { + UK_MANIFEST_URI: (_manifest(built_with=TARGET_MODEL), MANIFEST_SHA256), + UK_DENSE_URI: (_dense_manifest(), DENSE_MANIFEST_SHA256), + } + dense_record = _dense_record() + + _certify( + bundle_path, + manifests=manifests, + regional_manifest_uri=UK_DENSE_URI, + regional_compatibility_record=dense_record, + ) + + release = json.loads(bundle_path.read_text())["data_releases"]["uk"] + assert release["certification"]["compatibility_basis"] == ( + "built_with_model_package" + ) + assert release["certification"]["certified_for_core_version"] == CORE + assert release["regional_compatibility_basis"] == BASIS_COMPATIBILITY_CHECKED + assert "regional_certification" not in release + assert read_compatibility_records( + compatibility_records_path(tmp_path / "data", "uk"), "uk" + ) == [dense_record] + + def test__given_regional_record_and_accepted_mismatch__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="mismatch"): + _certify( + _bundle(tmp_path), + manifests={ + UK_MANIFEST_URI: ( + _manifest(built_with=TARGET_MODEL), + MANIFEST_SHA256, + ), + UK_DENSE_URI: (_dense_manifest(), DENSE_MANIFEST_SHA256), + }, + regional_manifest_uri=UK_DENSE_URI, + regional_compatibility_record=_dense_record(), + regional_model_mismatch_reason="reviewed", + ) + + def test__given_regional_record_without_regional_release__then_refuses( + self, tmp_path + ): + with pytest.raises(CertificationError, match="regional"): + _certify( + _bundle(tmp_path), + regional_compatibility_record=_dense_record(), + ) + + def test__given_regional_record_for_other_bytes__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="manifest_sha256"): + _certify( + _bundle(tmp_path), + manifests={ + UK_MANIFEST_URI: ( + _manifest(built_with=TARGET_MODEL), + MANIFEST_SHA256, + ), + UK_DENSE_URI: (_dense_manifest(), "3" * 64), + }, + regional_manifest_uri=UK_DENSE_URI, + regional_compatibility_record=_dense_record(), + ) + + +def _certificate(**overrides) -> DataCertification: + return DataCertification( + **{ + "compatibility_basis": BASIS_COMPATIBILITY_CHECKED, + "certified_for_model_version": TARGET_MODEL, + "certified_for_core_version": CORE, + "core_binding": "certified", + "data_build_id": UK_TAG, + "built_with_model_version": BUILD_MODEL, + **overrides, + } + ) + + +class TestRuntimeAcceptance: + def setup_method(self): + get_data_release_manifest.cache_clear() + + def _remote(self, source_sha256=MANIFEST_SHA256, **kwargs) -> DataReleaseManifest: + remote = _manifest(**kwargs) + remote.source_sha256 = source_sha256 + return remote + + def _load( + self, + certificate, + *, + remote=None, + records=(), + runtime_model=TARGET_MODEL, + core=CORE, + wheel_sha256=WHEEL_SHA256, + regional_basis=None, + regional_sha256=None, + ): + country_manifest = MagicMock(certification=certificate) + country_manifest.model_package.name = "policyengine-uk" + country_manifest.model_package.sha256 = wheel_sha256 + country_manifest.regional_compatibility_basis = regional_basis + country_manifest.regional_source_manifest_sha256 = regional_sha256 + if remote is None: + data_patch = patch( + "policyengine.provenance.manifest.get_data_release_manifest", + side_effect=DataReleaseManifestUnavailableError("private"), + ) + else: + data_patch = patch( + "policyengine.provenance.manifest.get_data_release_manifest", + return_value=remote, + ) + with ( + patch( + "policyengine.provenance.manifest.get_release_manifest", + return_value=country_manifest, + ), + data_patch, + patch( + "policyengine.provenance.manifest.bundled_compatibility_records", + return_value=list(records), + ), + ): + return certify_data_release_compatibility( + "uk", + runtime_model_version=runtime_model, + runtime_core_version=core, + ) + + def test__given_matching_record__then_accepts_the_certificate(self): + certificate = self._load( + _certificate(), remote=self._remote(), records=[_record()] + ) + + assert certificate.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_no_record__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load(_certificate(), remote=self._remote(), records=[]) + + def test__given_other_model__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(), + records=[_record()], + runtime_model="2.180.1", + ) + + def test__given_other_core__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(), + records=[_record()], + core=OTHER_CORE, + ) + + def test__given_other_manifest_bytes__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(source_sha256="4" * 64), + records=[_record()], + ) + + def test__given_other_wheel__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(), + records=[_record()], + wheel_sha256="5" * 64, + ) + + def test__given_publisher_claim__then_does_not_replace_a_missing_record(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(model_claims=(">=2.179,<3",)), + records=[], + ) + + def test__given_manifest_unavailable_and_matching_record__then_accepts(self): + certificate = self._load(_certificate(), records=[_record()]) + + assert certificate.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_manifest_unavailable_and_no_record__then_unverified(self): + certificate = self._load(_certificate(), records=[]) + + assert certificate.compatibility_basis == ( + "unverified_data_release_manifest_unavailable" + ) + + def test__given_regional_record__then_accepts(self): + certificate = self._load( + _certificate( + compatibility_basis="built_with_model_package", + built_with_model_version=TARGET_MODEL, + ), + remote=self._remote(built_with=TARGET_MODEL), + records=[_dense_record()], + regional_basis=BASIS_COMPATIBILITY_CHECKED, + regional_sha256=DENSE_MANIFEST_SHA256, + ) + + assert certificate.compatibility_basis == "exact_build_model_version" + + def test__given_regional_basis_without_record__then_refuses(self): + with pytest.raises(ValueError, match="regional"): + self._load( + _certificate( + compatibility_basis="built_with_model_package", + built_with_model_version=TARGET_MODEL, + ), + remote=self._remote(built_with=TARGET_MODEL), + records=[], + regional_basis=BASIS_COMPATIBILITY_CHECKED, + regional_sha256=DENSE_MANIFEST_SHA256, + ) + + def test__exact_pair_names_its_core(self): + assert BASIS_COMPATIBILITY_CHECKED in CLAIM_BASED_COMPATIBILITY + assert f"{BASIS_COMPATIBILITY_CHECKED}_local_manifest" in ( + CLAIM_BASED_COMPATIBILITY + ) + assert _runtime_core_is_certified(_certificate(), CORE) + assert not _runtime_core_is_certified(_certificate(), OTHER_CORE) + + +def test_committed_certificates_on_the_record_basis_have_records(): + """Every committed certificate resting on a check names a stored record.""" + + for country in ("uk", "us"): + records = bundled_compatibility_records(country) + release = get_release_manifest(country) + certificate = release.certification + if ( + certificate is not None + and certificate.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + ): + assert ( + matching_compatibility_record( + records, + country=country, + build=certificate.data_build_id, + model_package=release.model_package.name, + model_version=certificate.certified_for_model_version, + wheel_sha256=release.model_package.sha256, + core_version=certificate.certified_for_core_version, + ) + is not None + ), f"{country}: no stored compatibility record for the certificate" + if release.regional_compatibility_basis == BASIS_COMPATIBILITY_CHECKED: + assert certificate is not None + assert ( + matching_compatibility_record( + records, + country=country, + manifest_sha256=release.regional_source_manifest_sha256, + model_package=release.model_package.name, + model_version=certificate.certified_for_model_version, + wheel_sha256=release.model_package.sha256, + core_version=certificate.certified_for_core_version, + ) + is not None + ), f"{country}: no stored compatibility record for the regional release" + + +def _load_script(monkeypatch, name: str): + scripts_dir = Path(__file__).resolve().parents[1] / "scripts" + monkeypatch.syspath_prepend(str(scripts_dir)) + spec = importlib.util.spec_from_file_location( + f"{name}_under_test", scripts_dir / f"{name}.py" + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +class TestScripts: + def test__given_check_compatibility__then_runs_the_check_and_writes_record( + self, monkeypatch, tmp_path + ): + bundle_script = _load_script(monkeypatch, "bundle") + calls = [] + + def check(**kwargs): + calls.append(kwargs) + return _record() + + monkeypatch.setattr( + "policyengine.provenance.compatibility_check.check_build_compatibility", + check, + ) + output = tmp_path / "record.json" + + assert ( + bundle_script.main( + [ + "check-compatibility", + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--model-version", + TARGET_MODEL, + "--core-version", + CORE, + "--work-dir", + str(tmp_path / "work"), + "--output", + str(output), + ] + ) + == 0 + ) + + (call,) = calls + assert call["country"] == "uk" + assert call["manifest_uri"] == UK_MANIFEST_URI + assert call["model_version"] == TARGET_MODEL + assert call["core_version"] == CORE + assert call["work_dir"] == tmp_path / "work" + assert CompatibilityRecord.model_validate_json(output.read_text()) == ( + _record() + ) + + def test__given_certify_data_records__then_forwards_them(self, monkeypatch): + bundle_script = _load_script(monkeypatch, "bundle") + captured: dict[str, list[str]] = {} + fake = ModuleType("certify_data_release") + + def fake_main(argv): + captured["argv"] = argv + return 0 + + fake.main = fake_main + monkeypatch.setitem(sys.modules, "certify_data_release", fake) + + assert ( + bundle_script.main( + [ + "certify-data", + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--compatibility-record", + "national.json", + "--regional-manifest-uri", + UK_DENSE_URI, + "--regional-compatibility-record", + "dense.json", + ] + ) + == 0 + ) + + argv = captured["argv"] + assert argv[argv.index("--compatibility-record") + 1] == "national.json" + assert argv[argv.index("--regional-compatibility-record") + 1] == "dense.json" + + def test__given_record_files__then_certifier_reads_them( + self, monkeypatch, tmp_path + ): + certify_script = _load_script(monkeypatch, "certify_data_release") + national = tmp_path / "national.json" + national.write_text(_record().model_dump_json()) + dense = tmp_path / "dense.json" + dense.write_text(_dense_record().model_dump_json()) + calls = [] + + def certify(**kwargs): + calls.append(kwargs) + raise SystemExit(0) + + monkeypatch.setattr(certify_script, "certify_data_release", certify) + + with pytest.raises(SystemExit): + certify_script.main( + [ + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--compatibility-record", + str(national), + "--regional-manifest-uri", + UK_DENSE_URI, + "--regional-compatibility-record", + str(dense), + ] + ) + + (call,) = calls + assert call["compatibility_record"] == _record() + assert call["regional_compatibility_record"] == _dense_record() + + def test__given_strict_tro_on_record_basis__then_revalidates_with_the_record( + self, monkeypatch + ): + generator = _load_script(monkeypatch, "generate_trace_tros") + captured = {} + + class Stop(Exception): + pass + + def validate(*args, **kwargs): + captured.update(kwargs) + raise Stop + + monkeypatch.setattr(generator, "validate_release_manifest", validate) + monkeypatch.setattr( + generator, "bundled_compatibility_records", lambda country: [_record()] + ) + country = MagicMock() + country.country_id = "uk" + country.data_package.release_manifest_revision = UK_TAG + country.model_package.name = "policyengine-uk" + country.model_package.version = TARGET_MODEL + country.model_package.sha256 = WHEEL_SHA256 + country.model_package.wheel_url = WHEEL_URL + country.certification = _certificate() + data = _manifest() + data.source_sha256 = MANIFEST_SHA256 + + with pytest.raises(Stop): + generator._validate_reviewed_inputs(country, data, Path("unused.jsonld")) + + assert captured["core_version"] == CORE + assert captured["qualified_pair_id"] is None + assert captured["compatibility_record"] == _record() diff --git a/tests/test_compatibility_check.py b/tests/test_compatibility_check.py new file mode 100644 index 00000000..6555d4a7 --- /dev/null +++ b/tests/test_compatibility_check.py @@ -0,0 +1,938 @@ +"""Tests for the compatibility check of one data build against one model version. + +The check downloads the build's H5 files and the model wheel, reads the +stored columns, reads the build model's variables in a throwaway +environment, and runs a 2,000-household sample under the new model in +another. Every download and subprocess is replaced here, so no test +reaches Hugging Face, PyPI or uv. +""" + +import hashlib +import json +import math +import subprocess +from pathlib import Path +from types import SimpleNamespace + +import pandas as pd +import pytest + +from policyengine.provenance import compatibility_check, compatibility_probe +from policyengine.provenance.certification import parse_manifest_uri +from policyengine.provenance.compatibility_check import ( + HEADLINE_VARIABLES, + CompatibilityCheckError, + check_build_compatibility, + probe_command, + probe_environment, + total_problems, +) +from policyengine.provenance.compatibility_probe import ( + CHECK_IN_PROGRESS_BASIS, + SAMPLE_HOUSEHOLDS, + SAMPLE_METHOD, + SAMPLE_SALT, + household_ids_sha256, + replace_certificate_lookup, + run_probe, + sample_household_ids, + weighted_totals, +) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + CompatibilityRecord, + compatibility_record_problems, + compatibility_records_path, + matching_compatibility_record, + read_compatibility_records, + write_compatibility_records, +) +from policyengine.provenance.manifest import DataReleaseManifest + +UK_TAG = "uk-frs-calibration-attempt-20261122T100732Z-b891aa69" +UK_MANIFEST_URI = ( + "hf://dataset/policyengine/populace-uk-private" + f"@{UK_TAG}/releases/{UK_TAG}/release_manifest.json" +) +UK_DATASET = "microcosm_uk_2024_25" +BUILD_MODEL_VERSION = "2.179.2" +TARGET_MODEL_VERSION = "2.180.0" +CORE_VERSION = "3.34.10" +WHEEL_BYTES = b"policyengine-uk wheel" +WHEEL_URL = ( + "https://files.pythonhosted.org/packages/aa/bb/" + f"policyengine_uk-{TARGET_MODEL_VERSION}-py3-none-any.whl" +) +MANIFEST_SHA256 = "e" * 64 +UK_TOTALS = { + "household_net_income": 1_200_000.0, + "income_tax": 150_000.0, + "universal_credit": 20_000.0, + "child_benefit": 5_000.0, + "state_pension": 40_000.0, + "pension_credit": 3_000.0, + "housing_benefit": 4_000.0, +} +#: Stored in the file and defined by the build model only. +DROPPED_COLUMN = "retired_input" +#: Stored in the file and defined by neither model. +NEVER_MODELLED_COLUMN = "microcosm_area_code" +#: An input of the target model only, which the file does not store. +NEW_INPUT = "new_target_input" + + +def _sha256(content: bytes) -> str: + return hashlib.sha256(content).hexdigest() + + +def _uk_h5(path: Path, *, extra_household_columns: tuple[str, ...] = ()) -> Path: + with pd.HDFStore(path, mode="w") as store: + store.put("time_period", pd.Series([2024]), format="table") + store.put( + "person", + pd.DataFrame( + { + "person_id": [1.0, 2.0, 3.0], + "person_benunit_id": [1.0, 2.0, 3.0], + "person_household_id": [1.0, 2.0, 3.0], + "age": [30.0, 70.0, 45.0], + "employment_income": [20_000.0, 0.0, 35_000.0], + } + ), + format="table", + ) + store.put("benunit", pd.DataFrame({"benunit_id": [1.0, 2.0, 3.0]})) + household = { + "household_id": [1.0, 2.0, 3.0], + "household_weight": [100.0, 120.0, 80.0], + } + for column in extra_household_columns: + household[column] = [1.0, 2.0, 3.0] + store.put("household", pd.DataFrame(household), format="table") + return path + + +STORED_COLUMNS = [ + "age", + "benunit_id", + "employment_income", + "household_id", + "household_weight", + "person_benunit_id", + "person_household_id", + "person_id", +] +TARGET_VARIABLES = sorted( + [*STORED_COLUMNS, NEW_INPUT, *UK_TOTALS] + ["benunit_weight", "person_weight"] +) +TARGET_INPUTS = sorted([*STORED_COLUMNS, NEW_INPUT]) +BUILD_VARIABLES = sorted([*TARGET_VARIABLES, DROPPED_COLUMN]) +BUILD_INPUTS = sorted([*STORED_COLUMNS, DROPPED_COLUMN]) + + +def _uk_manifest(h5_sha256: str, **build_overrides) -> DataReleaseManifest: + build = { + "build_id": UK_TAG, + "built_at": "2026-11-22T17:14:41.779575+00:00", + "built_with_model_package": { + "name": "policyengine-uk", + "version": BUILD_MODEL_VERSION, + }, + "built_with_core_package": { + "name": "policyengine-core", + "version": CORE_VERSION, + }, + **build_overrides, + } + return DataReleaseManifest.model_validate( + { + "schema_version": 1, + "data_package": {"name": "microcosm-data", "version": "0.1.0"}, + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": f"=={BUILD_MODEL_VERSION}"} + ], + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": f"=={CORE_VERSION}"} + ], + "default_datasets": {"national": UK_DATASET}, + "build": build, + "artifacts": { + UK_DATASET: { + "kind": "microdata", + "path": f"{UK_DATASET}.h5", + "repo_id": "policyengine/populace-uk-private", + "repo_type": "dataset", + "revision": UK_TAG, + "sha256": h5_sha256, + }, + "calibration_diagnostics": { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": "policyengine/populace-uk-private", + "repo_type": "dataset", + "revision": UK_TAG, + "sha256": "c" * 64, + }, + }, + } + ) + + +def _bundle(tmp_path: Path) -> Path: + bundle_path = tmp_path / "bundle.json" + bundle_path.write_text( + json.dumps( + { + "packages": { + "policyengine-core": { + "name": "policyengine-core", + "version": CORE_VERSION, + }, + "spm-calculator": {"name": "spm-calculator", "version": "1.1.0"}, + } + } + ) + ) + return bundle_path + + +class FakeUv: + """Answers the build-model read and the probe as uv would.""" + + def __init__(self, *, target_variables=None, probe_result=None): + self.commands: list[list[str]] = [] + self.environments: list[dict] = [] + self.requests: list[dict] = [] + self.target_variables = target_variables or TARGET_VARIABLES + self.probe_result = probe_result + + def __call__(self, command, **kwargs): + self.commands.append(command) + self.environments.append(kwargs.get("env") or {}) + if "-c" in command: + surface = { + "model_version": BUILD_MODEL_VERSION, + "core_version": CORE_VERSION, + "variables": BUILD_VARIABLES, + "inputs": BUILD_INPUTS, + } + return subprocess.CompletedProcess(command, 0, json.dumps(surface), "") + request = json.loads(Path(command[-1]).read_text()) + self.requests.append(request) + result = self.probe_result or { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": self.target_variables, + "inputs": [name for name in TARGET_INPUTS if name in self.target_variables], + "input_aliases": {}, + "artifacts": { + name: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": dict(UK_TOTALS), + } + for name in request["artifacts"] + }, + } + Path(request["result_path"]).write_text(json.dumps(result)) + return subprocess.CompletedProcess(command, 0, "", "") + + +class FakeDownloads: + def __init__(self, files: dict[str, bytes]): + self.files = files + self.requests: list[tuple[str, dict]] = [] + + def __call__(self, url: str, destination: Path, headers: dict) -> None: + self.requests.append((url, headers)) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(self.files[url]) + + +def _h5_url() -> str: + return ( + "https://huggingface.co/datasets/policyengine/populace-uk-private/" + f"resolve/{UK_TAG}/{UK_DATASET}.h5" + ) + + +def _check( + tmp_path: Path, + monkeypatch, + *, + uv: FakeUv | None = None, + h5_bytes: bytes | None = None, + manifest_h5_sha256: str | None = None, + wheel_sha256: str | None = None, + model_version: str = TARGET_MODEL_VERSION, + manifest: DataReleaseManifest | None = None, + core_version: str | None = None, +): + source = _uk_h5(tmp_path / "source.h5", extra_household_columns=(DROPPED_COLUMN,)) + # The never-modelled column is stored too. + with pd.HDFStore(source, mode="a") as store: + household = store.select("household") + household[NEVER_MODELLED_COLUMN] = [7.0, 8.0, 9.0] + store.put("household", household, format="table") + stored = source.read_bytes() + served = stored if h5_bytes is None else h5_bytes + manifest = manifest or _uk_manifest(manifest_h5_sha256 or _sha256(stored)) + monkeypatch.setattr( + compatibility_check, + "fetch_release_manifest", + lambda uri, token=None: (manifest, MANIFEST_SHA256, parse_manifest_uri(uri)), + ) + monkeypatch.setattr( + compatibility_check, "require_tagged_layout", lambda *args, **kwargs: None + ) + monkeypatch.setattr( + compatibility_check, + "fetch_pypi_wheel_metadata", + lambda name, version: { + "sha256": wheel_sha256 or _sha256(WHEEL_BYTES), + "url": WHEEL_URL, + }, + ) + uv = uv or FakeUv() + downloads = FakeDownloads({_h5_url(): served, WHEEL_URL: WHEEL_BYTES}) + record = check_build_compatibility( + country="uk", + manifest_uri=UK_MANIFEST_URI, + model_version=model_version, + core_version=core_version, + work_dir=tmp_path / "work", + policyengine_source=tmp_path / "checkout", + bundle_path=_bundle(tmp_path), + run=uv, + download=downloads, + ) + return record, uv, downloads + + +class TestSampleHouseholdIds: + def test__given_more_households_than_the_sample__then_keeps_lowest_ranked( + self, + ): + household_ids = list(range(1, 5001)) + + sample = sample_household_ids(household_ids) + + ranked = sorted( + household_ids, + key=lambda household_id: hashlib.sha256( + f"{SAMPLE_SALT}:{household_id}".encode() + ).hexdigest(), + ) + assert SAMPLE_HOUSEHOLDS == 2000 + assert len(sample) == SAMPLE_HOUSEHOLDS + assert sample == sorted(ranked[:SAMPLE_HOUSEHOLDS]) + + def test__given_ids_in_another_order__then_draws_the_same_sample(self): + household_ids = list(range(1, 5001)) + + assert sample_household_ids(household_ids) == sample_household_ids( + list(reversed(household_ids)) + ) + + def test__given_whole_number_floats__then_reads_them_as_integers(self): + assert sample_household_ids([3.0, 1.0, 2.0]) == [1, 2, 3] + + def test__given_fewer_households_than_the_sample__then_keeps_all(self): + assert sample_household_ids([5, 9, 7], size=10) == [5, 7, 9] + + def test__given_repeated_ids__then_refuses(self): + with pytest.raises(ValueError, match="repeat"): + sample_household_ids([1, 2.0, 2]) + + def test__given_fractional_id__then_refuses(self): + with pytest.raises(ValueError, match="whole number"): + sample_household_ids([1, 1.5]) + + def test__given_ids__then_digest_covers_sorted_decimal_ids(self): + assert household_ids_sha256([3, 1.0, 2]) == _sha256(b"1\n2\n3") + + +class TestTotalProblems: + def test__given_positive_totals__then_none(self): + assert total_problems(UK_TOTALS, HEADLINE_VARIABLES["uk"]) == [] + + @pytest.mark.parametrize( + ("value", "reason"), + [(0.0, "not positive"), (-1.0, "not positive"), (math.nan, "not finite")], + ) + def test__given_bad_total__then_names_it(self, value, reason): + totals = {**UK_TOTALS, "pension_credit": value} + + problems = total_problems(totals, HEADLINE_VARIABLES["uk"]) + + assert len(problems) == 1 + assert "pension_credit" in problems[0] + assert reason in problems[0] + + def test__given_missing_total__then_names_it(self): + totals = { + name: value for name, value in UK_TOTALS.items() if name != "income_tax" + } + + problems = total_problems(totals, HEADLINE_VARIABLES["uk"]) + + assert problems == ["income_tax: no total"] + + def test__headline_variables_follow_the_agreed_lists(self): + assert HEADLINE_VARIABLES["uk"] == ( + "household_net_income", + "income_tax", + "universal_credit", + "child_benefit", + "state_pension", + "pension_credit", + "housing_benefit", + ) + assert HEADLINE_VARIABLES["us"] == ( + "household_net_income", + "income_tax", + "snap", + "ssi", + "social_security", + ) + + +class TestProbeCommand: + def test__given_pins__then_installs_exactly_them_from_pypi_in_isolation( + self, tmp_path + ): + command = probe_command( + policyengine_source=tmp_path / "checkout", + wheel_path=tmp_path / "policyengine_uk-2.180.0-py3-none-any.whl", + core_version=CORE_VERSION, + extra_requirements=["spm-calculator==1.1.0"], + request_path=tmp_path / "request.json", + ) + + assert command[:6] == [ + "uv", + "run", + "--isolated", + "--no-project", + "--no-config", + "--default-index", + ] + assert command[6] == "https://pypi.org/simple" + requirements = [ + command[index + 1] + for index, argument in enumerate(command) + if argument == "--with" + ] + assert requirements == [ + str(tmp_path / "checkout"), + str(tmp_path / "policyengine_uk-2.180.0-py3-none-any.whl"), + f"policyengine-core=={CORE_VERSION}", + "spm-calculator==1.1.0", + ] + assert command[-5:] == [ + "python", + "-I", + "-m", + "policyengine.provenance.compatibility_probe", + str(tmp_path / "request.json"), + ] + + def test__given_caller_environment__then_drops_tokens_and_uv_settings(self): + environment = probe_environment( + { + "PATH": "/bin", + "VIRTUAL_ENV": "/somewhere/.venv", + "UV_INDEX_URL": "https://mirror.invalid/simple", + "UV_CACHE_DIR": "/cache", + "HUGGING_FACE_TOKEN": "secret", + "HF_TOKEN": "secret", + "HUGGINGFACE_HUB_TOKEN": "secret", + "POLICYENGINE_UK_DATA_MANIFEST_FILE": "/manifest.json", + } + ) + + assert environment == { + "PATH": "/bin", + "UV_CACHE_DIR": "/cache", + "POLICYENGINE_SKIP_COUNTRY_IMPORTS": "1", + } + + +class TestCheckBuildCompatibility: + def test__given_compatible_build__then_writes_record(self, tmp_path, monkeypatch): + record, uv, downloads = _check( + tmp_path, + monkeypatch, + uv=FakeUv(target_variables=[*TARGET_VARIABLES, DROPPED_COLUMN]), + ) + + assert isinstance(record, CompatibilityRecord) + assert record.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + assert record.country == "uk" + assert record.manifest_uri == UK_MANIFEST_URI + assert record.manifest_sha256 == MANIFEST_SHA256 + assert record.build == UK_TAG + assert record.built_with_model_version == BUILD_MODEL_VERSION + assert record.built_with_core_version == CORE_VERSION + assert record.model_package.name == "policyengine-uk" + assert record.model_package.version == TARGET_MODEL_VERSION + assert record.model_package.wheel_sha256 == _sha256(WHEEL_BYTES) + assert record.model_package.wheel_url == WHEEL_URL + assert record.core_version == CORE_VERSION + assert record.policyengine_version == "6.20.5" + assert record.sample.method == SAMPLE_METHOD + assert record.sample.salt == SAMPLE_SALT + assert record.sample.size == SAMPLE_HOUSEHOLDS + assert record.headline_variables == list(HEADLINE_VARIABLES["uk"]) + assert list(record.artifacts) == [UK_DATASET] + artifact = record.artifacts[UK_DATASET] + assert artifact.path == f"{UK_DATASET}.h5" + assert artifact.revision == UK_TAG + assert artifact.year == 2024 + assert artifact.households == 3 + assert artifact.sample_households == 3 + assert artifact.totals == UK_TOTALS + assert record.never_modelled_columns == [NEVER_MODELLED_COLUMN] + assert record.defaulted_inputs == [NEW_INPUT] + # Only the microdata H5 and the wheel are downloaded. + assert [url for url, _ in downloads.requests] == [WHEEL_URL, _h5_url()] + + def test__given_check__then_probe_runs_the_verified_wheel_and_core( + self, tmp_path, monkeypatch + ): + _, uv, _ = _check( + tmp_path, + monkeypatch, + uv=FakeUv(target_variables=[*TARGET_VARIABLES, DROPPED_COLUMN]), + ) + + build_read, probe = uv.commands + assert f"policyengine-uk=={BUILD_MODEL_VERSION}" in build_read + assert "--exclude-newer" in build_read + wheel_argument = probe[probe.index(str(tmp_path / "checkout")) + 2] + assert Path(wheel_argument).name == WHEEL_URL.rsplit("/", 1)[1] + assert Path(wheel_argument).read_bytes() == WHEEL_BYTES + assert f"policyengine-core=={CORE_VERSION}" in probe + assert not any("spm-calculator" in argument for argument in probe) + assert uv.environments[1]["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] == "1" + (request,) = uv.requests + assert request["country"] == "uk" + assert request["model_version"] == TARGET_MODEL_VERSION + assert request["core_version"] == CORE_VERSION + assert request["sample_size"] == SAMPLE_HOUSEHOLDS + assert request["headline_variables"] == list(HEADLINE_VARIABLES["uk"]) + assert request["artifacts"][UK_DATASET]["year"] == 2024 + assert Path(request["artifacts"][UK_DATASET]["path"]).is_file() + + def test__given_column_the_new_model_dropped__then_refuses( + self, tmp_path, monkeypatch + ): + with pytest.raises(CompatibilityCheckError, match=DROPPED_COLUMN): + _check(tmp_path, monkeypatch) + + def test__given_h5_bytes_differ_from_manifest__then_refuses( + self, tmp_path, monkeypatch + ): + with pytest.raises(CompatibilityCheckError, match="SHA-256"): + _check(tmp_path, monkeypatch, manifest_h5_sha256="0" * 64) + + def test__given_wheel_bytes_differ_from_pypi__then_refuses( + self, tmp_path, monkeypatch + ): + with pytest.raises(CompatibilityCheckError, match="wheel"): + _check(tmp_path, monkeypatch, wheel_sha256="0" * 64) + + def test__given_the_builds_own_model__then_refuses(self, tmp_path, monkeypatch): + with pytest.raises(CompatibilityCheckError, match="built with"): + _check(tmp_path, monkeypatch, model_version=BUILD_MODEL_VERSION) + + def test__given_build_records_no_core__then_refuses(self, tmp_path, monkeypatch): + manifest = _uk_manifest("0" * 64, built_with_core_package=None) + + with pytest.raises(CompatibilityCheckError, match="core"): + _check(tmp_path, monkeypatch, manifest=manifest) + + def test__given_microdata_without_sha256__then_refuses(self, tmp_path, monkeypatch): + manifest = _uk_manifest("0" * 64) + manifest.artifacts[UK_DATASET].sha256 = None + + with pytest.raises(CompatibilityCheckError, match="sha256"): + _check(tmp_path, monkeypatch, manifest=manifest) + + def test__given_zero_total__then_refuses(self, tmp_path, monkeypatch): + result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": {**UK_TOTALS, "housing_benefit": 0.0}, + } + }, + } + + with pytest.raises(CompatibilityCheckError, match="housing_benefit"): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + + def test__given_probe_ran_another_model__then_refuses(self, tmp_path, monkeypatch): + result = { + "model_version": "2.180.1", + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": {}, + } + + with pytest.raises(CompatibilityCheckError, match="2.180.1"): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + + def test__given_sample_smaller_than_expected__then_refuses( + self, tmp_path, monkeypatch + ): + result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 2, + "sample_household_ids_sha256": household_ids_sha256([1, 2]), + "totals": dict(UK_TOTALS), + } + }, + } + + with pytest.raises(CompatibilityCheckError, match="sample"): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + + def test__given_core_version__then_runs_that_core(self, tmp_path, monkeypatch): + uv = FakeUv( + target_variables=[*TARGET_VARIABLES, DROPPED_COLUMN], + probe_result=None, + ) + uv.probe_result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": "3.35.0", + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": dict(UK_TOTALS), + } + }, + } + + record, uv, _ = _check(tmp_path, monkeypatch, uv=uv, core_version="3.35.0") + + assert record.core_version == "3.35.0" + assert "policyengine-core==3.35.0" in uv.commands[1] + + +class TestCompatibilityRecords: + def _record(self, **overrides) -> CompatibilityRecord: + payload = { + "country": "uk", + "manifest_uri": UK_MANIFEST_URI, + "manifest_sha256": MANIFEST_SHA256, + "release": None, + "build": UK_TAG, + "built_with_model_version": BUILD_MODEL_VERSION, + "built_with_core_version": CORE_VERSION, + "model_package": { + "name": "policyengine-uk", + "version": TARGET_MODEL_VERSION, + "wheel_sha256": _sha256(WHEEL_BYTES), + "wheel_url": WHEEL_URL, + }, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "sample": { + "method": SAMPLE_METHOD, + "salt": SAMPLE_SALT, + "size": SAMPLE_HOUSEHOLDS, + }, + "headline_variables": list(HEADLINE_VARIABLES["uk"]), + "artifacts": { + UK_DATASET: { + "path": f"{UK_DATASET}.h5", + "revision": UK_TAG, + "sha256": "a" * 64, + "year": 2024, + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": "b" * 64, + "totals": UK_TOTALS, + } + }, + "never_modelled_columns": [], + "defaulted_inputs": [], + "checked_at": "2026-12-03T00:00:00Z", + **overrides, + } + return CompatibilityRecord.model_validate(payload) + + def _binding(self, **overrides) -> dict: + return { + "country": "uk", + "manifest_sha256": MANIFEST_SHA256, + "build": UK_TAG, + "model_package": "policyengine-uk", + "model_version": TARGET_MODEL_VERSION, + "wheel_sha256": _sha256(WHEEL_BYTES), + "core_version": CORE_VERSION, + **overrides, + } + + def test__given_unknown_field__then_refuses(self): + with pytest.raises(ValueError): + self._record(note="unexpected") + + def test__given_matching_binding__then_no_problems(self): + assert compatibility_record_problems(self._record(), **self._binding()) == [] + + @pytest.mark.parametrize( + ("field", "value"), + [ + ("manifest_sha256", "f" * 64), + ("build", "another-build"), + ("model_version", "2.181.0"), + ("wheel_sha256", "f" * 64), + ("core_version", "3.35.0"), + ], + ) + def test__given_other_binding__then_names_the_field(self, field, value): + problems = compatibility_record_problems( + self._record(), **self._binding(**{field: value}) + ) + + assert len(problems) == 1 + assert problems[0].startswith(f"{field}:") + + def test__given_unknown_expected_value__then_it_is_a_problem(self): + problems = compatibility_record_problems( + self._record(), **self._binding(wheel_sha256=None) + ) + + assert len(problems) == 1 + assert problems[0].startswith("wheel_sha256:") + + def test__given_records__then_finds_the_matching_one(self): + other = self._record(build="another-build") + record = self._record() + + assert ( + matching_compatibility_record([other, record], **self._binding()) is record + ) + assert matching_compatibility_record([other], **self._binding()) is None + + def test__given_records__then_round_trips_through_the_country_file(self, tmp_path): + path = compatibility_records_path(tmp_path, "uk") + record = self._record() + + write_compatibility_records(path, "uk", [record]) + + assert path == tmp_path / "compatibility" / "uk.json" + assert read_compatibility_records(path, "uk") == [record] + assert json.loads(path.read_text())["country"] == "uk" + + def test__given_no_records__then_removes_the_country_file(self, tmp_path): + path = compatibility_records_path(tmp_path, "uk") + write_compatibility_records(path, "uk", [self._record()]) + + write_compatibility_records(path, "uk", []) + + assert not path.exists() + assert read_compatibility_records(path, "uk") == [] + + def test__given_file_for_another_country__then_refuses(self, tmp_path): + path = compatibility_records_path(tmp_path, "uk") + write_compatibility_records(path, "uk", [self._record()]) + + with pytest.raises(ValueError, match="us"): + read_compatibility_records(path, "us") + + +class TestProbe: + def test__given_lookup_replaced__then_model_constructor_gets_a_placeholder( + self, monkeypatch + ): + from policyengine.tax_benefit_models.common import model_version + + # Restored when the test ends. + monkeypatch.setattr( + model_version, + "certify_data_release_compatibility", + model_version.certify_data_release_compatibility, + ) + + replace_certificate_lookup() + certificate = model_version.certify_data_release_compatibility( + "uk", runtime_model_version="2.180.0", runtime_data_build_fingerprint=None + ) + + assert certificate.compatibility_basis == CHECK_IN_PROGRESS_BASIS + assert certificate.certified_for_model_version == "2.180.0" + + def test__given_output__then_weights_each_variable_by_its_entity(self): + output = SimpleNamespace( + data=SimpleNamespace( + household=pd.DataFrame( + { + "household_net_income": [10.0, 20.0], + "household_weight": [2.0, 3.0], + } + ), + person=pd.DataFrame( + {"income_tax": [1.0, 4.0, 5.0], "person_weight": [1.0, 1.0, 2.0]} + ), + ) + ) + + totals = weighted_totals( + output, {"household_net_income": "household", "income_tax": "person"} + ) + + assert totals == {"household_net_income": 80.0, "income_tax": 15.0} + + def test__given_request__then_samples_simulates_and_reports( + self, tmp_path, monkeypatch + ): + household_ids = [float(household_id) for household_id in range(1, 2501)] + dataset = SimpleNamespace( + data=SimpleNamespace( + household=pd.DataFrame({"household_id": household_ids}) + ) + ) + created = [] + simulated = [] + + def create_datasets(datasets, years, data_folder, allow_unmanaged): + created.append((datasets, years, data_folder, allow_unmanaged)) + return {"source_2024": dataset} + + model = SimpleNamespace( + get_variable=lambda name: SimpleNamespace( + entity="person" if name == "income_tax" else "household" + ) + ) + + def simulate(dataset_argument, model_argument, sample, variables_by_entity): + simulated.append((dataset_argument, sample, variables_by_entity)) + return SimpleNamespace( + data=SimpleNamespace( + household=pd.DataFrame( + { + "household_net_income": [1.0] * len(sample), + "household_weight": [2.0] * len(sample), + } + ), + person=pd.DataFrame({"income_tax": [3.0], "person_weight": [1.0]}), + ) + ) + + monkeypatch.setattr( + compatibility_probe, + "installed_version", + lambda package: { + "policyengine-uk": TARGET_MODEL_VERSION, + "policyengine-core": CORE_VERSION, + "policyengine": "6.20.5", + }[package], + ) + result = run_probe( + { + "country": "uk", + "model_package": "policyengine-uk", + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "headline_variables": ["household_net_income", "income_tax"], + "sample_size": SAMPLE_HOUSEHOLDS, + "artifacts": { + UK_DATASET: {"path": str(tmp_path / "source.h5"), "year": 2024} + }, + "data_folder": str(tmp_path / "datasets"), + "result_path": str(tmp_path / "result.json"), + }, + load_country=lambda country: (create_datasets, model), + model_surface=lambda version, package: (["a", "b"], ["a"], {}), + simulate=simulate, + ) + + sample = sample_household_ids(household_ids) + assert created == [ + ( + [str(tmp_path / "source.h5")], + [2024], + str(tmp_path / "datasets" / UK_DATASET), + True, + ) + ] + (simulated_call,) = simulated + assert simulated_call[1] == sample + assert simulated_call[2] == { + "household": ["household_net_income"], + "person": ["income_tax"], + } + assert result["model_version"] == TARGET_MODEL_VERSION + assert result["core_version"] == CORE_VERSION + assert result["policyengine_version"] == "6.20.5" + assert result["variables"] == ["a", "b"] + assert result["inputs"] == ["a"] + assert result["input_aliases"] == {} + assert result["artifacts"][UK_DATASET] == { + "households": 2500, + "sample_households": SAMPLE_HOUSEHOLDS, + "sample_household_ids_sha256": household_ids_sha256(sample), + "totals": { + "household_net_income": 2.0 * SAMPLE_HOUSEHOLDS, + "income_tax": 3.0, + }, + } + + def test__given_another_core_installed__then_refuses(self, tmp_path, monkeypatch): + monkeypatch.setattr( + compatibility_probe, + "installed_version", + lambda package: { + "policyengine-uk": TARGET_MODEL_VERSION, + "policyengine-core": "3.35.0", + "policyengine": "6.20.5", + }[package], + ) + + with pytest.raises(compatibility_probe.CompatibilityProbeError, match="3.35.0"): + run_probe( + { + "country": "uk", + "model_package": "policyengine-uk", + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "headline_variables": [], + "sample_size": SAMPLE_HOUSEHOLDS, + "artifacts": {}, + "data_folder": str(tmp_path), + "result_path": str(tmp_path / "result.json"), + }, + load_country=lambda country: (None, None), + model_surface=lambda version, package: ([], [], {}), + simulate=lambda *args: None, + ) From e081234dd2b62de1a67e3b49b0dd0964e63fa673 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:44:25 +0400 Subject: [PATCH 02/25] Check one Microcosm build against one model version scripts/bundle.py check-compatibility checks one UK or US build against one model version: certify-data's metadata checks, the input columns of every microdata H5 file against the build's model and the new one, and a 2,000-household sample run through .py under the new model's PyPI wheel and the chosen core. A pass writes a record bound to the SHA-256 of the build's release_manifest.json and of the wheel. certify-data --compatibility-record (and --regional-compatibility-record) certifies on that record, on the basis compatibility_checked_exact_pair, and stores it in src/policyengine/data/compatibility/.json. Loading a model accepts such a certificate only for the recorded build, wheel and core, with or without network access to the manifest. Co-Authored-By: Claude Opus 5.5 --- docs/release-bundles.md | 20 +- scripts/bundle.py | 98 +++ scripts/certify_data_release.py | 28 + scripts/generate_trace_tros.py | 33 + src/policyengine/provenance/certification.py | 229 ++++++- .../provenance/compatibility_check.py | 569 ++++++++++++++++++ .../provenance/compatibility_probe.py | 248 ++++++++ .../provenance/compatibility_record.py | 215 +++++++ src/policyengine/provenance/manifest.py | 136 ++++- 9 files changed, 1563 insertions(+), 13 deletions(-) create mode 100644 src/policyengine/provenance/compatibility_check.py create mode 100644 src/policyengine/provenance/compatibility_probe.py create mode 100644 src/policyengine/provenance/compatibility_record.py diff --git a/docs/release-bundles.md b/docs/release-bundles.md index b4f8199e..d46c623d 100644 --- a/docs/release-bundles.md +++ b/docs/release-bundles.md @@ -641,8 +641,24 @@ Things that should usually not affect the fingerprint: recorded with a warning and made good by the test suite passing on the pinned pair) -If neither is true, certification fails hard and a new data build or a -published compatibility claim is required. A `data_build_fingerprint` +3. a compatibility check of exactly this build, model wheel and core passed + (`compatibility_basis: compatibility_checked_exact_pair`). `python + scripts/bundle.py check-compatibility` runs it from a checkout, for one + UK or US Microcosm build and one model version: `certify-data`'s metadata + checks, the input columns of every microdata H5 file (a column the build's + model defines and the new model does not refuses), and a 2,000-household + sample run through .py under the new model's PyPI wheel. A pass writes a + record naming the build by the SHA-256 of its `release_manifest.json` and + the model by its wheel's SHA-256. `certify-data --compatibility-record` + (or `--regional-compatibility-record` for the regional release) certifies + on it and stores it in `src/policyengine/data/compatibility/.json`; + a model loads the certificate only for that build, wheel and core. The + record replaces a publisher claim, but never applies to the build's own + model or with a qualified pair. + +If none is true, certification fails hard and a new data build, a published +compatibility claim or a passed compatibility check is required. A +`data_build_fingerprint` basis (same fingerprint as the build-time model) is a planned third basis; it requires fingerprint metadata from the installed model package. diff --git a/scripts/bundle.py b/scripts/bundle.py index b05ffa58..40bac21f 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -7,6 +7,9 @@ Examples: python scripts/bundle.py update-packages --us 1.730.0 --uk 2.91.0 + python scripts/bundle.py check-compatibility --country uk \ + --manifest-uri hf://... --model-version 2.180.0 \ + --work-dir /tmp/check --output record.json python scripts/bundle.py certify-data --country uk --manifest-uri hf://... python scripts/bundle.py generate python scripts/bundle.py generate --include-tros @@ -66,9 +69,55 @@ def _certify_data(args: argparse.Namespace) -> int: argv.extend(["--core-version", args.core_version]) if args.qualified_pair_id: argv.extend(["--qualified-pair-id", args.qualified_pair_id]) + if args.compatibility_record: + argv.extend(["--compatibility-record", args.compatibility_record]) + if args.regional_compatibility_record: + argv.extend( + ["--regional-compatibility-record", args.regional_compatibility_record] + ) return certify_data_release_main(argv) +def _check_compatibility(args: argparse.Namespace) -> int: + """Check one build against one model version; write the record of a pass.""" + from policyengine.provenance import compatibility_check + + if not (REPO_ROOT / "pyproject.toml").is_file(): + raise ValueError( + "check-compatibility runs from a checkout of policyengine.py: the " + "sample run installs this checkout." + ) + token = os.environ.get("HUGGING_FACE_TOKEN") or os.environ.get("HF_TOKEN") + try: + record = compatibility_check.check_build_compatibility( + country=args.country, + manifest_uri=args.manifest_uri, + model_version=args.model_version, + core_version=args.core_version, + token=token, + work_dir=Path(args.work_dir), + policyengine_source=REPO_ROOT, + bundle_path=REPO_ROOT + / "src" + / "policyengine" + / "data" + / "bundle" + / "manifest.json", + ) + except compatibility_check.CompatibilityCheckError as exc: + print(f"The build does not pass: {exc}", file=sys.stderr) + return 1 + output = Path(args.output) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(record.model_dump_json(indent=2) + "\n") + print( + f"{args.country.upper()} build {record.build} passes with " + f"{record.model_package.name} {record.model_package.version} and " + f"policyengine-core {record.core_version}; record: {output}" + ) + return 0 + + def _update_packages(args: argparse.Namespace) -> int: from prepare_package_bundle_update import main as prepare_package_bundle_update_main @@ -281,8 +330,57 @@ def _parser() -> argparse.ArgumentParser: "--qualified-pair-id", help="Admit the exact pair on automated qualification (needs --core-version).", ) + certify.add_argument( + "--compatibility-record", + help=( + "Record from check-compatibility: certify exactly its model, core " + "and build on the basis compatibility_checked_exact_pair." + ), + ) + certify.add_argument( + "--regional-compatibility-record", + help=( + "Record from check-compatibility for the regional release: route " + "regions to it on that record." + ), + ) certify.set_defaults(func=_certify_data) + compatibility = subparsers.add_parser( + "check-compatibility", + help=( + "Check one Microcosm build against one model version and write the " + "record certify-data --compatibility-record reads." + ), + ) + compatibility.add_argument("--country", required=True, choices=["us", "uk"]) + compatibility.add_argument( + "--manifest-uri", + required=True, + help="hf://dataset/@/", + ) + compatibility.add_argument( + "--model-version", + required=True, + help="The model package version to check, installed from its PyPI wheel.", + ) + compatibility.add_argument( + "--core-version", + help="policyengine-core version to run (default: the bundle's pin).", + ) + compatibility.add_argument( + "--work-dir", + required=True, + help=( + "Folder for the downloaded wheel and H5 files and the sample run; " + "files already there with the expected SHA-256 are reused." + ), + ) + compatibility.add_argument( + "--output", required=True, help="Where to write the record of a pass." + ) + compatibility.set_defaults(func=_check_compatibility) + packages = subparsers.add_parser( "update-packages", help="Update package pins in the bundle manifest.", diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index 34129745..71ba8a04 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -39,6 +39,15 @@ REGIONAL_RELEASE_KINDS, certify_data_release, ) +from policyengine.provenance.compatibility_record import ( # noqa: E402 + CompatibilityRecord, +) + + +def _read_record(path: Path | None) -> CompatibilityRecord | None: + if path is None: + return None + return CompatibilityRecord.model_validate_json(path.read_bytes()) def main(argv=None) -> int: @@ -136,6 +145,23 @@ def main(argv=None) -> int: "the regional bytes, its build model and the exact target model." ), ) + parser.add_argument( + "--compatibility-record", + type=Path, + help=( + "Record from bundle.py check-compatibility: certify exactly its " + "model, core and build on the basis compatibility_checked_exact_pair. " + "The core defaults to the record's." + ), + ) + parser.add_argument( + "--regional-compatibility-record", + type=Path, + help=( + "Record from bundle.py check-compatibility for the regional release " + "named by --regional-manifest-uri." + ), + ) parser.add_argument("--no-changelog", action="store_true") parser.add_argument( "--skip-artifact-check", @@ -175,6 +201,8 @@ def main(argv=None) -> int: if args.regional_input_surface_evidence is not None else None ), + compatibility_record=_read_record(args.compatibility_record), + regional_compatibility_record=_read_record(args.regional_compatibility_record), ) print(result.summary()) diff --git a/scripts/generate_trace_tros.py b/scripts/generate_trace_tros.py index 656d1868..fe3ec79c 100644 --- a/scripts/generate_trace_tros.py +++ b/scripts/generate_trace_tros.py @@ -26,6 +26,11 @@ core_claim_warning, validate_release_manifest, ) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + bundled_compatibility_records, + matching_compatibility_record, +) from policyengine.provenance.manifest import ( CountryReleaseManifest, DataReleaseManifest, @@ -78,6 +83,25 @@ def _validate_reviewed_inputs( != country.model_package.version ): raise ValueError(f"{prefix} requires certification for the pinned model") + compatibility_record = None + if country.certification.compatibility_basis == BASIS_COMPATIBILITY_CHECKED: + # The certificate stands only with the record of the check that ran + # exactly these manifest bytes, model wheel and core. + compatibility_record = matching_compatibility_record( + bundled_compatibility_records(country.country_id), + country=country.country_id, + manifest_sha256=data.source_sha256, + build=country.certification.data_build_id, + model_package=country.model_package.name, + model_version=country.model_package.version, + wheel_sha256=country.model_package.sha256, + core_version=country.certification.certified_for_core_version, + ) + if compatibility_record is None: + raise ValueError( + f"{prefix} requires the stored compatibility record of the " + "certified build, model wheel and core" + ) validate_release_manifest( data, country.model_package.name, @@ -90,6 +114,7 @@ def _validate_reviewed_inputs( if country.certification.compatibility_basis == "qualified_exact_pair" else None ), + compatibility_record=compatibility_record, ) certified = country.certified_data_artifact artifact = data.artifacts.get(certified.dataset) if certified else None @@ -152,6 +177,14 @@ def _validate_runtime_model(bundle: dict, country: CountryReleaseManifest) -> No raise ValueError( f"{prefix}: a qualified exact pair must name its pair and core" ) + if ( + certification is not None + and certification.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + and not certification.certified_for_core_version + ): + raise ValueError( + f"{prefix}: a compatibility check's certificate must name its core" + ) if ( certification is not None and certification.core_binding is not None diff --git a/src/policyengine/provenance/certification.py b/src/policyengine/provenance/certification.py index 72a27890..6c81b251 100644 --- a/src/policyengine/provenance/certification.py +++ b/src/policyengine/provenance/certification.py @@ -62,6 +62,13 @@ LOCAL_AUTHORITY_ASSET_SPEC, ) from policyengine.provenance.bundle_validation import shadowed_dataset_overlays +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + CompatibilityRecord, + compatibility_record_problems, + compatibility_records_path, + write_compatibility_records, +) from policyengine.provenance.manifest import ( HF_REQUEST_TIMEOUT_SECONDS, RELEASES_RECORD_NAME, @@ -406,6 +413,7 @@ def validate_release_manifest( *, core_version: Optional[str] = None, qualified_pair_id: Optional[str] = None, + compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[str, list[str]]: """Hard checks raise; returns ``(compatibility_basis, warnings)``. @@ -423,6 +431,13 @@ def validate_release_manifest( qualified pair. A core admitted only by the qualification makes the basis ``qualified_exact_pair`` whatever the model's own claim, so the certificate names the pair and its ledger evidence is enforced. + + ``compatibility_record`` (``bundle.py check-compatibility``) admits + exactly the model, core and build the check ran, on the basis + ``compatibility_checked_exact_pair``. It replaces a publisher claim and + covers a core outside the release's core claims, but never applies to + the build's own model, which is certified on its build. It cannot be + combined with a qualified pair. """ warnings: list[str] = [] if "national" not in manifest.default_datasets: @@ -440,6 +455,21 @@ def validate_release_manifest( if not artifact.sha256: warnings.append(f"artifact {name!r} has no sha256") + if compatibility_record is not None: + if qualified_pair_id is not None: + raise CertificationError( + "A compatibility record and a qualified pair are two different " + "bases; pass one of them." + ) + return _compatibility_record_basis( + manifest, + model_package, + model_version, + core_version, + compatibility_record, + warnings, + ) + basis, basis_warning, refusal = _release_model_basis( manifest, model_package, model_version ) @@ -525,18 +555,73 @@ def _release_model_basis( ) +def _compatibility_record_basis( + manifest: DataReleaseManifest, + model_package: str, + model_version: str, + core_version: Optional[str], + record: CompatibilityRecord, + warnings: list[str], +) -> tuple[str, list[str]]: + """Certify exactly the model, core and build a compatibility check ran.""" + + if core_version is None: + raise CertificationError( + "A compatibility record names its core version; pass core_version." + ) + problems = compatibility_record_problems( + record, + build=release_build_id(manifest.build), + model_package=model_package, + model_version=model_version, + core_version=core_version, + ) + if problems: + raise CertificationError( + "The compatibility record is for another build, model or core: " + f"{'; '.join(problems)}." + ) + basis, _, _ = _release_model_basis(manifest, model_package, model_version) + if basis == BASIS_BUILT_WITH: + raise CertificationError( + f"The build was built with {model_package} {model_version}; certify " + "it without a compatibility record." + ) + warnings.append( + f"certifying exactly {model_package}=={model_version} with " + f"policyengine-core=={core_version} on the compatibility check of build " + f"{record.build} at {record.checked_at}; the certificate stands only " + f"with that record stored in data/compatibility/{record.country}.json" + ) + return BASIS_COMPATIBILITY_CHECKED, warnings + + def model_compatibility_basis( manifest: DataReleaseManifest, model_package: str, model_version: str, + compatibility_record: Optional[CompatibilityRecord] = None, + *, + core_version: Optional[str] = None, ) -> tuple[str, list[str]]: """Return the basis on which a release serves a model version by itself. The release must be built with ``model_version`` or claim compatibility with it; automated qualification of a pair does not apply. Certification - uses this for a regional release, which no qualification names. Returns + uses this for a regional release, which no qualification names. A + ``compatibility_record`` of the release admits exactly the checked model + and core (``core_version``, by default the record's). Returns ``(compatibility_basis, warnings)``. """ + if compatibility_record is not None: + return _compatibility_record_basis( + manifest, + model_package, + model_version, + core_version or compatibility_record.core_version, + compatibility_record, + [], + ) basis, warning, refusal = _release_model_basis( manifest, model_package, model_version ) @@ -1490,6 +1575,7 @@ def build_bundle_data_release_payload( regional_release_kind: Optional[RegionalReleaseKind] = None, regional_certification: Optional[dict] = None, regional_manifest_sha256: Optional[str] = None, + regional_compatibility_basis: Optional[str] = None, ) -> dict: """Map the country certification payload into bundle ``data_releases``.""" payload = copy.deepcopy(country_payload) @@ -1513,10 +1599,40 @@ def build_bundle_data_release_payload( payload["regional_release_kind"] = regional_release_kind if regional_certification is not None: payload["regional_certification"] = regional_certification + if regional_compatibility_basis is not None: + payload["regional_compatibility_basis"] = regional_compatibility_basis payload["default_dataset_uri"] = certified_artifact.get("uri") return payload +def _require_record_binds( + record: CompatibilityRecord, label: str, **expected: Optional[str] +) -> None: + """Refuse a compatibility record of another build, model, core or wheel.""" + + problems = compatibility_record_problems(record, **expected) + if problems: + raise CertificationError( + f"The {label}'s compatibility record does not match it: " + f"{'; '.join(problems)}." + ) + + +def _as_compatibility_record( + value: Optional[CompatibilityRecord | dict], label: str +) -> Optional[CompatibilityRecord]: + """Read a record given as a model or as its JSON object.""" + + if value is None or isinstance(value, CompatibilityRecord): + return value + try: + return CompatibilityRecord.model_validate(value) + except ValidationError as exc: + raise CertificationError( + f"The {label} is not a compatibility record: {exc}" + ) from exc + + class DataProducerCertificationStrategy: data_producer: str @@ -1538,6 +1654,8 @@ def certify( bundle_core_version: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord] = None, + regional_compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[dict, str, list[str]]: raise NotImplementedError @@ -1563,6 +1681,8 @@ def certify( bundle_core_version: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord] = None, + regional_compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[dict, str, list[str]]: raise CertificationError( "Legacy data-producer certification updates are not implemented in " @@ -1591,11 +1711,21 @@ def certify( bundle_core_version: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord] = None, + regional_compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[dict, str, list[str]]: manifest, manifest_sha256, uri_parts = fetch_release_manifest( manifest_uri, token=token ) require_tagged_layout(manifest, uri_parts, token) + if compatibility_record is not None: + _require_record_binds( + compatibility_record, + "data release", + country=country, + manifest_sha256=manifest_sha256, + build=release_build_id(manifest.build), + ) primary_manifest = manifest regional_manifest = None regional_manifest_sha256 = None @@ -1604,12 +1734,24 @@ def certify( regional_artifacts: dict[str, DataReleaseArtifact] = {} regional_warnings: list[str] = [] regional_certification: Optional[dict] = None + regional_compatibility_basis: Optional[str] = None mismatch_warning: Optional[str] = None if regional_model_mismatch_reason is not None and regional_manifest_uri is None: raise CertificationError( "--accept-regional-model-mismatch applies to a regional release; " "pass --regional-manifest-uri." ) + if regional_compatibility_record is not None: + if regional_manifest_uri is None: + raise CertificationError( + "A regional compatibility record applies to a regional " + "release; pass --regional-manifest-uri." + ) + if regional_model_mismatch_reason is not None: + raise CertificationError( + "A regional compatibility record and an accepted regional " + "model mismatch are two different bases; pass one of them." + ) if regional_manifest_uri is not None: regional_manifest, regional_manifest_sha256, regional_uri_parts = ( fetch_release_manifest(regional_manifest_uri, token=token) @@ -1617,13 +1759,32 @@ def certify( require_tagged_layout(regional_manifest, regional_uri_parts, token) _regional_build_model_version(regional_manifest, model_package) # The regional release runs on the same model and core, so it must - # cover the pinned versions by its own build or claims. A qualified + # cover the pinned versions by its own build or claims, or by a + # compatibility check of exactly this model and core. A qualified # pair names the primary release only, so it does not extend here. try: - _, regional_warnings = model_compatibility_basis( - regional_manifest, model_package, model_version + if regional_compatibility_record is not None: + _require_record_binds( + regional_compatibility_record, + "regional release", + country=country, + manifest_sha256=regional_manifest_sha256, + build=release_build_id(regional_manifest.build), + ) + regional_compatibility_basis, regional_warnings = ( + model_compatibility_basis( + regional_manifest, + model_package, + model_version, + regional_compatibility_record, + core_version=core_version, + ) ) except CertificationError as exc: + if regional_compatibility_record is not None: + raise CertificationError( + f"Regional release {regional_manifest_uri}: {exc}" + ) from exc if regional_model_mismatch_reason is None: raise CertificationError( f"Regional release {regional_manifest_uri}: {exc}" @@ -1647,7 +1808,8 @@ def certify( "certificate does not record a mismatch that is not there." ) try: - if core_version is not None: + # A compatibility record ran exactly this core. + if core_version is not None and regional_compatibility_record is None: _check_core_compatibility( regional_manifest, core_version, None, regional_warnings ) @@ -1681,6 +1843,7 @@ def certify( model_version, core_version=core_version, qualified_pair_id=qualified_pair_id, + compatibility_record=compatibility_record, ) warnings = warnings + regional_warnings if core_version is None and bundle_core_version is not None: @@ -1718,6 +1881,19 @@ def certify( ) model_wheel = fetch_pypi_wheel_metadata(model_package, model_version) + # A record holds only for the wheel the check installed. + for label, record in ( + ("data release", compatibility_record), + ("regional release", regional_compatibility_record), + ): + if record is not None: + _require_record_binds( + record, + label, + model_package=model_package, + model_version=model_version, + wheel_sha256=(model_wheel or {}).get("sha256"), + ) country_payload = build_country_manifest_payload( country=country, manifest=manifest, @@ -1755,6 +1931,11 @@ def certify( regional_release_kind=recorded_release_kind, regional_certification=regional_certification, regional_manifest_sha256=regional_manifest_sha256, + regional_compatibility_basis=( + regional_compatibility_basis + if regional_compatibility_basis == BASIS_COMPATIBILITY_CHECKED + else None + ), ), manifest_sha256, warnings, @@ -1807,6 +1988,9 @@ def certify_data_release( qualified_pair_id: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord | dict] = None, + regional_compatibility_record: Optional[CompatibilityRecord | dict] = None, + records_path: Optional[Path] = None, ) -> CertificationResult: """Certify a data release into the bundle manifest. @@ -1831,8 +2015,36 @@ def certify_data_release( never-modelled column, defaulted input and limitation is recorded in ``regional_certification`` alongside the reason and both model versions. The core must still be covered; area receipts remain uncertified. + + ``compatibility_record`` and ``regional_compatibility_record`` + (``bundle.py check-compatibility``) certify the data release or the + regional release on the basis ``compatibility_checked_exact_pair``: each + must name the fetched manifest's SHA-256 and build, the model version, the + SHA-256 of the wheel PyPI lists for it, and the core. ``core_version`` + defaults to the records' core. Certification replaces the country's + records file (``records_path``, by default + ``data/compatibility/.json`` beside the bundle's ``bundle`` + folder) with the records it used, and removes it when it used none. """ certified_country = _certified_country(country) + compatibility_record = _as_compatibility_record( + compatibility_record, "data release's record" + ) + regional_compatibility_record = _as_compatibility_record( + regional_compatibility_record, "regional release's record" + ) + records = [ + record + for record in (compatibility_record, regional_compatibility_record) + if record is not None + ] + record_cores = sorted({record.core_version for record in records}) + if len(record_cores) > 1: + raise CertificationError( + f"The compatibility records name different cores: {record_cores}." + ) + if core_version is None and record_cores: + core_version = record_cores[0] if ( regional_input_surface_evidence is not None and regional_model_mismatch_reason is None @@ -1886,6 +2098,8 @@ def certify_data_release( ).get("version"), regional_model_mismatch_reason=regional_model_mismatch_reason, regional_input_surface_evidence=regional_input_surface_evidence, + compatibility_record=compatibility_record, + regional_compatibility_record=regional_compatibility_record, ) previous_release = (bundle.get("data_releases") or {}).get(country) or {} bundle.setdefault("data_releases", {})[country] = data_release @@ -1924,6 +2138,11 @@ def certify_data_release( if core_version is not None and "policyengine-core" in bundle.get("packages", {}): bundle["packages"]["policyengine-core"]["version"] = core_version bundle_path.write_text(json.dumps(bundle, indent=2, sort_keys=True) + "\n") + write_compatibility_records( + records_path or compatibility_records_path(bundle_path.parent.parent, country), + country, + records, + ) return CertificationResult( country=country, diff --git a/src/policyengine/provenance/compatibility_check.py b/src/policyengine/provenance/compatibility_check.py new file mode 100644 index 00000000..442aa17a --- /dev/null +++ b/src/policyengine/provenance/compatibility_check.py @@ -0,0 +1,569 @@ +"""Check one Microcosm data build against one model version. + +``scripts/bundle.py check-compatibility`` runs this for one build, UK or US. +The check passes only when all of these hold: + +1. The build's manifest passes the metadata checks ``certify-data`` makes + before it downloads anything: a pinned, listed build in its own release + folder, a recorded build model and core, and a SHA-256 for every + microdata H5 file. +2. Each H5 file, downloaded and verified against the manifest's SHA-256, + stores no column its build model defines and the new model does not. + The build model is read in a throwaway ``uv run`` environment as the + regional input audit reads it (``regional_input_surface``); the new model + in the probe's environment. +3. A 2,000-household sample of each file, drawn as + ``compatibility_probe.sample_household_ids`` describes, loads and runs + through .py under exactly the new model wheel (verified against PyPI's + SHA-256) and core, and every headline variable has a finite, positive + weighted total. + +A pass returns a ``CompatibilityRecord``, which ``certify-data +--compatibility-record`` turns into a certificate on the basis +``compatibility_checked_exact_pair``. +""" + +from __future__ import annotations + +import json +import math +import os +import subprocess +from collections.abc import Callable, Iterable +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Optional + +import requests + +from policyengine.provenance.certification import ( + COUNTRY_MODEL_PACKAGES, + CertificationError, + default_bundle_source_path, + fetch_release_manifest, + require_tagged_layout, +) +from policyengine.provenance.compatibility_probe import ( + SAMPLE_HOUSEHOLDS, + SAMPLE_METHOD, + SAMPLE_SALT, +) +from policyengine.provenance.compatibility_record import ( + CompatibilityArtifactCheck, + CompatibilityModelPackage, + CompatibilityRecord, + CompatibilitySample, +) +from policyengine.provenance.manifest import ( + HF_REQUEST_TIMEOUT_SECONDS, + DataReleaseArtifact, + RegionalInputArtifactEvidence, + fetch_pypi_wheel_metadata, + https_dataset_uri, + release_build_id, +) +from policyengine.provenance.regional_input_surface import ( + BUILD_MODEL_INDEX, + BUILD_MODEL_KEPT_UV_SETTINGS, + BUILD_MODEL_PYTHON, + RegionalInputSurfaceError, + _build_model_surface, + _sha256_file, + _stored_columns, + compare_input_surface, + regional_build_cutoff, +) + +#: The variables whose sample totals must be finite and positive. +HEADLINE_VARIABLES: dict[str, tuple[str, ...]] = { + "uk": ( + "household_net_income", + "income_tax", + "universal_credit", + "child_benefit", + "state_pension", + "pension_credit", + "housing_benefit", + ), + "us": ( + "household_net_income", + "income_tax", + "snap", + "ssi", + "social_security", + ), +} +PROBE_MODULE = "policyengine.provenance.compatibility_probe" +#: The checkout this module was imported from, which the probe installs. +REPO_ROOT = Path(__file__).resolve().parents[3] +DOWNLOAD_CHUNK_BYTES = 1024 * 1024 + +Download = Callable[[str, Path, dict[str, str]], None] + + +class CompatibilityCheckError(ValueError): + """The build does not pass the check against the model version.""" + + +def total_problems(totals: dict[str, Any], variables: Iterable[str]) -> list[str]: + """Describe each headline total that is missing, not finite or not positive.""" + problems = [] + for variable in variables: + if variable not in totals: + problems.append(f"{variable}: no total") + continue + value = totals[variable] + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + ): + problems.append(f"{variable}: {value!r} is not finite") + elif value <= 0: + problems.append(f"{variable}: {value} is not positive") + return problems + + +def probe_command( + *, + policyengine_source: Path, + wheel_path: Path, + core_version: str, + extra_requirements: Iterable[str], + request_path: Path, +) -> list[str]: + """Run the probe with exactly this .py checkout, model wheel and core. + + As for the build model, ``--isolated --no-project --no-config`` gives a + fresh environment that ignores the caller's project and uv settings, and + PyPI is the only index. + """ + extras = [ + argument + for requirement in extra_requirements + for argument in ("--with", requirement) + ] + return [ + "uv", + "run", + "--isolated", + "--no-project", + "--no-config", + "--default-index", + BUILD_MODEL_INDEX, + "--python", + BUILD_MODEL_PYTHON, + "--with", + str(policyengine_source), + "--with", + str(wheel_path), + "--with", + f"policyengine-core=={core_version}", + *extras, + "python", + "-I", + "-m", + PROBE_MODULE, + str(request_path), + ] + + +def probe_environment(environ: Optional[dict[str, str]] = None) -> dict[str, str]: + """The probe's environment: no tokens, no .py settings, no uv overrides. + + The probe reads only local files, so Hugging Face tokens are removed. + ``POLICYENGINE_*`` settings are removed so the caller's configuration + cannot steer the run, and ``POLICYENGINE_SKIP_COUNTRY_IMPORTS`` is set + so importing .py builds no model before the certificate lookup is + replaced. + """ + source = os.environ if environ is None else environ + environment = { + key: value + for key, value in source.items() + if key != "VIRTUAL_ENV" + and not key.startswith(("HF_", "HUGGING", "POLICYENGINE_")) + and (not key.startswith("UV_") or key in BUILD_MODEL_KEPT_UV_SETTINGS) + } + environment["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] = "1" + return environment + + +def download_file(url: str, destination: Path, headers: dict[str, str]) -> None: + """Stream ``url`` to ``destination``, replacing it only when complete.""" + destination.parent.mkdir(parents=True, exist_ok=True) + partial = destination.with_name(f"{destination.name}.partial") + try: + with requests.get( + url, headers=headers, stream=True, timeout=HF_REQUEST_TIMEOUT_SECONDS + ) as response: + if response.status_code != 200: + raise CompatibilityCheckError( + f"Could not download {url} ({response.status_code})." + ) + with partial.open("wb") as file: + for chunk in response.iter_content(chunk_size=DOWNLOAD_CHUNK_BYTES): + file.write(chunk) + except requests.RequestException as exc: + raise CompatibilityCheckError(f"Could not download {url}.") from exc + partial.replace(destination) + + +def _download_verified( + download: Download, + url: str, + destination: Path, + headers: dict[str, str], + expected_sha256: str, + label: str, +) -> None: + """Download unless a verified copy is already there; refuse other bytes.""" + if destination.is_file() and _sha256_file(destination) == expected_sha256: + return + download(url, destination, headers) + actual = _sha256_file(destination) + if actual != expected_sha256: + raise CompatibilityCheckError( + f"{label}: the downloaded bytes have SHA-256 {actual}, not " + f"{expected_sha256}." + ) + + +def _microdata_artifacts(artifacts: dict[str, DataReleaseArtifact]): + microdata = { + name: artifact + for name, artifact in sorted(artifacts.items()) + if artifact.kind == "microdata" and Path(artifact.path).suffix.lower() == ".h5" + } + if not microdata: + raise CompatibilityCheckError("The build lists no microdata H5 file.") + unpinned = sorted( + name + for name, artifact in microdata.items() + if not artifact.sha256 or not artifact.revision + ) + if unpinned: + raise CompatibilityCheckError( + f"Microdata files {unpinned} have no sha256 or revision in the " + "manifest, so their bytes cannot be verified." + ) + return microdata + + +def _run_probe( + run: Callable[..., Any], command: list[str], label: str, result_path: Path +) -> dict[str, Any]: + try: + run( + command, + capture_output=True, + text=True, + check=True, + env=probe_environment(), + ) + except subprocess.CalledProcessError as exc: + detail = " | ".join((exc.stderr or "").strip().splitlines()[-5:]) + raise CompatibilityCheckError( + f"The sample run under {label} failed: {detail or exc}" + ) from exc + except OSError as exc: + raise CompatibilityCheckError( + f"Cannot run uv for the sample run under {label}." + ) from exc + try: + result = json.loads(result_path.read_text()) + except (OSError, ValueError) as exc: + raise CompatibilityCheckError( + f"The sample run under {label} wrote no result." + ) from exc + if not isinstance(result, dict): + raise CompatibilityCheckError(f"The sample run under {label} wrote no result.") + return result + + +def check_build_compatibility( + *, + country: str, + manifest_uri: str, + model_version: str, + work_dir: Path, + core_version: Optional[str] = None, + token: Optional[str] = None, + policyengine_source: Optional[Path] = None, + bundle_path: Optional[Path] = None, + run: Optional[Callable[..., Any]] = None, + download: Optional[Download] = None, + now: Optional[datetime] = None, +) -> CompatibilityRecord: + """Check one build against one model version; return the record of a pass. + + ``core_version`` defaults to the bundle's policyengine-core pin. Files go + under ``work_dir``; a file already there with the manifest's SHA-256 is + not downloaded again. ``run`` (``subprocess.run``) runs uv and + ``download`` (``download_file``) fetches the wheel and H5 files. + Raises ``CompatibilityCheckError`` with the reason when the build does + not pass. + """ + if country not in COUNTRY_MODEL_PACKAGES: + raise CompatibilityCheckError(f"Unknown country {country!r}.") + model_package = COUNTRY_MODEL_PACKAGES[country] # type: ignore[index] + run = run if run is not None else subprocess.run + download = download if download is not None else download_file + work_dir = Path(work_dir) + work_dir.mkdir(parents=True, exist_ok=True) + policyengine_source = Path(policyengine_source or REPO_ROOT) + bundle = json.loads(Path(bundle_path or default_bundle_source_path()).read_text()) + packages = bundle.get("packages") or {} + + # 1. Metadata, before any download. + try: + manifest, manifest_sha256, parts = fetch_release_manifest( + manifest_uri, token=token + ) + require_tagged_layout(manifest, parts, token) + except CertificationError as exc: + raise CompatibilityCheckError(str(exc)) from exc + build = manifest.build + build_model = build.built_with_model_package if build is not None else None + build_core = build.built_with_core_package if build is not None else None + if build is None or build_model is None or build_core is None: + raise CompatibilityCheckError( + "The build's manifest records no build model and core " + "(built_with_model_package and built_with_core_package), so there " + "is nothing to compare the new model with." + ) + if build_model.name != model_package: + raise CompatibilityCheckError( + f"The build was built with {build_model.name}, not {model_package}." + ) + if build_model.version == model_version: + raise CompatibilityCheckError( + f"The build was built with {model_package} {model_version}; it is " + "certified on that basis and needs no compatibility check." + ) + build_id = release_build_id(build) + if not build_id: + raise CompatibilityCheckError("The build's manifest names no build.") + microdata = _microdata_artifacts(manifest.artifacts) + core_version = core_version or (packages.get("policyengine-core") or {}).get( + "version" + ) + if not core_version: + raise CompatibilityCheckError( + "No policyengine-core version: pass --core-version or pin the core " + "in the bundle." + ) + extra_requirements = [] + spm_version = (packages.get("spm-calculator") or {}).get("version") + if country == "us" and spm_version: + extra_requirements.append(f"spm-calculator=={spm_version}") + label = f"{model_package} {model_version} with policyengine-core {core_version}" + + # 2. The exact model wheel, as PyPI lists it. + wheel = fetch_pypi_wheel_metadata(model_package, model_version) + wheel_sha256, wheel_url = wheel.get("sha256"), wheel.get("url") + if not wheel_sha256 or not wheel_url or not wheel_url.endswith(".whl"): + raise CompatibilityCheckError( + f"PyPI lists no wheel for {model_package} {model_version}." + ) + wheel_path = work_dir / "wheels" / wheel_url.rsplit("/", 1)[1] + _download_verified( + download, + wheel_url, + wheel_path, + {}, + wheel_sha256, + f"The {model_package} {model_version} wheel", + ) + + # 3. Each H5 file, verified against the manifest. + headers = {"Authorization": f"Bearer {token}"} if token else {} + files: dict[str, Path] = {} + for name, artifact in microdata.items(): + assert artifact.revision is not None and artifact.sha256 is not None + url = https_dataset_uri( + artifact.repo_id, + artifact.path, + artifact.revision, + repo_type=artifact.repo_type or parts["repo_type"], + ) + destination = work_dir / "data" / name / Path(artifact.path).name + _download_verified(download, url, destination, headers, artifact.sha256, name) + files[name] = destination + + # 4. The columns each file stores, and the build model's variables. + evidence: dict[str, RegionalInputArtifactEvidence] = {} + years: dict[str, int] = {} + for name, path in files.items(): + artifact = microdata[name] + try: + periods = _stored_columns(path, model_package) + except RegionalInputSurfaceError as exc: + raise CompatibilityCheckError(f"{name}: {exc}") from exc + evidence[name] = RegionalInputArtifactEvidence( + repo_id=artifact.repo_id, + repo_type=artifact.repo_type or parts["repo_type"], + path=artifact.path, + revision=artifact.revision, + sha256=artifact.sha256, + columns=sorted( + {column for columns in periods.values() for column in columns} + ), + columns_by_period=periods, + ) + years[name] = int(min(periods)) + try: + build_variables, build_inputs = _build_model_surface( + build_model.version, + build_core.version, + run=run, + exclude_newer=regional_build_cutoff(manifest) if build.built_at else None, + model_package=model_package, + ) + except RegionalInputSurfaceError as exc: + raise CompatibilityCheckError(str(exc)) from exc + + # 5. The sample run under the new model. + request_path = work_dir / "probe_request.json" + result_path = work_dir / "probe_result.json" + result_path.unlink(missing_ok=True) + headline = list(HEADLINE_VARIABLES[country]) + request_path.write_text( + json.dumps( + { + "country": country, + "model_package": model_package, + "model_version": model_version, + "core_version": core_version, + "headline_variables": headline, + "sample_size": SAMPLE_HOUSEHOLDS, + "artifacts": { + name: {"path": str(path), "year": years[name]} + for name, path in files.items() + }, + "data_folder": str(work_dir / "datasets"), + "result_path": str(result_path), + }, + indent=2, + ) + ) + result = _run_probe( + run, + probe_command( + policyengine_source=policyengine_source, + wheel_path=wheel_path, + core_version=core_version, + extra_requirements=extra_requirements, + request_path=request_path, + ), + label, + result_path, + ) + resolved = (result.get("model_version"), result.get("core_version")) + if resolved != (model_version, core_version): + raise CompatibilityCheckError( + f"The sample run used {model_package} {resolved[0]} with " + f"policyengine-core {resolved[1]}, not {label}." + ) + + # 6. Columns the new model would not read. + variables = result.get("variables") + inputs = result.get("inputs") + aliases = result.get("input_aliases") or {} + if ( + not isinstance(variables, list) + or not isinstance(inputs, list) + or not isinstance(aliases, dict) + ): + raise CompatibilityCheckError( + f"The sample run under {label} reported no variable lists." + ) + try: + comparison = compare_input_surface( + evidence, + variables, + inputs, + aliases, + build_model_variables=build_variables, + build_model_inputs=build_inputs, + model_package=model_package, + ) + except RegionalInputSurfaceError as exc: + raise CompatibilityCheckError(str(exc)) from exc + if comparison["dropped_columns"]: + raise CompatibilityCheckError( + f"The build stores columns {model_package} {build_model.version} " + f"defines and {model_version} does not, so {model_version} would " + f"not read them: {comparison['dropped_columns']}." + ) + + # 7. The sample and its totals. + reported = result.get("artifacts") + if not isinstance(reported, dict) or set(reported) != set(files): + raise CompatibilityCheckError( + f"The sample run under {label} reported files " + f"{sorted(reported or {})}, not {sorted(files)}." + ) + problems: list[str] = [] + checks: dict[str, CompatibilityArtifactCheck] = {} + for name, path in files.items(): + entry = reported[name] + households = entry.get("households") + sample_households = entry.get("sample_households") + expected_sample = ( + min(SAMPLE_HOUSEHOLDS, households) + if isinstance(households, int) and households > 0 + else None + ) + if expected_sample is None or sample_households != expected_sample: + problems.append( + f"{name}: the sample holds {sample_households} of {households} " + f"households, not {expected_sample}" + ) + continue + totals = entry.get("totals") or {} + artifact_problems = total_problems(totals, headline) + if artifact_problems: + problems.extend(f"{name}: {problem}" for problem in artifact_problems) + continue + artifact = microdata[name] + checks[name] = CompatibilityArtifactCheck( + path=artifact.path, + revision=artifact.revision, + sha256=artifact.sha256, + year=years[name], + households=households, + sample_households=sample_households, + sample_household_ids_sha256=entry.get("sample_household_ids_sha256"), + totals={variable: float(totals[variable]) for variable in headline}, + ) + if problems: + raise CompatibilityCheckError( + f"The sample run under {label} did not pass: {'; '.join(problems)}." + ) + + return CompatibilityRecord( + country=country, # type: ignore[arg-type] + manifest_uri=manifest_uri, + manifest_sha256=manifest_sha256, + release=manifest.release, + build=build_id, + built_with_model_version=build_model.version, + built_with_core_version=build_core.version, + model_package=CompatibilityModelPackage( + name=model_package, + version=model_version, + wheel_sha256=wheel_sha256, + wheel_url=wheel_url, + ), + core_version=core_version, + policyengine_version=result.get("policyengine_version") or "", + sample=CompatibilitySample( + method=SAMPLE_METHOD, salt=SAMPLE_SALT, size=SAMPLE_HOUSEHOLDS + ), + headline_variables=headline, + artifacts=checks, + never_modelled_columns=comparison["never_modelled_columns"], + defaulted_inputs=comparison["defaulted_inputs"], + checked_at=(now or datetime.now(UTC)).strftime("%Y-%m-%dT%H:%M:%SZ"), + ) diff --git a/src/policyengine/provenance/compatibility_probe.py b/src/policyengine/provenance/compatibility_probe.py new file mode 100644 index 00000000..5b93380f --- /dev/null +++ b/src/policyengine/provenance/compatibility_probe.py @@ -0,0 +1,248 @@ +"""Run a compatibility check's sample in a throwaway environment. + +``compatibility_check`` starts this module with ``uv run`` in an environment +holding exactly the model wheel, the core and this checkout of .py. It +reads one request JSON (``python -m policyengine.provenance.compatibility_probe +request.json``) and writes the result to the request's ``result_path``: + +- the installed model's variables, inputs and input aliases, read as the + regional input audit reads them; +- for each H5 file, its household count, the sampled households' digest and + the weighted totals of the headline variables over the sample. + +The sample is loaded and simulated through .py, as a user's run would be. +The model-version constructor asks for the bundle's data certificate, which +names another model while the check runs; inside this process only that +lookup is replaced (``replace_certificate_lookup``). + +Importing this module loads no country model, so the parent process uses its +sampling functions too. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import numbers +import sys +from collections.abc import Callable, Iterable +from importlib import metadata +from pathlib import Path +from typing import Any, Final, Optional, Union + +SAMPLE_HOUSEHOLDS = 2000 +SAMPLE_METHOD: Final = "sha256_rank_v1" +SAMPLE_SALT = "policyengine-compatibility-sample-v1" +#: The basis of the placeholder certificate the probe's model is built with. +CHECK_IN_PROGRESS_BASIS = "compatibility_check_in_progress" + + +class CompatibilityProbeError(ValueError): + """The probe cannot report a complete result for its request.""" + + +def installed_version(package: str) -> str: + return metadata.version(package) + + +def canonical_household_id(value: Any) -> str: + """Write a household ID as the decimal integer it holds.""" + if isinstance(value, bool): + raise ValueError(f"Household ID {value!r} is not a whole number.") + if isinstance(value, numbers.Integral): + return str(int(value)) + if isinstance(value, numbers.Real): + as_float = float(value) + if math.isfinite(as_float) and as_float.is_integer(): + return str(int(as_float)) + raise ValueError(f"Household ID {value!r} is not a whole number.") + + +def _sample_rank(canonical_id: str) -> str: + return hashlib.sha256(f"{SAMPLE_SALT}:{canonical_id}".encode()).hexdigest() + + +def sample_household_ids( + household_ids: Iterable[Any], size: int = SAMPLE_HOUSEHOLDS +) -> list[int]: + """Draw the check's sample: the ``size`` households ranked lowest. + + Each ID is written as a decimal integer and ranked by the SHA-256 hex + digest of ``"policyengine-compatibility-sample-v1:"``. The draw + depends only on the IDs, not their order, and keeps every household when + there are ``size`` or fewer. Returns the IDs as sorted integers. + """ + canonical = [canonical_household_id(value) for value in household_ids] + if len(set(canonical)) != len(canonical): + raise ValueError("Household IDs repeat; the sample needs unique IDs.") + ranked = sorted( + canonical, key=lambda canonical_id: (_sample_rank(canonical_id), canonical_id) + ) + return sorted(int(canonical_id) for canonical_id in ranked[:size]) + + +def household_ids_sha256(household_ids: Iterable[Any]) -> str: + """SHA-256 of the IDs as sorted decimal integers, one per line.""" + ordered = sorted(int(canonical_household_id(value)) for value in household_ids) + return hashlib.sha256( + "\n".join(str(value) for value in ordered).encode() + ).hexdigest() + + +def replace_certificate_lookup() -> None: + """Build this process's model versions without the bundle certificate. + + ``MicrosimulationModelVersion.__init__`` asks + ``certify_data_release_compatibility`` whether the bundle's data is + certified for the installed model. While a check runs it is not; the + check itself is what may certify it. Only that lookup is replaced, and + only in this process. + """ + from policyengine.provenance.manifest import DataCertification + from policyengine.tax_benefit_models.common import model_version + + def lookup( + country_id: str, + runtime_model_version: str, + runtime_data_build_fingerprint: Optional[str] = None, + runtime_core_version: Optional[str] = None, + ) -> DataCertification: + return DataCertification( + compatibility_basis=CHECK_IN_PROGRESS_BASIS, + certified_for_model_version=runtime_model_version, + ) + + model_version.certify_data_release_compatibility = lookup + + +def weighted_totals( + output_dataset: Any, variable_entities: dict[str, str] +) -> dict[str, float]: + """Sum each variable over its entity's rows, weighted by ``_weight``.""" + import pandas as pd + + totals = {} + for variable, entity in variable_entities.items(): + frame = pd.DataFrame(getattr(output_dataset.data, entity)) + values = frame[variable].astype(float) + weights = frame[f"{entity}_weight"].astype(float) + totals[variable] = float((values * weights).sum()) + return totals + + +def _load_country(country: str) -> tuple[Callable[..., Any], Any]: + import importlib + + replace_certificate_lookup() + module = importlib.import_module(f"policyengine.tax_benefit_models.{country}") + return module.create_datasets, module.model + + +def _model_surface(model_version: str, model_package: str): + from policyengine.provenance.regional_input_surface import _model_surface + + return _model_surface(model_version, model_package=model_package) + + +def _simulate( + dataset: Any, + model: Any, + household_ids: list[int], + variables_by_entity: dict[str, list[str]], +) -> Any: + from policyengine.core import Simulation + from policyengine.core.scoping_strategy import RowFilterStrategy + + filter_values: list[Union[str, int, float]] = list(household_ids) + simulation = Simulation( + dataset=dataset, + tax_benefit_model_version=model, + scoping_strategy=RowFilterStrategy( + variable_name="household_id", variable_value=filter_values + ), + extra_variables=variables_by_entity, + ) + simulation.run() + return simulation.output_dataset + + +def run_probe( + request: dict[str, Any], + *, + load_country: Optional[Callable[[str], tuple[Callable[..., Any], Any]]] = None, + model_surface: Optional[Callable[[str, str], tuple[list, list, dict]]] = None, + simulate: Optional[Callable[..., Any]] = None, +) -> dict[str, Any]: + """Load and simulate each file's sample under the installed model.""" + load_country = load_country or _load_country + model_surface = model_surface or _model_surface + simulate = simulate or _simulate + model_package = request["model_package"] + for package, requested in ( + (model_package, request["model_version"]), + ("policyengine-core", request["core_version"]), + ): + installed = installed_version(package) + if installed != requested: + raise CompatibilityProbeError( + f"The probe environment holds {package} {installed}, not {requested}." + ) + variables, inputs, aliases = model_surface(request["model_version"], model_package) + create_datasets, model = load_country(request["country"]) + headline = list(request["headline_variables"]) + variable_entities = { + variable: model.get_variable(variable).entity for variable in headline + } + variables_by_entity: dict[str, list[str]] = {} + for variable, entity in variable_entities.items(): + variables_by_entity.setdefault(entity, []).append(variable) + artifacts = {} + for name, artifact in request["artifacts"].items(): + created = create_datasets( + datasets=[artifact["path"]], + years=[int(artifact["year"])], + data_folder=str(Path(request["data_folder"]) / name), + allow_unmanaged=True, + ) + if len(created) != 1: + raise CompatibilityProbeError( + f"{name}: .py created {len(created)} datasets, not one." + ) + (dataset,) = created.values() + household_ids = dataset.data.household["household_id"].tolist() + sample = sample_household_ids(household_ids, request["sample_size"]) + output = simulate(dataset, model, sample, variables_by_entity) + artifacts[name] = { + "households": len(household_ids), + "sample_households": len(sample), + "sample_household_ids_sha256": household_ids_sha256(sample), + "totals": weighted_totals(output, variable_entities), + } + return { + "model_version": installed_version(model_package), + "core_version": installed_version("policyengine-core"), + "policyengine_version": installed_version("policyengine"), + "variables": variables, + "inputs": inputs, + "input_aliases": aliases, + "artifacts": artifacts, + } + + +def main(argv: Optional[list[str]] = None) -> int: + arguments = sys.argv[1:] if argv is None else argv + if len(arguments) != 1: + print( + "usage: python -m policyengine.provenance.compatibility_probe REQUEST", + file=sys.stderr, + ) + return 2 + request = json.loads(Path(arguments[0]).read_text()) + result = run_probe(request) + Path(request["result_path"]).write_text(json.dumps(result)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/policyengine/provenance/compatibility_record.py b/src/policyengine/provenance/compatibility_record.py new file mode 100644 index 00000000..7bfa7299 --- /dev/null +++ b/src/policyengine/provenance/compatibility_record.py @@ -0,0 +1,215 @@ +"""Records of a compatibility check of one data build against one model version. + +``scripts/bundle.py check-compatibility`` writes a record when one build +passes: its H5 files store no column its build model defined that the new +model does not, and a 2,000-household sample runs under the new model with +positive totals for the headline variables. ``certify-data`` certifies that +exact build, model wheel and core on the basis +``compatibility_checked_exact_pair`` and stores the record in +``data/compatibility/.json``; a model loads such a certificate only +when that file holds a matching record. + +A record names the build by the SHA-256 of its raw ``release_manifest.json`` +and the model by the SHA-256 of its PyPI wheel. This module imports nothing +from the rest of ``policyengine.provenance``, so certification and the +runtime check can both import it. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable +from importlib.resources import files +from pathlib import Path +from typing import Callable, Final, Literal, Optional + +from pydantic import BaseModel, Field + +BASIS_COMPATIBILITY_CHECKED: Final = "compatibility_checked_exact_pair" +COMPATIBILITY_RECORDS_SCHEMA_VERSION: Final = 1 +SHA256_PATTERN = r"^[0-9a-f]{64}$" + + +class CompatibilityModelPackage(BaseModel): + """The exact model wheel the check installed.""" + + model_config = {"extra": "forbid"} + + name: str = Field(min_length=1) + version: str = Field(min_length=1) + wheel_sha256: str = Field(pattern=SHA256_PATTERN) + wheel_url: str = Field(min_length=1) + + +class CompatibilitySample(BaseModel): + """How the check drew its households. + + ``sha256_rank_v1``: each household ID is written as a decimal integer, + ranked by the SHA-256 hex digest of ``f"{salt}:{id}"``, and the ``size`` + lowest-ranked households are kept (all of them when a file has fewer). + """ + + model_config = {"extra": "forbid"} + + method: Literal["sha256_rank_v1"] + salt: str = Field(min_length=1) + size: int = Field(gt=0) + + +class CompatibilityArtifactCheck(BaseModel): + """One H5 file of the build, as the check read and ran it.""" + + model_config = {"extra": "forbid"} + + path: str = Field(min_length=1) + revision: str = Field(min_length=1) + sha256: str = Field(pattern=SHA256_PATTERN) + year: int + households: int = Field(gt=0) + sample_households: int = Field(gt=0) + sample_household_ids_sha256: str = Field(pattern=SHA256_PATTERN) + """SHA-256 of the sampled household IDs, sorted, one decimal per line.""" + totals: dict[str, float] = Field(min_length=1) + """Weighted totals of the headline variables over the sample, using the + file's own weights (not scaled up to the whole file).""" + + +class CompatibilityRecord(BaseModel): + """A passed check of one build against one model wheel and core.""" + + model_config = {"extra": "forbid"} + + schema_version: Literal[1] = 1 + compatibility_basis: Literal["compatibility_checked_exact_pair"] = ( + BASIS_COMPATIBILITY_CHECKED + ) + country: Literal["uk", "us"] + manifest_uri: str = Field(min_length=1) + manifest_sha256: str = Field(pattern=SHA256_PATTERN) + """SHA-256 of the raw ``release_manifest.json`` bytes.""" + release: Optional[str] = None + build: str = Field(min_length=1) + built_with_model_version: str = Field(min_length=1) + built_with_core_version: str = Field(min_length=1) + model_package: CompatibilityModelPackage + core_version: str = Field(min_length=1) + policyengine_version: str = Field(min_length=1) + """The .py version that ran the sample.""" + sample: CompatibilitySample + headline_variables: list[str] = Field(min_length=1) + artifacts: dict[str, CompatibilityArtifactCheck] = Field(min_length=1) + never_modelled_columns: list[str] + """Stored columns neither model defines; no model reads them.""" + defaulted_inputs: list[str] + """Inputs of the new model the files do not store and the build model + did not have; runs on the build use their defaults.""" + checked_at: str = Field(min_length=1) + + +class CompatibilityRecords(BaseModel): + """The records one country's certificates rest on.""" + + model_config = {"extra": "forbid"} + + schema_version: Literal[1] = COMPATIBILITY_RECORDS_SCHEMA_VERSION + country: Literal["uk", "us"] + records: list[CompatibilityRecord] = Field(default_factory=list) + + +#: The value of each field a record can be matched on. +RECORD_BINDINGS: dict[str, Callable[[CompatibilityRecord], str]] = { + "country": lambda record: record.country, + "manifest_sha256": lambda record: record.manifest_sha256, + "build": lambda record: record.build, + "model_package": lambda record: record.model_package.name, + "model_version": lambda record: record.model_package.version, + "wheel_sha256": lambda record: record.model_package.wheel_sha256, + "core_version": lambda record: record.core_version, +} + + +def compatibility_records_path(data_dir: Path, country: str) -> Path: + """Return the records file for ``country`` under a package data folder.""" + return Path(data_dir) / "compatibility" / f"{country}.json" + + +def read_compatibility_records(path: Path, country: str) -> list[CompatibilityRecord]: + """Read a country's records file; a missing file holds no records.""" + path = Path(path) + if not path.exists(): + return [] + stored = CompatibilityRecords.model_validate_json(path.read_bytes()) + if stored.country != country: + raise ValueError(f"{path} holds {stored.country} records, not {country}.") + for record in stored.records: + if record.country != country: + raise ValueError( + f"{path} holds a {record.country} record among {country} records." + ) + return list(stored.records) + + +def write_compatibility_records( + path: Path, country: str, records: Iterable[CompatibilityRecord] +) -> None: + """Replace a country's records file; with no records, remove it.""" + path = Path(path) + records = list(records) + if not records: + path.unlink(missing_ok=True) + return + stored = CompatibilityRecords.model_validate( + {"country": country, "records": records} + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(stored.model_dump(mode="json"), indent=2, sort_keys=True) + "\n" + ) + + +def bundled_compatibility_records(country: str) -> list[CompatibilityRecord]: + """Read the records installed with this package for ``country``.""" + resource = files("policyengine").joinpath( + "data", "compatibility", f"{country}.json" + ) + if not resource.is_file(): + return [] + stored = CompatibilityRecords.model_validate_json(resource.read_bytes()) + if stored.country != country or any( + record.country != country for record in stored.records + ): + raise ValueError( + f"The installed compatibility records for {country} name another country." + ) + return list(stored.records) + + +def compatibility_record_problems( + record: CompatibilityRecord, **expected: Optional[str] +) -> list[str]: + """Describe each named field on which ``record`` differs from ``expected``. + + Fields are those of ``RECORD_BINDINGS``. An expected value of ``None`` + is a problem too: there is nothing to compare the record with. + """ + problems = [] + for field, value in expected.items(): + try: + recorded = RECORD_BINDINGS[field](record) + except KeyError as exc: + raise TypeError(f"Records are not matched on {field!r}.") from exc + if value is None: + problems.append(f"{field}: nothing to compare the record's {recorded} with") + elif recorded != value: + problems.append(f"{field}: the record names {recorded}, not {value}") + return problems + + +def matching_compatibility_record( + records: Iterable[CompatibilityRecord], **expected: Optional[str] +) -> Optional[CompatibilityRecord]: + """Return the first record that matches every expected field, if any.""" + for record in records: + if not compatibility_record_problems(record, **expected): + return record + return None diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index 9b3aa382..d905f2a3 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -22,6 +22,12 @@ shadowed_dataset_overlays, shadowing_overlays_message, ) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + bundled_compatibility_records, + compatibility_record_problems, + matching_compatibility_record, +) HF_REQUEST_TIMEOUT_SECONDS = 30 PYPI_REQUEST_TIMEOUT_SECONDS = 30 @@ -338,8 +344,19 @@ class DataCertification(BaseModel): { "legacy_compatible_model_package", "qualified_exact_pair", + BASIS_COMPATIBILITY_CHECKED, "legacy_compatible_model_package_local_manifest", "qualified_exact_pair_local_manifest", + f"{BASIS_COMPATIBILITY_CHECKED}_local_manifest", + } +) +#: Bases that hold for one model, one core and one data build only. +EXACT_PAIR_COMPATIBILITY = frozenset( + { + "qualified_exact_pair", + "qualified_exact_pair_local_manifest", + BASIS_COMPATIBILITY_CHECKED, + f"{BASIS_COMPATIBILITY_CHECKED}_local_manifest", } ) @@ -455,6 +472,10 @@ class CountryReleaseManifest(BaseModel): model mismatch rather than its own build or claims.""" regional_source_manifest_sha256: Optional[str] = None """SHA-256 of the original regional release manifest bytes.""" + regional_compatibility_basis: Optional[str] = None + """``compatibility_checked_exact_pair`` when the regional release serves + the certified model and core on a compatibility check's record, which + ``data/compatibility/.json`` must hold; otherwise absent.""" certified_data_artifact: Optional[CertifiedDataArtifact] = None certification: Optional[DataCertification] = None source_sha256: Optional[str] = Field(default=None, exclude=True) @@ -1111,14 +1132,12 @@ def _runtime_core_is_certified( ) -> bool: """Whether the running core is the one an exact-pair certificate tested. - Other bases make no claim about the core at run time. An exact pair was - tested with one core, so it holds only for that core. + Other bases make no claim about the core at run time. An exact pair (a + qualified pair, or a compatibility check's record) was tested with one + core, so it holds only for that core. """ - if certification.compatibility_basis not in { - "qualified_exact_pair", - "qualified_exact_pair_local_manifest", - }: + if certification.compatibility_basis not in EXACT_PAIR_COMPATIBILITY: return True if runtime_core_version is None: from importlib import metadata @@ -1130,6 +1149,60 @@ def _runtime_core_is_certified( return certification.certified_for_core_version == runtime_core_version +def _compatibility_record_gaps( + country_id: str, + country_manifest: CountryReleaseManifest, + **expected: Optional[str], +) -> list[str]: + """Why no installed compatibility record covers ``expected``; empty if one does. + + Every record must also be for this country, the bundle's model package + and the SHA-256 of the wheel the bundle pins. + """ + records = bundled_compatibility_records(country_id) + expected = { + "country": country_id, + "model_package": country_manifest.model_package.name, + "wheel_sha256": country_manifest.model_package.sha256, + **expected, + } + if matching_compatibility_record(records, **expected) is not None: + return [] + if not records: + return ["the installed package holds no compatibility record"] + return [ + f"the record of build {record.build} differs (" + f"{', '.join(compatibility_record_problems(record, **expected))})" + for record in records + ] + + +def _require_regional_compatibility_record( + country_id: str, country_manifest: CountryReleaseManifest +) -> None: + """Refuse a bundle that routes regions on a record the package lacks.""" + if country_manifest.regional_compatibility_basis != BASIS_COMPATIBILITY_CHECKED: + return + certification = country_manifest.certification + gaps = ( + ["the bundle has no certificate"] + if certification is None + else _compatibility_record_gaps( + country_id, + country_manifest, + manifest_sha256=country_manifest.regional_source_manifest_sha256, + model_version=certification.certified_for_model_version, + core_version=certification.certified_for_core_version, + ) + ) + if gaps: + raise ValueError( + f"The bundle serves country '{country_id}''s regional release on a " + "compatibility check whose record is not installed: " + f"{'; '.join(gaps)}." + ) + + def certify_data_release_compatibility( country_id: str, runtime_model_version: str, @@ -1137,6 +1210,7 @@ def certify_data_release_compatibility( runtime_core_version: Optional[str] = None, ) -> DataCertification: country_manifest = get_release_manifest(country_id) + _require_regional_compatibility_record(country_id, country_manifest) try: data_release_manifest = get_data_release_manifest(country_id) except DataReleaseManifestUnavailableError as exc: @@ -1154,12 +1228,25 @@ def certify_data_release_compatibility( "Runtime data build fingerprint does not match the bundled " "data certification." ) + # Without the manifest, a compatibility check's certificate holds + # only with its record for the certified build, model and core. if ( bundled_certification.certified_for_model_version == runtime_model_version and _runtime_core_is_certified( bundled_certification, runtime_core_version ) + and ( + bundled_certification.compatibility_basis + != BASIS_COMPATIBILITY_CHECKED + or not _compatibility_record_gaps( + country_id, + country_manifest, + build=bundled_certification.data_build_id, + model_version=runtime_model_version, + core_version=bundled_certification.certified_for_core_version, + ) + ) ): return bundled_certification return DataCertification( @@ -1237,6 +1324,43 @@ def _certify_available_data_release( f"build {remote_build_id} in country '{country_id}'; the exact " f"pair requires {bundled_certification.data_build_id}." ) + # A compatibility check ran one build, model wheel and core; nothing else + # the remote manifest says can stand in for its record. + if ( + bundled_certification is not None + and bundled_certification.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + ): + gaps = [] + if bundled_certification.certified_for_model_version != runtime_model_version: + gaps.append( + f"the check ran {bundled_certification.certified_for_model_version}" + ) + if not _runtime_core_is_certified(bundled_certification, runtime_core_version): + gaps.append( + "the check ran policyengine-core " + f"{bundled_certification.certified_for_core_version}" + ) + if bundled_certification.data_build_id != remote_build_id: + gaps.append( + f"the check ran build {bundled_certification.data_build_id}, " + f"not {remote_build_id}" + ) + if not gaps: + gaps = _compatibility_record_gaps( + country_id, + country_manifest, + manifest_sha256=data_release_manifest.source_sha256, + build=remote_build_id, + model_version=runtime_model_version, + core_version=bundled_certification.certified_for_core_version, + ) + if gaps: + raise ValueError( + "Data release manifest is not certified for the runtime model " + f"version {runtime_model_version} in country '{country_id}' on " + f"its compatibility check: {'; '.join(gaps)}." + ) + return bundled_certification built_with_model = ( data_release_manifest.build.built_with_model_package if data_release_manifest.build is not None From ec9142a6d227c15b2476e1a39b6599bb003d9937 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:03:53 +0400 Subject: [PATCH 03/25] Add failing tests for round 1 review findings - The probe installs the checkout editable, so uv cannot run an earlier cached build of it. - A malformed probe result refuses with a reason instead of raising a validation or attribute error. - A regional release's compatibility record holds only for the installed core, whatever the national build's basis. Co-Authored-By: Claude Opus 5.5 --- tests/test_compatibility_certification.py | 20 ++++++++++ tests/test_compatibility_check.py | 46 ++++++++++++++++++++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/tests/test_compatibility_certification.py b/tests/test_compatibility_certification.py index 2010b1e6..b33c6bed 100644 --- a/tests/test_compatibility_certification.py +++ b/tests/test_compatibility_certification.py @@ -689,6 +689,26 @@ def test__given_regional_basis_without_record__then_refuses(self): regional_sha256=DENSE_MANIFEST_SHA256, ) + @pytest.mark.parametrize("online", [True, False]) + def test__given_regional_record_under_another_installed_core__then_refuses( + self, online + ): + """The national build's own basis makes no claim about the core, but + the regional release's record holds only for the core it ran.""" + + with pytest.raises(ValueError, match="regional"): + self._load( + _certificate( + compatibility_basis="built_with_model_package", + built_with_model_version=TARGET_MODEL, + ), + remote=self._remote(built_with=TARGET_MODEL) if online else None, + records=[_dense_record()], + core=OTHER_CORE, + regional_basis=BASIS_COMPATIBILITY_CHECKED, + regional_sha256=DENSE_MANIFEST_SHA256, + ) + def test__exact_pair_names_its_core(self): assert BASIS_COMPATIBILITY_CHECKED in CLAIM_BASED_COMPATIBILITY assert f"{BASIS_COMPATIBILITY_CHECKED}_local_manifest" in ( diff --git a/tests/test_compatibility_check.py b/tests/test_compatibility_check.py index 6555d4a7..1036e13e 100644 --- a/tests/test_compatibility_check.py +++ b/tests/test_compatibility_check.py @@ -420,13 +420,20 @@ def test__given_pins__then_installs_exactly_them_from_pypi_in_isolation( "--default-index", ] assert command[6] == "https://pypi.org/simple" + # The checkout is installed editable, so the run imports its current + # source rather than a wheel uv built from it earlier and cached. + editable = [ + command[index + 1] + for index, argument in enumerate(command) + if argument == "--with-editable" + ] + assert editable == [str(tmp_path / "checkout")] requirements = [ command[index + 1] for index, argument in enumerate(command) if argument == "--with" ] assert requirements == [ - str(tmp_path / "checkout"), str(tmp_path / "policyengine_uk-2.180.0-py3-none-any.whl"), f"policyengine-core=={CORE_VERSION}", "spm-calculator==1.1.0", @@ -619,6 +626,43 @@ def test__given_sample_smaller_than_expected__then_refuses( with pytest.raises(CompatibilityCheckError, match="sample"): _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + @pytest.mark.parametrize( + ("change", "reason"), + [ + ("no_policyengine_version", "policyengine_version"), + ("entry_not_a_mapping", UK_DATASET), + ("no_sample_digest", "sample_household_ids_sha256"), + ], + ) + def test__given_malformed_probe_result__then_refuses_with_a_reason( + self, tmp_path, monkeypatch, change, reason + ): + result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": dict(UK_TOTALS), + } + }, + } + if change == "no_policyengine_version": + del result["policyengine_version"] + elif change == "entry_not_a_mapping": + result["artifacts"][UK_DATASET] = "not a mapping" + else: + del result["artifacts"][UK_DATASET]["sample_household_ids_sha256"] + + with pytest.raises(CompatibilityCheckError, match=reason): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + def test__given_core_version__then_runs_that_core(self, tmp_path, monkeypatch): uv = FakeUv( target_variables=[*TARGET_VARIABLES, DROPPED_COLUMN], From d9e34571f7e73ca1a1e49c2d062032e4f392cc45 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:09:11 +0400 Subject: [PATCH 04/25] Fix round 1 review findings in the compatibility check - Install the .py checkout editable in the probe environment, so the run imports the checkout's current source rather than a wheel uv cached. - Refuse a probe result with no policyengine_version, a file entry that is not a mapping, or no SHA-256 of the sampled household IDs, with a CompatibilityCheckError naming the field. - Match the regional release's compatibility record against the running model and the installed core, not the national certificate's. - Docs: the fingerprint basis is a planned further basis; the module docstring names the tagged-layout check and the missing built_at case. Co-Authored-By: Claude Opus 5.5 --- docs/release-bundles.md | 7 ++- .../provenance/compatibility_check.py | 49 +++++++++++++---- src/policyengine/provenance/manifest.py | 54 ++++++++++++------- 3 files changed, 76 insertions(+), 34 deletions(-) diff --git a/docs/release-bundles.md b/docs/release-bundles.md index d46c623d..2b063fd7 100644 --- a/docs/release-bundles.md +++ b/docs/release-bundles.md @@ -640,7 +640,6 @@ Things that should usually not affect the fingerprint: (`compatibility_basis: legacy_compatible_model_package` — the publisher's claim, recorded with a warning and made good by the test suite passing on the pinned pair) - 3. a compatibility check of exactly this build, model wheel and core passed (`compatibility_basis: compatibility_checked_exact_pair`). `python scripts/bundle.py check-compatibility` runs it from a checkout, for one @@ -658,9 +657,9 @@ Things that should usually not affect the fingerprint: If none is true, certification fails hard and a new data build, a published compatibility claim or a passed compatibility check is required. A -`data_build_fingerprint` -basis (same fingerprint as the build-time model) is a planned third -basis; it requires fingerprint metadata from the installed model package. +`data_build_fingerprint` basis (same fingerprint as the build-time model) +is planned as a further basis; it requires fingerprint metadata from the +installed model package. ## Artifact states diff --git a/src/policyengine/provenance/compatibility_check.py b/src/policyengine/provenance/compatibility_check.py index 442aa17a..07dbf748 100644 --- a/src/policyengine/provenance/compatibility_check.py +++ b/src/policyengine/provenance/compatibility_check.py @@ -4,9 +4,8 @@ The check passes only when all of these hold: 1. The build's manifest passes the metadata checks ``certify-data`` makes - before it downloads anything: a pinned, listed build in its own release - folder, a recorded build model and core, and a SHA-256 for every - microdata H5 file. + before it downloads anything: the tagged-layout check, a recorded build + model and core, and a SHA-256 for every microdata H5 file. 2. Each H5 file, downloaded and verified against the manifest's SHA-256, stores no column its build model defines and the new model does not. The build model is read in a throwaway ``uv run`` environment as the @@ -28,6 +27,7 @@ import json import math import os +import re import subprocess from collections.abc import Callable, Iterable from datetime import UTC, datetime @@ -49,6 +49,7 @@ SAMPLE_SALT, ) from policyengine.provenance.compatibility_record import ( + SHA256_PATTERN, CompatibilityArtifactCheck, CompatibilityModelPackage, CompatibilityRecord, @@ -136,7 +137,9 @@ def probe_command( As for the build model, ``--isolated --no-project --no-config`` gives a fresh environment that ignores the caller's project and uv settings, and - PyPI is the only index. + PyPI is the only index. The checkout is installed editable, so the probe + imports the checkout's current source; uv caches a wheel it builds from + a plain directory and could reuse it after the source changes. """ extras = [ argument @@ -153,7 +156,7 @@ def probe_command( BUILD_MODEL_INDEX, "--python", BUILD_MODEL_PYTHON, - "--with", + "--with-editable", str(policyengine_source), "--with", str(wheel_path), @@ -412,6 +415,9 @@ def check_build_compatibility( columns_by_period=periods, ) years[name] = int(min(periods)) + # A build that records no ``built_at`` is read without ``--exclude-newer``, + # so the build model's dependencies resolve to their newest compatible + # releases rather than those available when the build was made. try: build_variables, build_inputs = _build_model_surface( build_model.version, @@ -498,6 +504,11 @@ def check_build_compatibility( ) # 7. The sample and its totals. + policyengine_version = result.get("policyengine_version") + if not isinstance(policyengine_version, str) or not policyengine_version: + raise CompatibilityCheckError( + f"The sample run under {label} reported no policyengine_version." + ) reported = result.get("artifacts") if not isinstance(reported, dict) or set(reported) != set(files): raise CompatibilityCheckError( @@ -508,6 +519,9 @@ def check_build_compatibility( checks: dict[str, CompatibilityArtifactCheck] = {} for name, path in files.items(): entry = reported[name] + if not isinstance(entry, dict): + problems.append(f"{name}: the run reported {entry!r}, not a mapping") + continue households = entry.get("households") sample_households = entry.get("sample_households") expected_sample = ( @@ -515,13 +529,28 @@ def check_build_compatibility( if isinstance(households, int) and households > 0 else None ) - if expected_sample is None or sample_households != expected_sample: + if ( + not isinstance(households, int) + or expected_sample is None + or sample_households != expected_sample + ): problems.append( f"{name}: the sample holds {sample_households} of {households} " f"households, not {expected_sample}" ) continue - totals = entry.get("totals") or {} + totals = entry.get("totals") + if not isinstance(totals, dict): + totals = {} + sample_digest = entry.get("sample_household_ids_sha256") + if not isinstance(sample_digest, str) or not re.fullmatch( + SHA256_PATTERN, sample_digest + ): + problems.append( + f"{name}: sample_household_ids_sha256 is {sample_digest!r}, " + "not a SHA-256" + ) + continue artifact_problems = total_problems(totals, headline) if artifact_problems: problems.extend(f"{name}: {problem}" for problem in artifact_problems) @@ -533,8 +562,8 @@ def check_build_compatibility( sha256=artifact.sha256, year=years[name], households=households, - sample_households=sample_households, - sample_household_ids_sha256=entry.get("sample_household_ids_sha256"), + sample_households=expected_sample, + sample_household_ids_sha256=sample_digest, totals={variable: float(totals[variable]) for variable in headline}, ) if problems: @@ -557,7 +586,7 @@ def check_build_compatibility( wheel_url=wheel_url, ), core_version=core_version, - policyengine_version=result.get("policyengine_version") or "", + policyengine_version=policyengine_version, sample=CompatibilitySample( method=SAMPLE_METHOD, salt=SAMPLE_SALT, size=SAMPLE_HOUSEHOLDS ), diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index d905f2a3..4be08d76 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -1127,6 +1127,19 @@ def _specifier_matches(version: str, specifier: str) -> bool: return False +def _installed_core_version(runtime_core_version: Optional[str]) -> Optional[str]: + """The running core: the one given, else the installed one, else ``None``.""" + + if runtime_core_version is not None: + return runtime_core_version + from importlib import metadata + + try: + return metadata.version("policyengine-core") + except metadata.PackageNotFoundError: + return None + + def _runtime_core_is_certified( certification: DataCertification, runtime_core_version: Optional[str] ) -> bool: @@ -1139,13 +1152,9 @@ def _runtime_core_is_certified( if certification.compatibility_basis not in EXACT_PAIR_COMPATIBILITY: return True + runtime_core_version = _installed_core_version(runtime_core_version) if runtime_core_version is None: - from importlib import metadata - - try: - runtime_core_version = metadata.version("policyengine-core") - except metadata.PackageNotFoundError: - return False + return False return certification.certified_for_core_version == runtime_core_version @@ -1178,22 +1187,25 @@ def _compatibility_record_gaps( def _require_regional_compatibility_record( - country_id: str, country_manifest: CountryReleaseManifest + country_id: str, + country_manifest: CountryReleaseManifest, + runtime_model_version: str, + runtime_core_version: Optional[str], ) -> None: - """Refuse a bundle that routes regions on a record the package lacks.""" + """Refuse a regional release on a record that does not cover this run. + + The record was checked with one model and one core, so it must name the + running model and the running core, as the national certificate's + record must. + """ if country_manifest.regional_compatibility_basis != BASIS_COMPATIBILITY_CHECKED: return - certification = country_manifest.certification - gaps = ( - ["the bundle has no certificate"] - if certification is None - else _compatibility_record_gaps( - country_id, - country_manifest, - manifest_sha256=country_manifest.regional_source_manifest_sha256, - model_version=certification.certified_for_model_version, - core_version=certification.certified_for_core_version, - ) + gaps = _compatibility_record_gaps( + country_id, + country_manifest, + manifest_sha256=country_manifest.regional_source_manifest_sha256, + model_version=runtime_model_version, + core_version=_installed_core_version(runtime_core_version), ) if gaps: raise ValueError( @@ -1210,7 +1222,9 @@ def certify_data_release_compatibility( runtime_core_version: Optional[str] = None, ) -> DataCertification: country_manifest = get_release_manifest(country_id) - _require_regional_compatibility_record(country_id, country_manifest) + _require_regional_compatibility_record( + country_id, country_manifest, runtime_model_version, runtime_core_version + ) try: data_release_manifest = get_data_release_manifest(country_id) except DataReleaseManifestUnavailableError as exc: From 19791dc7b746ea5b2c8e43d4a683867182884d04 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:27:43 +0400 Subject: [PATCH 05/25] Add a failing test for the round 2 review finding check-compatibility must import .py without building the installed country models, whose bundle certificate need not cover the installed model version. Co-Authored-By: Claude Opus 5.5 --- tests/test_compatibility_certification.py | 40 +++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/test_compatibility_certification.py b/tests/test_compatibility_certification.py index b33c6bed..dba85c71 100644 --- a/tests/test_compatibility_certification.py +++ b/tests/test_compatibility_certification.py @@ -9,6 +9,7 @@ import importlib.util import json +import os import sys from pathlib import Path from types import ModuleType @@ -817,6 +818,45 @@ def check(**kwargs): _record() ) + def test__given_check_compatibility__then_skips_country_model_imports( + self, monkeypatch, tmp_path + ): + """Importing .py must not build the installed country models: their + bundle certificate need not cover the installed model version.""" + + # setenv first, so teardown removes the value the script sets. + monkeypatch.setenv("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "unset by the test") + monkeypatch.delenv("POLICYENGINE_SKIP_COUNTRY_IMPORTS") + bundle_script = _load_script(monkeypatch, "bundle") + skip_values = [] + + def check(**kwargs): + skip_values.append(os.environ.get("POLICYENGINE_SKIP_COUNTRY_IMPORTS")) + return _record() + + monkeypatch.setattr( + "policyengine.provenance.compatibility_check.check_build_compatibility", + check, + ) + + bundle_script.main( + [ + "check-compatibility", + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--model-version", + TARGET_MODEL, + "--work-dir", + str(tmp_path / "work"), + "--output", + str(tmp_path / "record.json"), + ] + ) + + assert skip_values == ["1"] + def test__given_certify_data_records__then_forwards_them(self, monkeypatch): bundle_script = _load_script(monkeypatch, "bundle") captured: dict[str, list[str]] = {} From 37d9480514ebbd9e0f46ec3c0f207d849d256d20 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:29:04 +0400 Subject: [PATCH 06/25] Fix the round 2 review finding and document the check - check-compatibility sets POLICYENGINE_SKIP_COUNTRY_IMPORTS before it imports .py, as the TRO commands do, so importing .py does not build the installed country models and check their bundle certificate. - The regional refusal says no installed record covers the running model and core, which also covers an installed record for another model or core. - The data-certification guide describes check-compatibility and certify-data --compatibility-record, and that a record binds its core. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/data-certification.md | 49 +++++++++++++++++-- scripts/bundle.py | 4 ++ src/policyengine/provenance/manifest.py | 4 +- 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/docs/engineering/skills/data-certification.md b/docs/engineering/skills/data-certification.md index 545b1aad..02b11b85 100644 --- a/docs/engineering/skills/data-certification.md +++ b/docs/engineering/skills/data-certification.md @@ -266,10 +266,52 @@ Microcosm national release with one of: `src/policyengine/data/schemas/execution_receipt.v1.schema.json`. Either way, certification checks that the regional release serves the pinned -model by its own build or compatibility claims (a `--qualified-pair-id` names -the primary release only), checks its core claims as for the primary release +model by its own build, its compatibility claims or a +`--regional-compatibility-record` (a `--qualified-pair-id` names the primary +release only), checks its core claims as for the primary release (below), and HEAD-checks every artifact it carries. +### Certifying a build for a newer model with a compatibility check + +A build can be certified for a model version it was not built with, and that +no publisher claim covers, by checking it against that version: + +```bash +python scripts/bundle.py check-compatibility --country uk \ + --manifest-uri "hf://dataset/@/releases///release_manifest.json" \ + --model-version \ + --work-dir --output +``` + +Run it from a checkout of this repository, with a Hugging Face token that can +read the build in `HUGGING_FACE_TOKEN` or `HF_TOKEN`. One run checks one +build, UK or US. It refuses a build whose model is the version given (certify +that on `built_with_model_package`), downloads the model's PyPI wheel and each +microdata H5 file and checks their SHA-256s, refuses a file that stores a +column the build's model defines and the given version does not, and runs a +2,000-household sample of each file through .py under exactly that wheel and +core (the bundle's pin, or `--core-version`). Every headline variable must +have a finite, positive weighted total. A pass writes a record to `--output` +that names the build by the SHA-256 of its `release_manifest.json` and the +model by its wheel's SHA-256. + +Certify with the record (`--regional-compatibility-record` for the regional +release): + +```bash +python scripts/bundle.py certify-data --country uk --data-producer populace \ + --manifest-uri "" --model-version \ + --compatibility-record +``` + +The basis is `compatibility_checked_exact_pair`. The certificate names the +core, and certification stores the record in +`src/policyengine/data/compatibility/.json`; commit that file with +the bundle. Certification refuses a record for other manifest bytes, another +build, model, wheel or core, and a record given with `--qualified-pair-id`. At +load, a model accepts the certificate only when that file holds a matching +record for the running model and core. + ### The core The bundle has one core pin, `packages.policyengine-core`, shared by every @@ -287,7 +329,8 @@ country. A certificate says how it covers it: core (`certified_for_core_version`). Certification refuses a core that a release neither was built with nor claims, and the strict check refuses a pin that differs from the named core, so moving the core needs a - re-certification first. A qualified exact pair always binds its core. + re-certification first. A qualified exact pair and a compatibility check's + record always bind their core. Use the default unless a release must not run on any other core. diff --git a/scripts/bundle.py b/scripts/bundle.py index 40bac21f..5c2bd551 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -80,6 +80,10 @@ def _certify_data(args: argparse.Namespace) -> int: def _check_compatibility(args: argparse.Namespace) -> int: """Check one build against one model version; write the record of a pass.""" + # Building the installed country models at import would check the + # bundle's certificate against the installed model version, which the + # check does not use and the bundle need not cover. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") from policyengine.provenance import compatibility_check if not (REPO_ROOT / "pyproject.toml").is_file(): diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index 4be08d76..b26263f0 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -1210,8 +1210,8 @@ def _require_regional_compatibility_record( if gaps: raise ValueError( f"The bundle serves country '{country_id}''s regional release on a " - "compatibility check whose record is not installed: " - f"{'; '.join(gaps)}." + "compatibility check, and no installed record covers it with this " + f"model and core: {'; '.join(gaps)}." ) From ba498b5c5b8046f9c6e0150a24e9cc85e2b05b07 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:48:55 +0400 Subject: [PATCH 07/25] Type the pinned microdata files and correct the core guidance From the round 3 review's code-quality notes: - _microdata_artifacts returns each file with the revision and SHA-256 it is pinned to, so mypy checks them where the record and the input-column evidence take them. - The data-certification guide says a regional record names its core instead of the core claims check, and that a qualified pair or a compatibility check's record admits a core no release claims. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/data-certification.md | 6 ++- .../provenance/compatibility_check.py | 40 +++++++++++++------ 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/docs/engineering/skills/data-certification.md b/docs/engineering/skills/data-certification.md index 02b11b85..9bec3d47 100644 --- a/docs/engineering/skills/data-certification.md +++ b/docs/engineering/skills/data-certification.md @@ -269,7 +269,8 @@ Either way, certification checks that the regional release serves the pinned model by its own build, its compatibility claims or a `--regional-compatibility-record` (a `--qualified-pair-id` names the primary release only), checks its core claims as for the primary release -(below), and HEAD-checks every artifact it carries. +(below; a `--regional-compatibility-record` names the core it ran instead), +and HEAD-checks every artifact it carries. ### Certifying a build for a newer model with a compatibility check @@ -327,7 +328,8 @@ country. A certificate says how it covers it: the release's claim; the warning, the certificate and its TRO say so. - **`core_binding: certified` (`--core-version`).** The certificate names the core (`certified_for_core_version`). Certification refuses a core that a - release neither was built with nor claims, and the strict check refuses a + release neither was built with nor claims, unless a qualified exact pair or + a compatibility check's record ran it, and the strict check refuses a pin that differs from the named core, so moving the core needs a re-certification first. A qualified exact pair and a compatibility check's record always bind their core. diff --git a/src/policyengine/provenance/compatibility_check.py b/src/policyengine/provenance/compatibility_check.py index 07dbf748..7fdc7511 100644 --- a/src/policyengine/provenance/compatibility_check.py +++ b/src/policyengine/provenance/compatibility_check.py @@ -32,7 +32,7 @@ from collections.abc import Callable, Iterable from datetime import UTC, datetime from pathlib import Path -from typing import Any, Optional +from typing import Any, NamedTuple, Optional import requests @@ -106,6 +106,15 @@ class CompatibilityCheckError(ValueError): """The build does not pass the check against the model version.""" +class PinnedArtifact(NamedTuple): + """A microdata file of the build with the revision and SHA-256 it is + pinned to.""" + + artifact: DataReleaseArtifact + revision: str + sha256: str + + def total_problems(totals: dict[str, Any], variables: Iterable[str]) -> list[str]: """Describe each headline total that is missing, not finite or not positive.""" problems = [] @@ -232,7 +241,10 @@ def _download_verified( ) -def _microdata_artifacts(artifacts: dict[str, DataReleaseArtifact]): +def _microdata_artifacts( + artifacts: dict[str, DataReleaseArtifact], +) -> dict[str, PinnedArtifact]: + """The build's microdata H5 files; each must name a revision and SHA-256.""" microdata = { name: artifact for name, artifact in sorted(artifacts.items()) @@ -250,7 +262,10 @@ def _microdata_artifacts(artifacts: dict[str, DataReleaseArtifact]): f"Microdata files {unpinned} have no sha256 or revision in the " "manifest, so their bytes cannot be verified." ) - return microdata + return { + name: PinnedArtifact(artifact, artifact.revision or "", artifact.sha256 or "") + for name, artifact in microdata.items() + } def _run_probe( @@ -382,23 +397,22 @@ def check_build_compatibility( # 3. Each H5 file, verified against the manifest. headers = {"Authorization": f"Bearer {token}"} if token else {} files: dict[str, Path] = {} - for name, artifact in microdata.items(): - assert artifact.revision is not None and artifact.sha256 is not None + for name, (artifact, revision, sha256) in microdata.items(): url = https_dataset_uri( artifact.repo_id, artifact.path, - artifact.revision, + revision, repo_type=artifact.repo_type or parts["repo_type"], ) destination = work_dir / "data" / name / Path(artifact.path).name - _download_verified(download, url, destination, headers, artifact.sha256, name) + _download_verified(download, url, destination, headers, sha256, name) files[name] = destination # 4. The columns each file stores, and the build model's variables. evidence: dict[str, RegionalInputArtifactEvidence] = {} years: dict[str, int] = {} for name, path in files.items(): - artifact = microdata[name] + artifact, revision, sha256 = microdata[name] try: periods = _stored_columns(path, model_package) except RegionalInputSurfaceError as exc: @@ -407,8 +421,8 @@ def check_build_compatibility( repo_id=artifact.repo_id, repo_type=artifact.repo_type or parts["repo_type"], path=artifact.path, - revision=artifact.revision, - sha256=artifact.sha256, + revision=revision, + sha256=sha256, columns=sorted( {column for columns in periods.values() for column in columns} ), @@ -555,11 +569,11 @@ def check_build_compatibility( if artifact_problems: problems.extend(f"{name}: {problem}" for problem in artifact_problems) continue - artifact = microdata[name] + artifact, revision, sha256 = microdata[name] checks[name] = CompatibilityArtifactCheck( path=artifact.path, - revision=artifact.revision, - sha256=artifact.sha256, + revision=revision, + sha256=sha256, year=years[name], households=households, sample_households=expected_sample, From 0be343d12e78ae6721124205aa8d6f6e7a13205c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:49:25 +0400 Subject: [PATCH 08/25] Add the changelog fragment for #788 Co-Authored-By: Claude Opus 5.5 --- changelog.d/788.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/788.added.md diff --git a/changelog.d/788.added.md b/changelog.d/788.added.md new file mode 100644 index 00000000..44e3a4de --- /dev/null +++ b/changelog.d/788.added.md @@ -0,0 +1 @@ +`python scripts/bundle.py check-compatibility` checks one UK or US Microcosm build against one model version, from a checkout. It runs `certify-data`'s metadata checks, downloads the model's PyPI wheel and each microdata H5 file and checks their SHA-256s, refuses a file that stores a column the build's model defines and the new model does not, and runs a deterministic 2,000-household sample of each file through .py under exactly that wheel and core, requiring finite, positive weighted totals for the headline variables. A pass writes a record naming the build by the SHA-256 of its `release_manifest.json` and the model by its wheel's SHA-256. `certify-data --compatibility-record` (and `--regional-compatibility-record`) certifies on it with the new basis `compatibility_checked_exact_pair` and stores the record in `src/policyengine/data/compatibility/.json`; a model accepts such a certificate at load only when that file holds a matching record for the running model, wheel and core. From 060288b5619883cc02d25238c8314a405d1e583c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:52:46 +0400 Subject: [PATCH 09/25] Add failing tests for certifying a Microcosm build by name Tests for a `bundle.py certify-build` command that certifies a build of either country, named by release and build: it reads each build at the commit that published it, runs the compatibility check, certifies, and regenerates the lock and provenance files on a new branch or in place. Co-Authored-By: Claude Opus 5.5 --- tests/test_certify_build.py | 903 ++++++++++++++++++++++++++++++++++++ 1 file changed, 903 insertions(+) create mode 100644 tests/test_certify_build.py diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py new file mode 100644 index 00000000..b2daf264 --- /dev/null +++ b/tests/test_certify_build.py @@ -0,0 +1,903 @@ +"""``scripts/bundle.py certify-build``: one certification command for a +Microcosm build of either country, named by release and build.""" + +from __future__ import annotations + +import importlib.util +import json +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "certify_build.py" +BUNDLE = json.loads((ROOT / "src/policyengine/data/bundle/manifest.json").read_text()) + +COMMIT_A = "a" * 40 +COMMIT_B = "b" * 40 +COMMIT_C = "c" * 40 +RELEASES = { + "us": ("microcosm-us-2024-national", "microcosm-us-2024-local"), + "uk": ("microcosm-uk-2024-25-national", "microcosm-uk-2024-25-dense"), +} +REPOS = {"us": "policyengine/populace-us", "uk": "policyengine/populace-uk-private"} +MODEL_PACKAGES = {"us": "policyengine-us", "uk": "policyengine-uk"} + + +def load_script(module_name: str, script: Path): + """Load a script as a module, registered so its dataclasses resolve.""" + spec = importlib.util.spec_from_file_location(module_name, script) + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def certify_build(): + assert SCRIPT.exists(), "scripts/certify_build.py is missing" + return load_script("certify_build_under_test", SCRIPT) + + +@pytest.fixture(scope="module") +def bundle_script(): + return load_script("bundle_script_under_test", ROOT / "scripts" / "bundle.py") + + +# --- A Hub that answers from memory ------------------------------------------ + + +class HubAnswer: + def __init__(self, status_code=200, payload=None, content=None, next_url=None): + self.status_code = status_code + self._payload = payload + if content is None and payload is not None: + content = json.dumps(payload).encode() + self.content = content or b"" + self.links = {"next": {"url": next_url}} if next_url else {} + + def json(self): + return self._payload + + +def releases_record(release, build, *, withdrawn=False, current=None): + return { + "schema_version": 1, + "default": release, + "releases": { + release: { + "role": "national", + "current": current + if current is not None + else (None if withdrawn else build), + "builds": { + build: { + "published_at": "2026-12-01T00:00:00Z", + "withdrawn": withdrawn, + } + }, + } + }, + } + + +def folder_manifest(release, build, *, model="2.200.0", core="3.36.1"): + return { + "schema_version": 1, + "data_package": {"name": "microcosm-data", "version": "0.1.0"}, + "release": release, + "build": build, + "built_at": "2026-12-01T00:00:00Z", + "built_with_model_package": {"name": "policyengine-uk", "version": model}, + "built_with_core_package": {"name": "policyengine-core", "version": core}, + "artifacts": {}, + } + + +class FakeHubSession: + """Answers the Hub's file, paths-info, commit and tree requests.""" + + def __init__(self, repo): + self.repo = repo + self.files = {} + self.records = {} + self.last_commits = {} + self.history_pages = [[]] + self.sizes = {} + + def add_build( + self, release, build, commit, *, model="2.200.0", size=1000, manifest=None + ): + path = f"releases/{release}/{build}/release_manifest.json" + self.files[(path, commit)] = manifest or folder_manifest( + release, build, model=model + ) + self.last_commits[path] = commit + self.sizes[(f"releases/{release}/{build}", commit)] = size + + def get(self, url, headers=None, timeout=None): + hub = "https://huggingface.co" + resolve = f"{hub}/datasets/{self.repo}/resolve/" + commits = f"{hub}/api/datasets/{self.repo}/commits/main" + tree = f"{hub}/api/datasets/{self.repo}/tree/" + if url.startswith(resolve): + revision, path = url.removeprefix(resolve).split("/", 1) + if path == "releases.json" and revision == "main": + return HubAnswer(content=json.dumps(self.records).encode()) + payload = self.files.get((path, revision)) + return HubAnswer(404) if payload is None else HubAnswer(payload=payload) + if url.startswith(commits): + page = int(url.split("p=", 1)[1]) if "p=" in url else 0 + next_url = ( + f"{commits}?p={page + 1}" + if page + 1 < len(self.history_pages) + else None + ) + entries = [{"id": commit} for commit in self.history_pages[page]] + return HubAnswer(payload=entries, next_url=next_url) + if url.startswith(tree): + revision, folder = url.removeprefix(tree).split("/", 1) + size = self.sizes.get((folder, revision), 0) + return HubAnswer( + payload=[{"type": "file", "path": f"{folder}/x.h5", "size": size}] + ) + return HubAnswer(404) + + def post(self, url, headers=None, timeout=None, data=None): + path = data["paths"] + commit = self.last_commits.get(path) + entries = ( + [] if commit is None else [{"path": path, "lastCommit": {"id": commit}}] + ) + return HubAnswer(payload=entries) + + +def hub_for(certify_build, country, *, national_build="nat-b1", local_build="loc-b1"): + national_release, local_release = RELEASES[country] + session = FakeHubSession(REPOS[country]) + record = releases_record(national_release, national_build) + record["releases"].update(releases_record(local_release, local_build)["releases"]) + session.records = record + session.add_build(national_release, national_build, COMMIT_A) + session.add_build(local_release, local_build, COMMIT_B, model="2.199.0") + return certify_build.Hub(token=None, session=session), session + + +# --- bundle.py and the arguments --------------------------------------------- + + +def test_bundle_hands_certify_build_to_its_own_parser(bundle_script, capsys): + with pytest.raises(SystemExit) as raised: + bundle_script.main(["certify-build", "--help"]) + + assert raised.value.code == 0 + help_text = capsys.readouterr().out + for option in ( + "--national-build", + "--national-release", + "--local-area-build", + "--local-area-release", + "--keep-regional-release", + "--drop-regional-release", + "--model-version", + "--core-version", + "--in-place", + "--skip-writer-check", + "--co-author", + "--pr-body-footer", + ): + assert option in help_text + + +def test_bundle_help_lists_certify_build(bundle_script, capsys): + with pytest.raises(SystemExit): + bundle_script.main(["--help"]) + + assert "certify-build" in capsys.readouterr().out + + +BASE_ARGUMENTS = ["--country", "uk", "--national-build", "nat-b1"] + + +@pytest.mark.parametrize( + ("extra", "message"), + [ + (["--drop-regional-release", "--open-pr"], "--open-pr needs --push"), + ( + ["--drop-regional-release", "--in-place", "--push"], + "does not go with --in-place", + ), + ( + ["--drop-regional-release", "--national-data-commit", "abc123"], + "full 40-character commit", + ), + (["--local-area-build", "../escape"], "is not a release or build name"), + ( + ["--drop-regional-release", "--local-area-release", "x"], + "go with --local-area-build", + ), + ( + ["--drop-regional-release", "--co-author", "Someone"], + "one line, 'Name '", + ), + ([], "one of the arguments"), + (["--drop-regional-release", "--keep-regional-release"], "not allowed with"), + ], +) +def test_arguments_refuse_incoherent_requests(certify_build, capsys, extra, message): + with pytest.raises(SystemExit) as raised: + certify_build.parse(BASE_ARGUMENTS + extra) + + assert raised.value.code == 2 + assert message in capsys.readouterr().err + + +# --- Reading a build from its folder ----------------------------------------- + + +def test_build_is_pinned_at_the_commit_that_published_its_folder(certify_build): + hub, _ = hub_for(certify_build, "uk") + + build = certify_build.read_published_build( + hub, "uk", "microcosm-uk-2024-25-national", "nat-b1" + ) + + assert build.commit == COMMIT_A + assert (build.model, build.core) == ("2.200.0", "3.36.1") + assert build.folder_bytes == 1000 + assert build.manifest_uri == ( + f"hf://dataset/policyengine/populace-uk-private@{COMMIT_A}" + "/releases/microcosm-uk-2024-25-national/nat-b1/release_manifest.json" + ) + + +def test_build_not_listed_in_releases_json_is_refused(certify_build): + hub, _ = hub_for(certify_build, "uk") + + with pytest.raises(certify_build.CertifyError, match="does not list build other"): + certify_build.read_published_build( + hub, "uk", "microcosm-uk-2024-25-national", "other" + ) + + +def test_withdrawn_build_is_refused(certify_build): + hub, session = hub_for(certify_build, "uk") + session.records = releases_record( + "microcosm-uk-2024-25-national", "nat-b1", withdrawn=True + ) + + with pytest.raises(certify_build.CertifyError, match="withdrawn"): + certify_build.read_published_build( + hub, "uk", "microcosm-uk-2024-25-national", "nat-b1" + ) + + +def test_manifest_naming_another_build_is_refused(certify_build): + hub, session = hub_for(certify_build, "uk") + session.add_build( + "microcosm-uk-2024-25-national", + "nat-b1", + COMMIT_A, + manifest=folder_manifest("microcosm-uk-2024-25-national", "nat-b2"), + ) + + with pytest.raises(certify_build.CertifyError, match="names release"): + certify_build.read_published_build( + hub, "uk", "microcosm-uk-2024-25-national", "nat-b1" + ) + + +def test_manifest_without_its_model_version_is_refused(certify_build): + hub, session = hub_for(certify_build, "uk") + manifest = folder_manifest("microcosm-uk-2024-25-national", "nat-b1") + del manifest["built_with_model_package"] + session.add_build( + "microcosm-uk-2024-25-national", "nat-b1", COMMIT_A, manifest=manifest + ) + + with pytest.raises(certify_build.CertifyError, match="built_with_model_package"): + certify_build.read_published_build( + hub, "uk", "microcosm-uk-2024-25-national", "nat-b1" + ) + + +def test_named_commit_must_be_in_mains_history(certify_build): + hub, session = hub_for(certify_build, "uk") + session.history_pages = [[COMMIT_A], [COMMIT_B]] + + with pytest.raises(certify_build.CertifyError, match="not in main's history"): + certify_build.read_published_build( + hub, "uk", "microcosm-uk-2024-25-national", "nat-b1", commit=COMMIT_C + ) + + +def test_named_commit_on_a_later_page_of_mains_history_is_read(certify_build): + hub, session = hub_for(certify_build, "uk") + session.history_pages = [[COMMIT_A], [COMMIT_C]] + session.files[ + ( + "releases/microcosm-uk-2024-25-national/nat-b1/release_manifest.json", + COMMIT_C, + ) + ] = folder_manifest("microcosm-uk-2024-25-national", "nat-b1") + + build = certify_build.read_published_build( + hub, "uk", "microcosm-uk-2024-25-national", "nat-b1", commit=COMMIT_C + ) + + assert build.commit == COMMIT_C + + +@pytest.mark.parametrize("country", ["us", "uk"]) +def test_release_names_default_to_the_bundles_pinned_releases(certify_build, country): + record = BUNDLE["data_releases"][country] + + national = certify_build.pinned_national(record, REPOS[country]) + local_area = certify_build.pinned_local_area(record, REPOS[country]) + + assert national.release == RELEASES[country][0] + assert local_area.release == RELEASES[country][1] + assert ( + certify_build.default_release(None, national, "--national-release") + == (RELEASES[country][0]) + ) + assert ( + certify_build.default_release("named", national, "--national-release") + == "named" + ) + + +# --- Checks before anything is written --------------------------------------- + + +def fake_listing(monkeypatch, certify_build, pull_requests, branches=""): + def run(argv, **kwargs): + if argv[:3] == ["gh", "pr", "list"]: + return SimpleNamespace( + returncode=0, stdout=json.dumps(pull_requests), stderr="" + ) + if argv[:2] == ["git", "ls-remote"]: + return SimpleNamespace(returncode=0, stdout=branches, stderr="") + raise AssertionError(argv) + + monkeypatch.setattr(certify_build.subprocess, "run", run) + + +def test_writer_check_finds_a_pull_request_for_the_same_build_and_model( + certify_build, monkeypatch, tmp_path +): + fake_listing( + monkeypatch, + certify_build, + [ + { + "number": 1, + "title": "Certify policyengine-uk 2.200.0", + "body": "national `nat-b1`", + "headRefName": "a", + }, + { + "number": 2, + "title": "Certify policyengine-uk 2.201.0", + "body": "national `nat-b1`", + "headRefName": "b", + }, + ], + ) + + found = certify_build.writer_check( + tmp_path, + "certify/uk/nat-b1/policyengine-uk-2.200.0", + "nat-b1", + "policyengine-uk 2.200.0", + ) + + assert len(found) == 1 and found[0].startswith("#1 ") + + +def test_writer_check_finds_the_branch_on_origin(certify_build, monkeypatch, tmp_path): + branch = "certify/uk/nat-b1/policyengine-uk-2.200.0" + fake_listing( + monkeypatch, certify_build, [], branches=f"{COMMIT_A}\trefs/heads/{branch}\n" + ) + + found = certify_build.writer_check( + tmp_path, branch, "nat-b1", "policyengine-uk 2.200.0" + ) + + assert found == [f"branch {branch} exists on origin"] + + +def test_writer_check_refuses_when_pull_requests_cannot_be_listed( + certify_build, monkeypatch, tmp_path +): + monkeypatch.setattr( + certify_build.subprocess, + "run", + lambda argv, **kwargs: SimpleNamespace( + returncode=1, stdout="", stderr="no auth" + ), + ) + + with pytest.raises( + certify_build.CertifyError, match="could not list .py pull requests" + ): + certify_build.writer_check(tmp_path, "b", "nat-b1", "policyengine-uk 2.200.0") + + +def test_free_disk_below_the_builds_size_is_refused( + certify_build, monkeypatch, tmp_path +): + monkeypatch.setattr( + certify_build.shutil, + "disk_usage", + lambda directory: SimpleNamespace(free=2_000_000_000), + ) + + with pytest.raises(certify_build.CertifyError, match="needs 7.0 GB"): + certify_build.check_free_disk(tmp_path / "not-yet", 7_000_000_000) + assert certify_build.check_free_disk(tmp_path, 1_000_000_000) == 2_000_000_000 + + +# --- Files certification changes --------------------------------------------- + + +def git_repository(path: Path) -> Path: + path.mkdir(parents=True, exist_ok=True) + for command in ( + ["git", "init", "-q", "-b", "main"], + ["git", "config", "user.name", "Tester"], + ["git", "config", "user.email", "tester@example.com"], + ): + subprocess.run(command, cwd=path, check=True) + return path + + +def commit_all(path: Path, message: str = "base") -> None: + subprocess.run(["git", "add", "-A"], cwd=path, check=True) + subprocess.run(["git", "commit", "-q", "-m", message], cwd=path, check=True) + + +def test_only_generated_files_are_committed(certify_build, tmp_path): + checkout = git_repository(tmp_path / "py") + for relative in ("pyproject.toml", "README.md", "tests/test_models.py"): + (checkout / relative).parent.mkdir(parents=True, exist_ok=True) + (checkout / relative).write_text("old\n") + commit_all(checkout) + (checkout / "pyproject.toml").write_text("new\n") + (checkout / "tests/test_models.py").write_text("new\n") + (checkout / "changelog.d").mkdir() + (checkout / "changelog.d/certify-uk-nat-b1.changed.md").write_text("x\n") + (checkout / "notes.txt").write_text("operator notes\n") + + assert certify_build.certification_changes(checkout, "uk", "nat-b1") == [ + "changelog.d/certify-uk-nat-b1.changed.md", + "pyproject.toml", + "tests/test_models.py", + ] + + (checkout / "README.md").write_text("changed by hand\n") + with pytest.raises(certify_build.CertifyError, match="README.md"): + certify_build.certification_changes(checkout, "uk", "nat-b1") + + +def record_for(build, revision, model, built_with): + return { + "certification": { + "data_build_id": build, + "built_with_model_version": built_with, + }, + "data_package": {"release_manifest_revision": revision, "version": "0.1.0"}, + "model_package": {"version": model}, + } + + +def test_constants_move_to_the_new_builds_and_model(certify_build, tmp_path): + old = record_for("nat-old", COMMIT_A, "2.199.0", "2.199.0") + new = record_for("nat-new", COMMIT_C, "2.200.0", "2.200.0") + old_local = certify_build.BuildPin("loc", "loc-old", COMMIT_B) + new_local = certify_build.BuildPin("loc", "loc-new", "d" * 40) + (tmp_path / "tests").mkdir() + (tmp_path / "tests/test_models.py").write_text( + f'NATIONAL = "nat-old"\nREVISION = "{COMMIT_A}"\nMODEL = "2.199.0"\n' + f'LOCAL = "releases/loc/loc-old/x"\nLOCAL_COMMIT = "@{COMMIT_B}"\n' + "UNQUOTED = nat-old\n" + ) + + changed = certify_build.rewrite_constants( + tmp_path, certify_build.constant_replacements(old, new, old_local, new_local) + ) + + assert changed == ["tests/test_models.py"] + assert (tmp_path / "tests/test_models.py").read_text() == ( + f'NATIONAL = "nat-new"\nREVISION = "{COMMIT_C}"\nMODEL = "2.200.0"\n' + f'LOCAL = "releases/loc/loc-new/x"\nLOCAL_COMMIT = "@{"d" * 40}"\n' + "UNQUOTED = nat-old\n" + ) + + +def test_local_area_commit_shared_with_a_national_build_is_left_to_a_person( + certify_build, +): + old = record_for("nat-old", COMMIT_A, "2.199.0", "2.199.0") + new = record_for("nat-new", COMMIT_C, "2.200.0", "2.200.0") + old_local = certify_build.BuildPin("loc", "loc-old", COMMIT_A) + new_local = certify_build.BuildPin("loc", "loc-new", COMMIT_B) + + pairs = certify_build.constant_replacements(old, new, old_local, new_local) + + assert (COMMIT_A, COMMIT_C) in pairs + assert (COMMIT_A, COMMIT_B) not in pairs + assert ( + certify_build.shared_local_area_commit(old, new, old_local, new_local) + == COMMIT_A + ) + + +# --- The pull request body --------------------------------------------------- + + +def body_context(country, **changes): + context = { + "country": country, + "national_build": "nat-b1", + "national_commit": COMMIT_A, + "local_area": None, + "model_label": f"{MODEL_PACKAGES[country]} 2.200.0", + "core": "3.36.1", + "core_binding": "bundle_pin", + "regional_summary": "local-area build `loc-b1`", + "basis": "compatibility_checked_exact_pair", + "base_commit": COMMIT_C, + "checks": [{"build": "nat-b1", "summary": "passed: no dropped columns"}], + "commands": ["python scripts/bundle.py certify-data --country uk"], + "uc_floor": "`passed`", + "uc_floor_passed": True, + } + context.update(changes) + return context + + +def test_body_lists_the_check_results_and_asks_for_no_qualification_receipts( + certify_build, +): + body = certify_build.pr_body(body_context("us")) + + assert "`nat-b1`: passed: no dropped columns" in body + assert "compatibility_checked_exact_pair" in body + assert "qualification" not in body.lower() + assert "Universal Credit" not in body + assert "Needs a person" not in body + + +def test_uk_body_asks_a_person_to_accept_a_failed_universal_credit_floor( + certify_build, +): + body = certify_build.pr_body( + body_context( + "uk", uc_floor="`FAILED`", uc_floor_passed=False, footer="Made by a tool" + ) + ) + + assert "Universal Credit floor (weighted national totals" in body + assert "- [ ] **Universal Credit floor.**" in body + assert body.rstrip().endswith("Made by a tool") + + +def test_commit_credits_only_the_named_co_authors(certify_build): + assert certify_build.commit_message("Certify x") == "Certify x" + assert certify_build.commit_message("Certify x", co_authors=["A B "]) == ( + "Certify x\n\nCo-Authored-By: A B " + ) + + +# --- The whole command ------------------------------------------------------- + + +CHECK_RECORD = { + "defaulted_inputs": ["is_disabled"], + "never_modelled_columns": ["old_flag", "older_flag"], + "artifacts": { + "national": {"path": "x.h5", "households": 20000, "sample_households": 2000} + }, +} + + +class FakeShell: + """Records each command; runs git and gh for real, imitates the rest.""" + + runs: list[list[str]] = [] + + def __init__(self, cwd, log): + self.cwd = cwd + self.argvs = [] + FakeShell.runs = self.argvs + + def public_commands(self, home=None): + return [" ".join(argv) for argv in self.argvs] + + def __call__(self, argv, *, step, env=None, check=True, credentials=True): + self.argvs.append(list(argv)) + if argv[0] == "git": + subprocess.run(argv, cwd=self.cwd, check=True) + elif "certify-data" in argv: + bundle_path = self.cwd / "src/policyengine/data/bundle/manifest.json" + bundle = json.loads(bundle_path.read_text()) + country = argv[argv.index("--country") + 1] + record = bundle["data_releases"][country] + record["certification"]["data_build_id"] = "nat-b1" + record["certification"]["compatibility_basis"] = ( + "compatibility_checked_exact_pair" + ) + bundle_path.write_text(json.dumps(bundle)) + (self.cwd / "changelog.d").mkdir(exist_ok=True) + (self.cwd / f"changelog.d/certify-{country}-nat-b1.changed.md").write_text( + "x\n" + ) + elif "check_uk_uc_floor.py" in argv[1]: + receipt = { + "check": "uk_uc_floor", + "passed": True, + "measures": [ + {"name": "benefit_units", "ratio": 1.0, "passed": True}, + {"name": "spend", "ratio": 1.0, "passed": True}, + ], + } + Path(argv[argv.index("--output") + 1]).write_text(json.dumps(receipt)) + elif "check-compatibility" in argv: + record = Path(argv[argv.index("--output") + 1]) + record.parent.mkdir(parents=True, exist_ok=True) + record.write_text(json.dumps(CHECK_RECORD)) + return subprocess.CompletedProcess(argv, 0, "", "") + + +def bundle_checkout(tmp_path: Path) -> Path: + checkout = git_repository(tmp_path / "py") + bundle_path = checkout / "src/policyengine/data/bundle/manifest.json" + bundle_path.parent.mkdir(parents=True) + bundle_path.write_text(json.dumps(BUNDLE)) + commit_all(checkout) + return checkout + + +def step_names(runs): + names = [] + for argv in runs: + if argv[0] == "uv": + names.append(f"uv {argv[1]}") + elif argv[0] == "git": + names.append(f"git {argv[1]}") + elif "-m" in argv and "pytest" in argv: + names.append("snapshots") + else: + names.append( + next( + argument + for argument in argv[1:] + if not argument.startswith("-") and argument != "scripts/bundle.py" + ).split("/")[-1] + ) + return names + + +@pytest.mark.parametrize("country", ["us", "uk"]) +def test_in_place_run_checks_both_builds_then_certifies_without_committing( + certify_build, monkeypatch, tmp_path, country +): + monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0) + checkout = bundle_checkout(tmp_path) + hub, _ = hub_for(certify_build, country) + args = certify_build.parse( + ["--country", country, "--national-build", "nat-b1", "--local-area-build", + "loc-b1", "--model-version", "2.200.0", "--in-place", + "--output-dir", str(tmp_path / "out")] + ) # fmt: skip + + code = certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout) + + assert code == 0 + expected = [ + "uv sync", + "check-compatibility", + "check-compatibility", + "certify-data", + "uv lock", + "uv sync", + "release_lock.py", + "generate", + "snapshots", + "check", + ] + (["check_uk_uc_floor.py"] if country == "uk" else []) + assert step_names(FakeShell.runs) == expected + checks = [argv for argv in FakeShell.runs if "check-compatibility" in argv] + national_uri, local_uri = ( + argv[argv.index("--manifest-uri") + 1] for argv in checks + ) + assert national_uri.endswith( + f"@{COMMIT_A}/releases/{RELEASES[country][0]}/nat-b1/release_manifest.json" + ) + assert local_uri.endswith( + f"@{COMMIT_B}/releases/{RELEASES[country][1]}/loc-b1/release_manifest.json" + ) + certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv) + assert certify_data[certify_data.index("--regional-manifest-uri") + 1] == local_uri + assert certify_data[certify_data.index("--model-version") + 1] == "2.200.0" + assert "--core-version" not in certify_data + assert "--data-producer" in certify_data + # The national build was made with 2.200.0, so it is certified without a + # record; the local-area build was made with 2.199.0, so on its record. + assert "--compatibility-record" not in certify_data + assert certify_data[certify_data.index("--regional-compatibility-record") + 1] == ( + str(tmp_path / "out" / "py.compatibility" / "loc-b1.record.json") + ) + head = subprocess.run( + ["git", "log", "--oneline"], + cwd=checkout, + capture_output=True, + text=True, + check=True, + ).stdout + assert len(head.splitlines()) == 1 + # A job that commits the result itself stages exactly these paths. + assert (tmp_path / "out" / "py.changed-paths.txt").read_text().splitlines() == [ + f"changelog.d/certify-{country}-nat-b1.changed.md", + "src/policyengine/data/bundle/manifest.json", + ] + body = (tmp_path / "out" / "py.pr-body.md").read_text() + assert f"{MODEL_PACKAGES[country]} 2.200.0" in body + assert "`nat-b1`: passed; no stored column dropped" in body + assert "1 input takes a default (`is_disabled`)" in body + assert "2000 of 20000 households in `x.h5`" in body + + +def test_each_build_made_with_another_model_is_certified_on_its_record( + certify_build, monkeypatch, tmp_path +): + monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0) + checkout = bundle_checkout(tmp_path) + hub, _ = hub_for(certify_build, "us") + args = certify_build.parse( + ["--country", "us", "--national-build", "nat-b1", "--local-area-build", + "loc-b1", "--model-version", "2.201.0", "--core-version", "3.37.0", + "--in-place", "--output-dir", str(tmp_path / "out")] + ) # fmt: skip + + code = certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout) + + assert code == 0 + work_dir = tmp_path / "out" / "py.compatibility" + checks = [argv for argv in FakeShell.runs if "check-compatibility" in argv] + assert len(checks) == 2 + for argv, build in zip(checks, ("nat-b1", "loc-b1")): + assert argv[argv.index("--model-version") + 1] == "2.201.0" + assert argv[argv.index("--core-version") + 1] == "3.37.0" + assert argv[argv.index("--work-dir") + 1] == str(work_dir) + assert argv[argv.index("--output") + 1] == str( + work_dir / f"{build}.record.json" + ) + certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv) + assert certify_data[certify_data.index("--compatibility-record") + 1] == str( + work_dir / "nat-b1.record.json" + ) + assert certify_data[certify_data.index("--regional-compatibility-record") + 1] == ( + str(work_dir / "loc-b1.record.json") + ) + assert certify_data[certify_data.index("--core-version") + 1] == "3.37.0" + + +def test_check_summary_names_what_the_check_found(certify_build): + record = { + "defaulted_inputs": [f"input_{number}" for number in range(12)], + "never_modelled_columns": [], + "artifacts": {}, + } + + summary = certify_build.check_summary(record) + + assert summary.startswith( + "passed; no stored column dropped; 12 inputs take defaults" + ) + assert "`input_9` and 2 more" in summary + assert "the model reads every stored column" in summary + + +def test_worktree_run_commits_on_a_new_branch_with_the_named_co_author( + certify_build, monkeypatch, tmp_path +): + monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0) + checkout = bundle_checkout(tmp_path) + hub, _ = hub_for(certify_build, "uk") + worktree = tmp_path / "certify-worktree" + args = certify_build.parse( + ["--country", "uk", "--national-build", "nat-b1", "--drop-regional-release", + "--base-ref", "HEAD", "--worktree", str(worktree), "--skip-writer-check", + "testing", "--co-author", "A B "] + ) # fmt: skip + + code = certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout) + + assert code == 0 + branch = subprocess.run( + ["git", "branch", "--show-current"], + cwd=worktree, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + assert branch == "certify/uk/nat-b1/policyengine-uk-2.200.0" + message = subprocess.run( + ["git", "log", "-1", "--format=%B"], + cwd=worktree, + capture_output=True, + text=True, + check=True, + ).stdout + assert message.startswith( + "Certify Microcosm UK build nat-b1 for policyengine-uk 2.200.0" + ) + assert "Co-Authored-By: A B " in message + committed = subprocess.run( + ["git", "show", "--name-only", "--format=", "HEAD"], + cwd=worktree, + capture_output=True, + text=True, + check=True, + ).stdout.split() + assert committed == [ + "changelog.d/certify-uk-nat-b1.changed.md", + "src/policyengine/data/bundle/manifest.json", + ] + certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv) + assert "--drop-regional-release" in certify_data + assert not any(argv[:2] == ["git", "push"] for argv in FakeShell.runs) + assert sum("check-compatibility" in argv for argv in FakeShell.runs) == 1 + + +def test_keep_regional_release_reads_the_bundles_local_area_build_at_its_commit( + certify_build, monkeypatch, tmp_path +): + monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0) + checkout = bundle_checkout(tmp_path) + pinned = certify_build.pinned_local_area(BUNDLE["data_releases"]["uk"], REPOS["uk"]) + hub, session = hub_for(certify_build, "uk", local_build=pinned.build) + session.history_pages = [[pinned.commit]] + session.files[ + ( + f"releases/{pinned.release}/{pinned.build}/release_manifest.json", + pinned.commit, + ) + ] = folder_manifest(pinned.release, pinned.build) + args = certify_build.parse( + ["--country", "uk", "--national-build", "nat-b1", "--keep-regional-release", + "--in-place", "--output-dir", str(tmp_path / "out")] + ) # fmt: skip + + certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout) + + certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv) + assert ( + certify_data[certify_data.index("--regional-manifest-uri") + 1] + == (BUNDLE["data_releases"]["uk"]["regional_source_manifest_uri"]) + ) + + +def test_in_place_run_refuses_a_checkout_with_changed_files(certify_build, tmp_path): + checkout = bundle_checkout(tmp_path) + (checkout / "src/policyengine/data/bundle/manifest.json").write_text("{}") + hub, _ = hub_for(certify_build, "uk") + args = certify_build.parse( + [ + "--country", + "uk", + "--national-build", + "nat-b1", + "--drop-regional-release", + "--in-place", + ] + ) + + with pytest.raises(certify_build.CertifyError, match="no changes to tracked files"): + certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout) From c6f29929f767a9ece0ff68e4502f6103bf095128 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:08:49 +0400 Subject: [PATCH 10/25] Certify a Microcosm build of either country by release and build name `scripts/bundle.py certify-build` takes a build of either country by release and build name and does what Microcosm's UK-only certification script did, for both countries: - reads each build at the commit on `main` that published its folder, after checking `releases.json` lists it and has not withdrawn it; - runs the compatibility check on the national build and on the local-area build, and certifies on the check's record when a build was made with another model version; - runs `certify-data`, relocks, regenerates the provenance files and the household snapshots, and runs `bundle.py check` with the TRO files; - for the UK, runs the Universal Credit floor and leaves a failure to a person in the pull request body; - commits only certification files on a new branch in a new worktree, and optionally pushes it and opens a draft pull request. `--in-place` changes the current checkout instead, for a workflow that commits the result itself, and lists the changed paths in the output directory. Co-Authored-By: Claude Opus 5.5 --- scripts/bundle.py | 21 +- scripts/certify_build.py | 1410 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 1430 insertions(+), 1 deletion(-) create mode 100644 scripts/certify_build.py diff --git a/scripts/bundle.py b/scripts/bundle.py index 5c2bd551..8cd60212 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -11,6 +11,8 @@ --manifest-uri hf://... --model-version 2.180.0 \ --work-dir /tmp/check --output record.json python scripts/bundle.py certify-data --country uk --manifest-uri hf://... + python scripts/bundle.py certify-build --country uk --national-build \ + --local-area-build python scripts/bundle.py generate python scripts/bundle.py generate --include-tros python scripts/bundle.py check @@ -384,6 +386,16 @@ def _parser() -> argparse.ArgumentParser: "--output", required=True, help="Where to write the record of a pass." ) compatibility.set_defaults(func=_check_compatibility) + # Listed for --help only: main() hands certify-build's arguments to + # scripts/certify_build.py before this parser runs. + subparsers.add_parser( + "certify-build", + add_help=False, + help=( + "Certify a Microcosm build of either country, named by release and " + "build, on a new branch (see scripts/certify_build.py)." + ), + ) packages = subparsers.add_parser( "update-packages", @@ -474,8 +486,15 @@ def _parser() -> argparse.ArgumentParser: def main(argv: list[str] | None = None) -> int: + arguments = sys.argv[1:] if argv is None else list(argv) + if arguments[:1] == ["certify-build"]: + # Its own parser holds its options, and importing it loads .py, so it + # is imported only when it runs. + from certify_build import main as certify_build_main + + return certify_build_main(arguments[1:]) parser = _parser() - args = parser.parse_args(argv) + args = parser.parse_args(arguments) if getattr(args, "strict_tros", False) and not args.include_tros: parser.error("--strict-tros requires --include-tros") try: diff --git a/scripts/certify_build.py b/scripts/certify_build.py new file mode 100644 index 00000000..fb4bf100 --- /dev/null +++ b/scripts/certify_build.py @@ -0,0 +1,1410 @@ +"""Certify a Microcosm build of either country into the bundle, on a branch. + +``python scripts/bundle.py certify-build`` prepares the certification pull +request for one country's Microcosm national build, and the local-area build +its regions use, named by release and build: + +1. refuse if an open pull request or a branch already certifies this national + build for this model version (``--skip-writer-check WHY`` skips this); +2. read each build from its own folder, ``releases///``, at + the commit that published it, after checking that ``releases.json`` at + ``main`` lists the build and has not withdrawn it, and check that the disk + has room for the builds' files; +3. ``scripts/bundle.py check-compatibility`` for each build and the model + version; certification takes a build's record as its compatibility basis + when the build was made with another model version; +4. ``scripts/bundle.py certify-data`` with the national build and the chosen + regional route; +5. ``uv lock`` and ``scripts/release_lock.py``; +6. ``scripts/bundle.py generate --include-tros``, the rewrite of the + certified constants the tests pin, the household snapshots, then + ``scripts/bundle.py check --published-spm --include-tros --strict-tros``; +7. for the UK, the Universal Credit floor (weighted national totals); +8. a commit on a new branch in a new worktree, and a pull request body that + lists every judgment left to a person. ``--push`` pushes the branch and + ``--open-pr`` opens a draft pull request. It never merges or releases. + +``--in-place`` changes the files of this checkout instead, and makes no +worktree, branch or commit, for a job that commits the result itself. It +writes the paths it changed, one per line, to +``/.changed-paths.txt`` beside the pull request +body, for ``git add --pathspec-from-file``. + +The model version defaults to the one the national build was made with, and +the core to the bundle's pin (``--core-version`` names another and moves the +pin). Each build is pinned at the last commit of its ``release_manifest.json`` +on ``main``, since a build folder never changes after it is published; +``--national-data-commit`` and ``--local-area-data-commit`` name another +commit on ``main`` that holds the folder. + +Regional routes (pick one): + +``--local-area-build BUILD`` route regions to this local-area build +``--keep-regional-release`` keep the local-area build the bundle routes to +``--drop-regional-release`` route no regions to a local-area build + +It runs no tests beyond regenerating the household snapshots; the pull +request's CI runs them. Private builds (the UK) need ``HUGGING_FACE_TOKEN`` +or ``HF_TOKEN``; it also needs ``uv``, PyPI and, for the one-writer check and +the pull request, ``gh``. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import re +import shlex +import shutil +import subprocess +import sys +import time +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any, NamedTuple, Optional + +import requests + +REPO_ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO_ROOT / "src")) + +from policyengine.provenance.certification import ( # noqa: E402 + COUNTRY_MODEL_PACKAGES, + MICROCOSM_RELEASE_REPOS, +) +from policyengine.provenance.manifest import ( # noqa: E402 + HF_REQUEST_TIMEOUT_SECONDS, + RELEASE_FOLDER_NAME, + RELEASE_MANIFEST_NAME, + RELEASES_FOLDER, + RELEASES_RECORD_NAME, + RELEASES_RECORD_REVISION, + DataReleaseManifest, + ReleaseBuildFolderError, + check_build_listed, + release_build_id, +) + +PEPY_REPO = "PolicyEngine/policyengine.py" +#: The interpreter the certified environment is made with. +PEPY_PYTHON = "3.13" +HUB = "https://huggingface.co" +#: A full commit ID. A branch moves, and a short ID can be ambiguous. +COMMIT_PATTERN = re.compile(r"^[0-9a-f]{40}$") +BUNDLE_MANIFEST = "src/policyengine/data/bundle/manifest.json" +#: The compatibility records ``check-compatibility`` writes, one per country. +COMPATIBILITY_RECORD = "src/policyengine/data/compatibility/{country}.json" +SNAPSHOT_DIR = "tests/fixtures/household_calculator_snapshots" +#: Test files that pin the certified builds and model versions as literals. +CONSTANT_FILES = ( + "tests/test_models.py", + "tests/test_release_manifests.py", + "tests/test_uk_regions.py", +) +#: A quoted certified value: ``"2.125.1"``, ``"@"``, ``"//"``. +CONSTANT_PATTERN = r'(?P
["@/-]){old}(?P["/])'
+#: Free disk kept beyond the builds' files: the certified environment, the
+#: compatibility check's throwaway environment and the lock (decimal bytes).
+DISK_MARGIN_BYTES = 5_000_000_000
+#: What .py's commands never get from this process: the caller's environment
+#: selectors, with which uv would sync, install into or run another project's
+#: environment.
+WITHHELD_ENVIRONMENT = frozenset({"UV_PROJECT_ENVIRONMENT", "VIRTUAL_ENV"})
+#: Hugging Face tokens, withheld from steps that only install or resolve
+#: packages.
+HF_TOKEN_ENVIRONMENT = frozenset(
+    {
+        "HF_TOKEN",
+        "HUGGING_FACE_TOKEN",
+        "HUGGINGFACE_HUB_TOKEN",
+        "HUGGING_FACE_HUB_TOKEN",
+    }
+)
+#: A commit trailer's co-author: one line, ``Name ``.
+CO_AUTHOR_PATTERN = re.compile(r"^[^<>\n]+ <[^<>\s@]+@[^<>\s]+>$")
+
+
+class CertifyError(RuntimeError):
+    """A refusal the operator must act on."""
+
+
+class BuildPin(NamedTuple):
+    """A build in its own folder, and the commit it is read at."""
+
+    release: str
+    build: str
+    commit: str
+
+
+def build_folder(release: str, build: str) -> str:
+    return f"{RELEASES_FOLDER}/{release}/{build}"
+
+
+def folder_manifest_path(release: str, build: str) -> str:
+    return f"{build_folder(release, build)}/{RELEASE_MANIFEST_NAME}"
+
+
+def manifest_uri(repo: str, release: str, build: str, commit: str) -> str:
+    """The build's folder manifest at ``commit``, as ``certify-data`` takes it."""
+
+    return f"hf://dataset/{repo}@{commit}/{folder_manifest_path(release, build)}"
+
+
+def folder_reference(uri: Optional[str], repo: str) -> Optional[BuildPin]:
+    """The build a folder manifest URI in ``repo`` names, or ``None`` for any
+    other URI (a tagged manifest, another repository)."""
+
+    pattern = re.compile(
+        rf"^hf://dataset/{re.escape(repo)}@(?P[^/@]+)"
+        rf"/{RELEASES_FOLDER}/(?P[^/]+)/(?P[^/]+)"
+        rf"/{re.escape(RELEASE_MANIFEST_NAME)}$"
+    )
+    match = pattern.match(uri or "")
+    if match is None:
+        return None
+    return BuildPin(match["release"], match["build"], match["commit"])
+
+
+@dataclass(frozen=True)
+class PublishedBuild:
+    """A build read from its own folder, and what it was made with."""
+
+    repo: str
+    release: str
+    build: str
+    commit: str
+    model: str
+    core: str
+    folder_bytes: int
+
+    @property
+    def pin(self) -> BuildPin:
+        return BuildPin(self.release, self.build, self.commit)
+
+    @property
+    def manifest_uri(self) -> str:
+        return manifest_uri(self.repo, self.release, self.build, self.commit)
+
+
+# --- Reading builds from the Hub -------------------------------------------
+
+
+def hub_token() -> Optional[str]:
+    return os.environ.get("HUGGING_FACE_TOKEN") or os.environ.get("HF_TOKEN")
+
+
+class Hub:
+    """Reads a dataset repository on the Hugging Face Hub over HTTP."""
+
+    def __init__(self, token: Optional[str] = None, session: Any = None) -> None:
+        self.headers = {"Authorization": f"Bearer {token}"} if token else {}
+        self.session = requests if session is None else session
+
+    def _answer(self, method: str, url: str, what: str, **kwargs: Any) -> Any:
+        try:
+            response = getattr(self.session, method)(
+                url,
+                headers=self.headers,
+                timeout=HF_REQUEST_TIMEOUT_SECONDS,
+                **kwargs,
+            )
+        except requests.RequestException as error:
+            raise CertifyError(f"could not read {what}: {error}") from error
+        if response.status_code != 200:
+            raise CertifyError(
+                f"could not read {what} ({response.status_code}) from {url}."
+            )
+        return response
+
+    def file(self, repo: str, path: str, revision: str) -> bytes:
+        url = f"{HUB}/datasets/{repo}/resolve/{revision}/{path}"
+        return self._answer("get", url, f"{path} at {revision} in {repo}").content
+
+    def last_commit(self, repo: str, path: str) -> str:
+        """The last commit of ``path`` on ``main``."""
+
+        url = f"{HUB}/api/datasets/{repo}/paths-info/{RELEASES_RECORD_REVISION}"
+        entries = self._answer(
+            "post",
+            url,
+            f"which commit published {path} in {repo}",
+            data={"paths": path, "expand": "true"},
+        ).json()
+        for entry in entries if isinstance(entries, list) else ():
+            commit = (entry.get("lastCommit") or {}).get("id")
+            if entry.get("path") == path and COMMIT_PATTERN.match(str(commit or "")):
+                return str(commit)
+        raise CertifyError(
+            f"{repo} has no {path} on {RELEASES_RECORD_REVISION}, so the build "
+            "has no folder to certify from."
+        )
+
+    def commit_on_main(self, repo: str, commit: str) -> bool:
+        """Whether ``commit`` is in ``main``'s history, page by page."""
+
+        url: Optional[str] = (
+            f"{HUB}/api/datasets/{repo}/commits/{RELEASES_RECORD_REVISION}"
+        )
+        while url:
+            response = self._answer("get", url, f"main's history in {repo}")
+            if any(entry.get("id") == commit for entry in response.json()):
+                return True
+            url = (getattr(response, "links", None) or {}).get("next", {}).get("url")
+        return False
+
+    def folder_bytes(self, repo: str, folder: str, revision: str) -> int:
+        """The total size of the files in ``folder`` at ``revision``."""
+
+        url: Optional[str] = f"{HUB}/api/datasets/{repo}/tree/{revision}/{folder}"
+        total = 0
+        while url:
+            response = self._answer("get", url, f"the files of {folder} in {repo}")
+            total += sum(
+                int(entry.get("size") or 0)
+                for entry in response.json()
+                if entry.get("type") == "file"
+            )
+            url = (getattr(response, "links", None) or {}).get("next", {}).get("url")
+        return total
+
+
+def read_published_build(
+    hub: Hub,
+    country: str,
+    release: str,
+    build: str,
+    *,
+    commit: Optional[str] = None,
+) -> PublishedBuild:
+    """Build ``build`` of ``release``, read from its own folder.
+
+    ``releases.json`` at ``main`` must list the build and 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 made with.
+    """
+
+    repo = MICROCOSM_RELEASE_REPOS[country]
+    record = hub.file(repo, RELEASES_RECORD_NAME, RELEASES_RECORD_REVISION)
+    try:
+        check_build_listed(record, release=release, build=build)
+    except ReleaseBuildFolderError as error:
+        raise CertifyError(f"{repo}: {error}") from error
+    path = folder_manifest_path(release, build)
+    if commit is None:
+        commit = hub.last_commit(repo, path)
+    elif not hub.commit_on_main(repo, commit):
+        raise CertifyError(
+            f"commit {commit} is not in main's history in {repo}; pin a commit "
+            "on main that holds the build's folder."
+        )
+    try:
+        manifest = DataReleaseManifest.model_validate(
+            json.loads(hub.file(repo, path, commit))
+        )
+    except ValueError as error:
+        raise CertifyError(f"{path} at {commit} is not a release manifest.") from error
+    named = (manifest.release, release_build_id(manifest.build))
+    if named != (release, build):
+        raise CertifyError(
+            f"{path} at {commit} names release {named[0]!r} and build {named[1]!r}."
+        )
+    details = manifest.build
+    model = details.built_with_model_package if details else None
+    core = details.built_with_core_package if details else None
+    if model is None or not model.version:
+        raise CertifyError(f"{path} at {commit} records no built_with_model_package.")
+    if core is None or not core.version:
+        raise CertifyError(f"{path} at {commit} records no built_with_core_package.")
+    return PublishedBuild(
+        repo=repo,
+        release=release,
+        build=build,
+        commit=commit,
+        model=model.version,
+        core=core.version,
+        folder_bytes=hub.folder_bytes(repo, build_folder(release, build), commit),
+    )
+
+
+# --- What the bundle pins now ----------------------------------------------
+
+
+def pinned_national(record: Mapping[str, Any], repo: str) -> Optional[BuildPin]:
+    """The national build the bundle's record certifies, when it is a build in
+    its own folder in ``repo``."""
+
+    package = record.get("data_package") or {}
+    if package.get("repo_id") != repo:
+        return None
+    match = re.match(
+        rf"^{RELEASES_FOLDER}/(?P[^/]+)/(?P[^/]+)"
+        rf"/{re.escape(RELEASE_MANIFEST_NAME)}$",
+        package.get("release_manifest_path") or "",
+    )
+    revision = package.get("release_manifest_revision")
+    if match is None or not revision:
+        return None
+    return BuildPin(match["release"], match["build"], revision)
+
+
+def pinned_local_area(record: Mapping[str, Any], repo: str) -> Optional[BuildPin]:
+    """The local-area build the bundle's record routes regions to, when it is
+    a build in its own folder in ``repo``."""
+
+    return folder_reference(record.get("regional_source_manifest_uri"), repo)
+
+
+def default_release(given: Optional[str], pinned: Optional[BuildPin], flag: str) -> str:
+    if given:
+        return given
+    if pinned is None:
+        raise CertifyError(
+            f"the bundle pins no build in its own folder to take the release "
+            f"name from; name it with {flag}."
+        )
+    return pinned.release
+
+
+# --- Running .py's commands -------------------------------------------------
+
+
+def policyengine_py_environment(*, credentials: bool = True) -> dict[str, str]:
+    """This process's environment, less what .py's commands must not see.
+
+    ``credentials=False`` also withholds the Hugging Face tokens, for steps
+    that only install or resolve packages.
+    """
+
+    withheld = WITHHELD_ENVIRONMENT | (
+        frozenset() if credentials else HF_TOKEN_ENVIRONMENT
+    )
+    return {key: value for key, value in os.environ.items() if key not in withheld}
+
+
+def public_command(argv: Sequence[str], checkout: Path, *, home: Path) -> str:
+    """A command as the pull request body shows it.
+
+    A path in the checkout is shown relative to it, one beside it starting
+    ``../``, and one under the home directory starting ``~/``, so the body
+    names no one's folders.
+    """
+
+    prefixes = (
+        (f"{checkout}/", ""),
+        (f"{checkout.parent}/", "../"),
+        (f"{home}/", "~/"),
+    )
+    shown = []
+    for argument in argv:
+        for prefix, replacement in prefixes:
+            argument = argument.replace(prefix, replacement)
+        shown.append(argument)
+    return shlex.join(shown)
+
+
+class Shell:
+    """Runs commands in the checkout being certified, logging their output."""
+
+    def __init__(self, cwd: Path, log: Path) -> None:
+        self.cwd = cwd
+        self.log = log
+        self.argvs: list[list[str]] = []
+
+    def public_commands(self, *, home: Optional[Path] = None) -> list[str]:
+        home = Path.home() if home is None else home
+        return [public_command(argv, self.cwd, home=home) for argv in self.argvs]
+
+    def __call__(
+        self,
+        argv: list[str],
+        *,
+        step: str,
+        env: Optional[dict[str, str]] = None,
+        check: bool = True,
+        credentials: bool = True,
+    ) -> subprocess.CompletedProcess:
+        line = shlex.join(argv)
+        self.argvs.append(list(argv))
+        print(f"$ {line}", flush=True)
+        started = time.monotonic()
+        output: list[str] = []
+        self.log.parent.mkdir(parents=True, exist_ok=True)
+        with self.log.open("a") as handle:
+            handle.write(f"\n# {step}: $ {line}\n")
+            handle.flush()
+            with subprocess.Popen(
+                argv,
+                cwd=self.cwd,
+                env={
+                    **policyengine_py_environment(credentials=credentials),
+                    **(env or {}),
+                },
+                stdout=subprocess.PIPE,
+                stderr=subprocess.STDOUT,
+                text=True,
+                bufsize=1,
+            ) as process:
+                for text in process.stdout or ():
+                    handle.write(text)
+                    handle.flush()
+                    output.append(text)
+                returncode = process.wait()
+        print(
+            f"[done] {step}: {time.monotonic() - started:.1f}s (exit {returncode})",
+            flush=True,
+        )
+        result = subprocess.CompletedProcess(argv, returncode, "".join(output), "")
+        if check and returncode != 0:
+            tail = "\n".join(result.stdout.splitlines()[-25:])
+            raise CertifyError(f"{step} exited {returncode}:\n{tail}")
+        return result
+
+
+def git(checkout: Path, *arguments: str) -> str:
+    return subprocess.check_output(["git", *arguments], cwd=checkout, text=True)
+
+
+# --- Checks before anything is written --------------------------------------
+
+
+def writer_check(
+    checkout: Path, branch: str, national_build: str, model_label: str
+) -> list[str]:
+    """Open pull requests or branches already certifying this national build
+    for this model version.
+
+    A writer is an open pull request whose title or body names both the build
+    and ``model_label`` (``" "``), an open pull
+    request from ``branch``, or ``branch`` on ``origin``. A listing that
+    cannot be read refuses rather than passing.
+    """
+
+    found = []
+    listing = subprocess.run(
+        [
+            "gh", "pr", "list", "--repo", PEPY_REPO, "--state", "open",
+            "--limit", "1000", "--json", "number,title,body,headRefName",
+        ],
+        capture_output=True,
+        text=True,
+        check=False,
+        timeout=120,
+    )  # fmt: skip
+    if listing.returncode != 0:
+        raise CertifyError(
+            "could not list .py pull requests to check for another writer "
+            f"({listing.stderr.strip()[:200]}); retry, or pass "
+            "--skip-writer-check with a reason."
+        )
+    for pull_request in json.loads(listing.stdout or "[]"):
+        text = f"{pull_request.get('title') or ''}\n{pull_request.get('body') or ''}"
+        names_pair = national_build in text and model_label in text
+        if names_pair or pull_request.get("headRefName") == branch:
+            found.append(
+                f"#{pull_request['number']} {pull_request['title']} "
+                f"({pull_request['headRefName']})"
+            )
+    remote = subprocess.run(
+        ["git", "ls-remote", "--heads", "origin", f"refs/heads/{branch}"],
+        cwd=checkout,
+        capture_output=True,
+        text=True,
+        check=False,
+        timeout=120,
+    )
+    if remote.returncode != 0:
+        raise CertifyError(
+            "could not list .py branches to check for another writer "
+            f"({remote.stderr.strip()[:200]}); retry, or pass "
+            "--skip-writer-check with a reason."
+        )
+    if remote.stdout.strip():
+        found.append(f"branch {branch} exists on origin")
+    return found
+
+
+def check_free_disk(directory: Path, needed: int) -> int:
+    """Refuse before any download when ``directory``'s disk has less free
+    space than ``needed`` bytes; returns the free bytes."""
+
+    while not directory.exists():
+        directory = directory.parent
+    free = shutil.disk_usage(directory).free
+    if free < needed:
+        raise CertifyError(
+            f"{directory} has {free / 1e9:.1f} GB free; certifying these builds "
+            f"needs {needed / 1e9:.1f} GB (their files and "
+            f"{DISK_MARGIN_BYTES / 1e9:g} GB for the environments)."
+        )
+    return free
+
+
+def tracked_changes(checkout: Path) -> list[str]:
+    output = git(checkout, "status", "--porcelain", "--untracked-files=no", "-z")
+    return [entry[3:] for entry in output.split("\0") if entry]
+
+
+# --- Files certification changes ---------------------------------------------
+
+
+def changelog_fragment(country: str, national_build: str) -> str:
+    """The fragment ``certify-data`` writes."""
+
+    return f"changelog.d/certify-{country}-{national_build}.changed.md"
+
+
+def certification_path(relative: str, country: str, national_build: str) -> bool:
+    """A file this command may change: generated files only."""
+
+    if relative.startswith(f"{SNAPSHOT_DIR}/") and relative.endswith(".json"):
+        return "/" not in relative.removeprefix(f"{SNAPSHOT_DIR}/")
+    return relative in {
+        "pyproject.toml",
+        "uv.lock",
+        *CONSTANT_FILES,
+        changelog_fragment(country, national_build),
+        BUNDLE_MANIFEST,
+        COMPATIBILITY_RECORD.format(country=country),
+        "src/policyengine/data/bundle/uk.trace.tro.jsonld",
+        "src/policyengine/data/bundle/us.trace.tro.jsonld",
+    }
+
+
+def certification_changes(
+    checkout: Path, country: str, national_build: str
+) -> list[str]:
+    """The files to commit: every tracked change, and the new files
+    certification writes. Refuses any tracked change it did not make."""
+
+    tracked = [
+        path
+        for path in git(checkout, "diff", "--name-only", "-z", "HEAD").split("\0")
+        if path
+    ]
+    unexpected = [
+        path
+        for path in tracked
+        if not certification_path(path, country, national_build)
+    ]
+    if unexpected:
+        raise CertifyError(
+            "files certification does not write have changed; refusing to "
+            "commit: " + ", ".join(unexpected)
+        )
+    untracked = git(checkout, "ls-files", "--others", "--exclude-standard", "-z")
+    new = {
+        changelog_fragment(country, national_build),
+        COMPATIBILITY_RECORD.format(country=country),
+    }
+    return sorted(
+        set(tracked) | {path for path in untracked.split("\0") if path in new}
+    )
+
+
+def certified_values(record: Mapping[str, Any]) -> dict[str, Optional[str]]:
+    certification = record.get("certification") or {}
+    data = record.get("data_package") or {}
+    return {
+        "build_id": certification.get("data_build_id"),
+        "revision": data.get("release_manifest_revision"),
+        "model": (record.get("model_package") or {}).get("version"),
+        "built_with": certification.get("built_with_model_version"),
+        "data": data.get("version"),
+    }
+
+
+def constant_replacements(
+    old_record: Mapping[str, Any],
+    new_record: Mapping[str, Any],
+    old_local_area: Optional[BuildPin],
+    new_local_area: Optional[BuildPin],
+) -> list[tuple[str, str]]:
+    """Old certified values and their new ones, national first.
+
+    The local-area build's name and commit move only when the bundle routed
+    regions to one before and routes them to one now. A local-area commit
+    shared with the old or new national build is left alone, since a literal
+    rewrite cannot tell the two builds' constants apart.
+    """
+
+    old, new = certified_values(old_record), certified_values(new_record)
+    pairs = [
+        (old[key], new[key])
+        for key in ("build_id", "revision", "model", "built_with", "data")
+        if old[key] and new[key] and old[key] != new[key]
+    ]
+    if old_local_area is not None and new_local_area is not None:
+        national_commits = {old["revision"], new["revision"]}
+        if old_local_area.build != new_local_area.build:
+            pairs.append((old_local_area.build, new_local_area.build))
+        if (
+            old_local_area.commit != new_local_area.commit
+            and old_local_area.commit not in national_commits
+        ):
+            pairs.append((old_local_area.commit, new_local_area.commit))
+    seen: set[str] = set()
+    unique = []
+    for before, after in pairs:
+        if before not in seen:
+            seen.add(before)
+            unique.append((before, after))
+    return unique
+
+
+def rewrite_constants(
+    checkout: Path, replacements: Sequence[tuple[str, str]]
+) -> list[str]:
+    """Rewrite quoted occurrences of old certified values in the constant
+    files; returns the files changed."""
+
+    changed = []
+    for relative in CONSTANT_FILES if replacements else ():
+        path = checkout / relative
+        if not path.exists():
+            continue
+        text = updated = path.read_text()
+        for before, after in replacements:
+            pattern = re.compile(CONSTANT_PATTERN.format(old=re.escape(before)))
+            updated = pattern.sub(
+                lambda match, after=after: match["pre"] + after + match["post"],
+                updated,
+            )
+        if updated != text:
+            path.write_text(updated)
+            changed.append(relative)
+    return changed
+
+
+def shared_local_area_commit(
+    old_record: Mapping[str, Any],
+    new_record: Mapping[str, Any],
+    old_local_area: Optional[BuildPin],
+    new_local_area: Optional[BuildPin],
+) -> Optional[str]:
+    """The old local-area commit when a rewrite cannot move it: it is also
+    the old or new national commit, and the new builds' commits differ."""
+
+    if old_local_area is None or new_local_area is None:
+        return None
+    old, new = certified_values(old_record), certified_values(new_record)
+    if (
+        old_local_area.commit in {old["revision"], new["revision"]}
+        and old_local_area.commit != new_local_area.commit
+        and new_local_area.commit != new["revision"]
+    ):
+        return old_local_area.commit
+    return None
+
+
+def dropped_overlays(
+    country: str, old_bundle: Mapping[str, Any], new_bundle: Mapping[str, Any]
+) -> list[str]:
+    old = set(((old_bundle.get("dataset_overlays") or {}).get(country)) or {})
+    new = set(((new_bundle.get("dataset_overlays") or {}).get(country)) or {})
+    return sorted(old - new)
+
+
+# --- Results -----------------------------------------------------------------
+
+
+def uc_floor_summary(receipt: object) -> tuple[bool, str]:
+    """The Universal Credit floor's verdict and a summary of its ratios.
+
+    Only a complete receipt is accepted: the ``uk_uc_floor`` check with a
+    boolean verdict, and measures including ``benefit_units`` and ``spend``,
+    each with a unique name, a boolean verdict and a finite ratio, whose
+    verdicts together give the overall one. Anything else is the check failing
+    to run, never a crash.
+    """
+
+    incomplete = CertifyError(
+        "the Universal Credit floor check did not run: incomplete receipt."
+    )
+    if not isinstance(receipt, dict) or receipt.get("check") != "uk_uc_floor":
+        raise incomplete
+    passed, measures = receipt.get("passed"), receipt.get("measures")
+    if not isinstance(passed, bool) or not isinstance(measures, list):
+        raise incomplete
+    rows: list[tuple[str, float, bool]] = []
+    for measure in measures:
+        if not isinstance(measure, dict):
+            raise incomplete
+        name, ratio, verdict = (measure.get(k) for k in ("name", "ratio", "passed"))
+        if not isinstance(name, str) or not name or not isinstance(verdict, bool):
+            raise incomplete
+        if isinstance(ratio, bool) or not isinstance(ratio, (int, float)):
+            raise incomplete
+        try:
+            ratio = float(ratio)
+        except OverflowError:
+            raise incomplete from None
+        if not math.isfinite(ratio):
+            raise incomplete
+        rows.append((name, ratio, verdict))
+    names = [name for name, _, _ in rows]
+    if len(set(names)) != len(names) or not {"benefit_units", "spend"} <= set(names):
+        raise incomplete
+    if passed != all(verdict for _, _, verdict in rows):
+        raise incomplete
+    ratios = ", ".join(f"{name}={ratio:.6f}" for name, ratio, _ in rows)
+    return passed, (
+        f"{'passed' if passed else 'FAILED'}; measured/benchmark ratios: {ratios}"
+    )
+
+
+def core_summary(core: str, core_binding: str) -> str:
+    if core_binding == "certified":
+        return f"policyengine-core {core} (`core_binding: certified`)"
+    return f"policyengine-core {core}, the bundle's pin (`core_binding: bundle_pin`)"
+
+
+def pull_request_title(country: str, national_build: str, model_label: str) -> str:
+    return (
+        f"Certify Microcosm {country.upper()} build {national_build} for {model_label}"
+    )
+
+
+def pr_body(context: Mapping[str, Any]) -> str:
+    """The pull request body: what was certified, how, and what a person must
+    still judge."""
+
+    local_area = context.get("local_area")
+    lines = [
+        f"Certifies Microcosm {context['country'].upper()} national build "
+        f"`{context['national_build']}` from its folder at commit "
+        f"`{context['national_commit']}`, for {context['model_label']} with "
+        f"{core_summary(context['core'], context['core_binding'])}.",
+        "",
+        f"- **Regional route:** {context['regional_summary']}",
+        f"- **Compatibility basis:** `{context.get('basis')}`",
+        f"- **Made by** `scripts/bundle.py certify-build` at "
+        f"`{context['base_commit'][:9]}`.",
+        "",
+        "## Compatibility check",
+        "",
+    ]
+    for check in context.get("checks") or ():
+        lines.append(f"- `{check['build']}`: {check['summary']}")
+    lines += [
+        "",
+        "## How it was made",
+        "",
+        "```bash",
+        *context["commands"],
+        "```",
+        "",
+        "## Results",
+        "",
+    ]
+    if context["country"] == "uk":
+        lines.append(
+            "- Universal Credit floor (weighted national totals, "
+            f"`scripts/check_uk_uc_floor.py`): {context.get('uc_floor', 'not run')}"
+        )
+    lines += [
+        "- Tests: not run by this command, apart from regenerating the household "
+        "snapshots; the pull request's CI runs them.",
+        f"- Certified-constant files rewritten: {context.get('constants') or 'none'}",
+    ]
+    needs = []
+    if context.get("uc_floor_passed") is False:
+        needs.append(
+            "- [ ] **Universal Credit floor.** This build fails the floor; accept "
+            "it explicitly in this pull request (data-certification.md, "
+            "recorded exceptions). Accepted by: ___"
+        )
+    if context.get("shared_old_commit"):
+        regional = local_area.commit if local_area is not None else None
+        needs.append(
+            "- [ ] **Local-area commit constants.** The previous local-area build "
+            f"shared commit `{context['shared_old_commit']}` with a national "
+            "build, so rewriting quoted literals cannot tell the two builds' "
+            "constants apart, and this command 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.")
+        )
+    if context.get("dropped_overlays"):
+        needs.append(
+            "- [ ] **Dataset overlays dropped by certification:** "
+            f"{', '.join(context['dropped_overlays'])}. Re-add any that must stay "
+            "loadable from the previous bundle."
+        )
+    if context.get("warnings"):
+        needs.append(
+            "- [ ] **Certification warnings** (from `certify-data`):\n  "
+            + "\n  ".join(f"- {warning}" for warning in context["warnings"])
+        )
+    if needs:
+        lines += ["", "## Needs a person before this leaves draft", "", *needs]
+    if context.get("footer"):
+        lines += ["", context["footer"]]
+    return "\n".join(lines) + "\n"
+
+
+def commit_message(title: str, *, co_authors: Sequence[str] = ()) -> str:
+    """The certification commit's message, crediting only the named co-authors."""
+
+    if not co_authors:
+        return title
+    trailers = "\n".join(f"Co-Authored-By: {author}" for author in co_authors)
+    return f"{title}\n\n{trailers}"
+
+
+# --- Arguments ---------------------------------------------------------------
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+    parser.add_argument(
+        "--country", required=True, choices=sorted(MICROCOSM_RELEASE_REPOS)
+    )
+    parser.add_argument(
+        "--national-build",
+        required=True,
+        metavar="BUILD",
+        help="the national build's name in releases.json",
+    )
+    parser.add_argument(
+        "--national-release",
+        metavar="RELEASE",
+        help="the national build's release (default: the bundle's national release)",
+    )
+    parser.add_argument(
+        "--national-data-commit",
+        metavar="COMMIT",
+        help="read the national build at this commit on main instead of the one "
+        "that published its folder",
+    )
+    route = parser.add_mutually_exclusive_group(required=True)
+    route.add_argument(
+        "--local-area-build",
+        metavar="BUILD",
+        help="route the local region types to this local-area build",
+    )
+    route.add_argument(
+        "--keep-regional-release",
+        action="store_true",
+        help="keep the local-area build the bundle routes regions to",
+    )
+    route.add_argument(
+        "--drop-regional-release",
+        action="store_true",
+        help="route no regions to a local-area build",
+    )
+    parser.add_argument(
+        "--local-area-release",
+        metavar="RELEASE",
+        help="the local-area build's release (default: the bundle's local-area "
+        "release)",
+    )
+    parser.add_argument(
+        "--local-area-data-commit",
+        metavar="COMMIT",
+        help="with --local-area-build: read it at this commit on main instead of "
+        "the one that published its folder",
+    )
+    parser.add_argument(
+        "--model-version",
+        help="the model version to certify for (default: the national build's own)",
+    )
+    parser.add_argument(
+        "--core-version",
+        help="bind the certificate to this policyengine-core and move the "
+        "bundle's core pin to it (default: the bundle's core pin)",
+    )
+    parser.add_argument(
+        "--in-place",
+        action="store_true",
+        help="change this checkout's files instead of making a worktree, branch "
+        "and commit, and list the changed paths in the output directory",
+    )
+    parser.add_argument(
+        "--worktree",
+        type=Path,
+        help="the new worktree (default: beside this checkout)",
+    )
+    parser.add_argument(
+        "--base-ref",
+        default="origin/main",
+        help="the commit the branch starts from (default: origin/main)",
+    )
+    parser.add_argument(
+        "--output-dir",
+        type=Path,
+        help="where the log, the pull request body and, with --in-place, the "
+        "list of changed paths go (default: beside the checkout being certified)",
+    )
+    parser.add_argument("--skip-writer-check", metavar="WHY")
+    parser.add_argument("--push", action="store_true", help="push the branch")
+    parser.add_argument(
+        "--open-pr", action="store_true", help="open a draft pull request; needs --push"
+    )
+    parser.add_argument("--dry-run", action="store_true", help="print the plan only")
+    parser.add_argument(
+        "--co-author",
+        action="append",
+        default=[],
+        metavar="NAME ",
+        help="add a Co-Authored-By trailer to the commit (repeatable)",
+    )
+    parser.add_argument(
+        "--pr-body-footer",
+        metavar="TEXT",
+        help="a closing line for the pull request body",
+    )
+
+
+def validate(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None:
+    if args.open_pr and not args.push:
+        parser.error("--open-pr needs --push.")
+    if args.in_place:
+        for flag, given in (
+            ("--worktree", args.worktree is not None),
+            ("--push", args.push),
+            ("--co-author", bool(args.co_author)),
+            ("--base-ref", args.base_ref != "origin/main"),
+        ):
+            if given:
+                parser.error(
+                    f"{flag} does not go with --in-place, which commits nothing."
+                )
+    for author in args.co_author:
+        if not CO_AUTHOR_PATTERN.match(author):
+            parser.error(f"--co-author must be one line, 'Name ': {author!r}")
+    for flag, name in (
+        ("--national-build", args.national_build),
+        ("--national-release", args.national_release),
+        ("--local-area-build", args.local_area_build),
+        ("--local-area-release", args.local_area_release),
+    ):
+        if name is not None and not RELEASE_FOLDER_NAME.fullmatch(name):
+            parser.error(f"{flag} {name!r} is not a release or build name.")
+    for flag, commit in (
+        ("--national-data-commit", args.national_data_commit),
+        ("--local-area-data-commit", args.local_area_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.local_area_build is None and (
+        args.local_area_data_commit is not None or args.local_area_release is not None
+    ):
+        parser.error(
+            "--local-area-release and --local-area-data-commit go with "
+            "--local-area-build."
+        )
+
+
+def parse(argv: Optional[Sequence[str]]) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        prog="bundle.py certify-build", description=__doc__.split("\n\n")[0]
+    )
+    add_arguments(parser)
+    args = parser.parse_args(argv)
+    validate(args, parser)
+    return args
+
+
+# --- The certification -------------------------------------------------------
+
+
+def branch_name(country: str, national_build: str, model_label: str) -> str:
+    return f"certify/{country}/{national_build}/{model_label.replace(' ', '-')}"
+
+
+def compatibility_check_argv(
+    python: str,
+    country: str,
+    build: PublishedBuild,
+    model_version: str,
+    core_version: str,
+    work_dir: Path,
+    record: Path,
+) -> list[str]:
+    """``check-compatibility`` for one build and the model and core versions,
+    downloading into ``work_dir`` and writing the record of a pass to
+    ``record``."""
+
+    return [
+        python, "scripts/bundle.py", "check-compatibility",
+        "--country", country,
+        "--manifest-uri", build.manifest_uri,
+        "--model-version", model_version,
+        "--core-version", core_version,
+        "--work-dir", str(work_dir),
+        "--output", str(record),
+    ]  # fmt: skip
+
+
+#: The most names of each kind a check summary lists.
+SUMMARY_NAMES = 10
+
+
+def check_summary(record: Mapping[str, Any]) -> str:
+    """What a passed check found, from its record: the inputs that take
+    defaults, the stored columns no model reads, and the sample it ran."""
+
+    def names(values: Sequence[str]) -> str:
+        shown = ", ".join(f"`{value}`" for value in values[:SUMMARY_NAMES])
+        more = len(values) - SUMMARY_NAMES
+        return shown + (f" and {more} more" if more > 0 else "")
+
+    defaulted = list(record.get("defaulted_inputs") or [])
+    never_modelled = list(record.get("never_modelled_columns") or [])
+    samples = [
+        f"{artifact.get('sample_households')} of {artifact.get('households')} "
+        f"households in `{artifact.get('path')}`"
+        for artifact in (record.get("artifacts") or {}).values()
+    ]
+    if len(defaulted) == 1:
+        defaults = f"1 input takes a default ({names(defaulted)})"
+    elif defaulted:
+        defaults = f"{len(defaulted)} inputs take defaults ({names(defaulted)})"
+    else:
+        defaults = "no input takes a default"
+    if len(never_modelled) == 1:
+        unread = f"1 stored column no model reads ({names(never_modelled)})"
+    elif never_modelled:
+        unread = (
+            f"{len(never_modelled)} stored columns no model reads "
+            f"({names(never_modelled)})"
+        )
+    else:
+        unread = "the model reads every stored column"
+    return (
+        f"passed; no stored column dropped; {defaults}; {unread}"
+        + (f"; ran {'; '.join(samples)}" if samples else "")
+        + "."
+    )
+
+
+def certify(
+    args: argparse.Namespace,
+    *,
+    hub: Optional[Hub] = None,
+    shell_factory: Any = Shell,
+    repo: Path = REPO_ROOT,
+) -> int:
+    hub = Hub(hub_token()) if hub is None else hub
+    country = args.country
+    build_repo = MICROCOSM_RELEASE_REPOS[country]
+    model_package = COUNTRY_MODEL_PACKAGES[country]
+
+    if args.in_place:
+        checkout = repo
+        changed = tracked_changes(checkout)
+        if changed:
+            raise CertifyError(
+                "--in-place needs a checkout with no changes to tracked files: "
+                + ", ".join(changed)
+            )
+        base_commit = git(checkout, "rev-parse", "HEAD").strip()
+    else:
+        base_ref = args.base_ref
+        if base_ref.startswith("origin/"):
+            remote_branch = base_ref.removeprefix("origin/")
+            subprocess.run(
+                ["git", "fetch", "--quiet", "origin",
+                 f"+refs/heads/{remote_branch}:refs/remotes/origin/{remote_branch}"],
+                cwd=repo,
+                check=True,
+                timeout=300,
+            )  # fmt: skip
+        base_commit = git(
+            repo, "rev-parse", "--verify", f"{base_ref}^{{commit}}"
+        ).strip()
+        checkout = Path()  # set once the branch is named
+    old_bundle = json.loads(git(repo, "show", f"{base_commit}:{BUNDLE_MANIFEST}"))
+    record = old_bundle["data_releases"][country]
+    old_national = pinned_national(record, build_repo)
+    old_local_area = pinned_local_area(record, build_repo)
+
+    national = read_published_build(
+        hub,
+        country,
+        default_release(args.national_release, old_national, "--national-release"),
+        args.national_build,
+        commit=args.national_data_commit,
+    )
+    model = args.model_version or national.model
+    model_label = f"{model_package} {model}"
+    pinned_core = (
+        (old_bundle.get("packages") or {}).get("policyengine-core") or {}
+    ).get("version")
+    core = args.core_version or pinned_core or national.core
+    core_binding = "certified" if args.core_version else "bundle_pin"
+
+    local_area: Optional[PublishedBuild] = None
+    if args.local_area_build:
+        local_area = read_published_build(
+            hub,
+            country,
+            default_release(
+                args.local_area_release, old_local_area, "--local-area-release"
+            ),
+            args.local_area_build,
+            commit=args.local_area_data_commit,
+        )
+    elif args.keep_regional_release:
+        if old_local_area is None:
+            raise CertifyError(
+                "the bundle routes regions to no local-area build in its own "
+                f"folder in {build_repo}; name one with --local-area-build, or "
+                "pass --drop-regional-release."
+            )
+        local_area = read_published_build(
+            hub,
+            country,
+            old_local_area.release,
+            old_local_area.build,
+            commit=old_local_area.commit,
+        )
+    if local_area is None:
+        regional_flags = ["--drop-regional-release"]
+        regional_summary = "no local-area build (`--drop-regional-release`)"
+    else:
+        regional_flags = ["--regional-manifest-uri", local_area.manifest_uri]
+        regional_summary = (
+            f"local-area build `{local_area.build}` at commit `{local_area.commit}`"
+        )
+
+    branch = branch_name(country, national.build, model_label)
+    if not args.in_place:
+        checkout = args.worktree or (
+            repo.parent / "_worktrees" / f"pepy-{branch.replace('/', '-')}"
+        )
+        if checkout.exists():
+            raise CertifyError(f"{checkout} exists; choose another --worktree.")
+    output_dir = args.output_dir or checkout.parent
+    log = output_dir / f"{checkout.name}.certify.log"
+    # The check downloads the builds' files here, so the disk check is here.
+    work_dir = output_dir / f"{checkout.name}.compatibility"
+
+    if args.skip_writer_check:
+        print(f"writer check skipped: {args.skip_writer_check}")
+    elif not args.in_place:
+        others = writer_check(repo, branch, national.build, model_label)
+        if others:
+            raise CertifyError(
+                "this build is already being certified for this model version: "
+                + "; ".join(others)
+                + ". Work on that pull request instead of opening a second one."
+            )
+
+    needed = (
+        national.folder_bytes
+        + (local_area.folder_bytes if local_area else 0)
+        + DISK_MARGIN_BYTES
+    )
+    free = check_free_disk(work_dir, needed)
+
+    plan = {
+        "country": country,
+        "base_commit": base_commit,
+        "national": national.manifest_uri,
+        "local_area": None if local_area is None else local_area.manifest_uri,
+        "model": model_label,
+        "core": core,
+        "core_binding": core_binding,
+        "checkout": str(checkout),
+        "branch": None if args.in_place else branch,
+        "free_bytes": free,
+        "needed_bytes": needed,
+    }
+    print(json.dumps(plan, indent=2))
+    if args.dry_run:
+        return 0
+    output_dir.mkdir(parents=True, exist_ok=True)
+
+    if not args.in_place:
+        subprocess.run(
+            ["git", "worktree", "add", "--quiet", "-b", branch, str(checkout),
+             base_commit],
+            cwd=repo,
+            check=True,
+        )  # fmt: skip
+    run = shell_factory(checkout, log)
+    python = str(checkout / ".venv/bin/python")
+    sync = ["uv", "sync", "--frozen", "--extra", country, "--extra", "dev",
+            "--python", PEPY_PYTHON]  # fmt: skip
+    run(sync, step="sync", credentials=False)
+
+    # The check runs for every build. A build made with another model version
+    # is certified on its record; certify-data refuses a record for a build
+    # made with this one.
+    checks = []
+    record_flags: list[str] = []
+    for build, flag in (
+        (national, "--compatibility-record"),
+        (local_area, "--regional-compatibility-record"),
+    ):
+        if build is None:
+            continue
+        record_path = work_dir / f"{build.build}.record.json"
+        # An earlier run's record must not stand in for this check.
+        record_path.unlink(missing_ok=True)
+        run(
+            compatibility_check_argv(
+                python, country, build, model, core, work_dir, record_path
+            ),
+            step=f"compatibility check of {build.build}",
+        )
+        try:
+            record_document = json.loads(record_path.read_text())
+        except (OSError, ValueError) as error:
+            raise CertifyError(
+                f"the compatibility check of {build.build} wrote no readable "
+                f"record at {record_path}."
+            ) from error
+        checks.append({"build": build.build, "summary": check_summary(record_document)})
+        if build.model != model:
+            record_flags += [flag, str(record_path)]
+
+    certify_result = run(
+        [
+            python, "scripts/bundle.py", "certify-data", "--country", country,
+            "--data-producer", "populace",
+            "--manifest-uri", national.manifest_uri,
+            *regional_flags,
+            "--model-version", model,
+            *record_flags,
+            *(["--core-version", core] if args.core_version else []),
+        ],
+        step="certify-data",
+    )  # fmt: skip
+    warnings = [
+        line.strip()
+        for line in certify_result.stdout.splitlines()
+        if "warning" in line.lower()
+    ]
+    run(
+        ["uv", "lock", "--no-config", "--no-sources", "--default-index",
+         "https://pypi.org/simple", "--python", python],
+        step="lock",
+        credentials=False,
+    )  # fmt: skip
+    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="generate")
+
+    new_bundle = json.loads((checkout / BUNDLE_MANIFEST).read_text())
+    new_record = new_bundle["data_releases"][country]
+    new_local_area = None if local_area is None else local_area.pin
+    shared_old_commit = shared_local_area_commit(
+        record, new_record, old_local_area, new_local_area
+    )
+    constants = rewrite_constants(
+        checkout,
+        constant_replacements(record, new_record, old_local_area, new_local_area),
+    )
+    run(
+        [python, "-m", "pytest", "tests/test_household_calculator_snapshot.py", "-q"],
+        env={"PE_UPDATE_SNAPSHOTS": "1"},
+        step="household snapshots",
+    )
+    run(
+        [python, "scripts/bundle.py", "check", "--published-spm", "--include-tros",
+         "--strict-tros"],
+        step="strict check",
+    )  # fmt: skip
+
+    uc_passed: Optional[bool] = None
+    uc_summary = None
+    if country == "uk":
+        receipt_path = output_dir / f"{checkout.name}.uc_floor.json"
+        # An earlier run's receipt must not stand in for this one.
+        receipt_path.unlink(missing_ok=True)
+        uc_floor = run(
+            [python, "scripts/check_uk_uc_floor.py", "--dataset",
+             new_record["default_dataset"], "--output", str(receipt_path)],
+            check=False,
+            step="Universal Credit floor",
+            env={"POLICYENGINE_SKIP_COUNTRY_IMPORTS": "1"},
+        )  # fmt: skip
+        if not receipt_path.exists():
+            raise CertifyError(
+                f"the Universal Credit floor check did not run (exit "
+                f"{uc_floor.returncode}) and wrote no receipt; see {log}."
+            )
+        try:
+            receipt = json.loads(receipt_path.read_text())
+        except json.JSONDecodeError as error:
+            raise CertifyError(
+                "the Universal Credit floor check wrote an unreadable receipt."
+            ) from error
+        uc_passed, uc_summary = uc_floor_summary(receipt)
+        if uc_floor.returncode != (0 if uc_passed else 1):
+            raise CertifyError(
+                f"the Universal Credit floor check exited {uc_floor.returncode}, "
+                "which disagrees with its receipt."
+            )
+
+    context = {
+        "country": country,
+        "national_build": national.build,
+        "national_commit": national.commit,
+        "local_area": local_area,
+        "model_label": model_label,
+        "core": core,
+        "core_binding": core_binding,
+        "regional_summary": regional_summary,
+        "basis": (new_record.get("certification") or {}).get("compatibility_basis"),
+        "base_commit": base_commit,
+        "checks": checks,
+        "commands": run.public_commands(),
+        "uc_floor": None if uc_summary is None else f"`{uc_summary}`",
+        "uc_floor_passed": uc_passed,
+        "constants": ", ".join(constants),
+        "shared_old_commit": shared_old_commit,
+        "dropped_overlays": dropped_overlays(country, old_bundle, new_bundle),
+        "warnings": warnings,
+        "footer": args.pr_body_footer,
+    }
+    body = output_dir / f"{checkout.name}.pr-body.md"
+    body.write_text(pr_body(context))
+    paths = certification_changes(checkout, country, national.build)
+    if args.in_place:
+        changed_paths = output_dir / f"{checkout.name}.changed-paths.txt"
+        changed_paths.write_text("".join(f"{changed}\n" for changed in paths))
+        print(
+            f"\nchanged in {checkout}: {', '.join(paths)}; listed in {changed_paths}; "
+            f"pull request body: {body}"
+        )
+        return 0
+    title = pull_request_title(country, national.build, model_label)
+    if paths:
+        run(["git", "add", "--", *paths], step="stage")
+    run(
+        ["git", "commit", "-q", "-m", commit_message(title, co_authors=args.co_author)],
+        step="commit",
+    )
+    print(f"\ncommitted on {branch} in {checkout}; pull request body: {body}")
+    if args.push:
+        run(["git", "push", "-u", "origin", branch], step="push")
+    if args.open_pr:
+        run(
+            ["gh", "pr", "create", "--draft", "--repo", PEPY_REPO, "--base", "main",
+             "--head", branch, "--title", title, "--body-file", str(body)],
+            step="pull request",
+        )  # fmt: skip
+    return 0
+
+
+def run_command(args: argparse.Namespace) -> int:
+    try:
+        return certify(args)
+    except CertifyError as error:
+        print(f"REFUSED: {error}", file=sys.stderr)
+        return 2
+
+
+def main(argv: Optional[Sequence[str]] = None) -> int:
+    return run_command(parse(argv))
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

From 79d5d6acfd99710f9e8d6fc3822fb71972b66768 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 00:09:44 +0400
Subject: [PATCH 11/25] Fix the type errors mypy finds in the certification
 script

Co-Authored-By: Claude Opus 5.5 
---
 scripts/certify_build.py | 37 ++++++++++++++++++++++++-------------
 1 file changed, 24 insertions(+), 13 deletions(-)

diff --git a/scripts/certify_build.py b/scripts/certify_build.py
index fb4bf100..5296f4fb 100644
--- a/scripts/certify_build.py
+++ b/scripts/certify_build.py
@@ -61,7 +61,7 @@
 import subprocess
 import sys
 import time
-from collections.abc import Mapping, Sequence
+from collections.abc import Callable, Mapping, Sequence
 from dataclasses import dataclass
 from pathlib import Path
 from typing import Any, NamedTuple, Optional
@@ -221,7 +221,10 @@ def _answer(self, method: str, url: str, what: str, **kwargs: Any) -> Any:
 
     def file(self, repo: str, path: str, revision: str) -> bytes:
         url = f"{HUB}/datasets/{repo}/resolve/{revision}/{path}"
-        return self._answer("get", url, f"{path} at {revision} in {repo}").content
+        content: bytes = self._answer(
+            "get", url, f"{path} at {revision} in {repo}"
+        ).content
+        return content
 
     def last_commit(self, repo: str, path: str) -> str:
         """The last commit of ``path`` on ``main``."""
@@ -633,13 +636,15 @@ def constant_replacements(
     """
 
     old, new = certified_values(old_record), certified_values(new_record)
-    pairs = [
-        (old[key], new[key])
-        for key in ("build_id", "revision", "model", "built_with", "data")
-        if old[key] and new[key] and old[key] != new[key]
-    ]
+    pairs: list[tuple[str, str]] = []
+    for key in ("build_id", "revision", "model", "built_with", "data"):
+        before, after = old[key], new[key]
+        if before and after and before != after:
+            pairs.append((before, after))
     if old_local_area is not None and new_local_area is not None:
-        national_commits = {old["revision"], new["revision"]}
+        national_commits = {
+            commit for commit in (old["revision"], new["revision"]) if commit
+        }
         if old_local_area.build != new_local_area.build:
             pairs.append((old_local_area.build, new_local_area.build))
         if (
@@ -648,7 +653,7 @@ def constant_replacements(
         ):
             pairs.append((old_local_area.commit, new_local_area.commit))
     seen: set[str] = set()
-    unique = []
+    unique: list[tuple[str, str]] = []
     for before, after in pairs:
         if before not in seen:
             seen.add(before)
@@ -656,6 +661,15 @@ def constant_replacements(
     return unique
 
 
+def _keep_quotes_around(after: str) -> Callable[[re.Match[str]], str]:
+    """A substitution that puts ``after`` between the matched delimiters."""
+
+    def substitute(match: re.Match[str]) -> str:
+        return match["pre"] + after + match["post"]
+
+    return substitute
+
+
 def rewrite_constants(
     checkout: Path, replacements: Sequence[tuple[str, str]]
 ) -> list[str]:
@@ -670,10 +684,7 @@ def rewrite_constants(
         text = updated = path.read_text()
         for before, after in replacements:
             pattern = re.compile(CONSTANT_PATTERN.format(old=re.escape(before)))
-            updated = pattern.sub(
-                lambda match, after=after: match["pre"] + after + match["post"],
-                updated,
-            )
+            updated = pattern.sub(_keep_quotes_around(after), updated)
         if updated != text:
             path.write_text(updated)
             changed.append(relative)

From ef4da45d509f8bd7d6eb51d5254fec5ac792eded Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 00:28:07 +0400
Subject: [PATCH 12/25] Add failing tests for round 1 review findings

Tests for: the US region and model pins a US certification must move;
a kept local-area build on the old national commit; values the other
country also certifies; the core a compatibility record binds the
certificate to, and a build without a record outside it; a branch left
by a failed run; command failures and Hub answers that are not JSON as
refusals; relative paths; --pr-base; and importing the script without
the country models.

Co-Authored-By: Claude Opus 5.5 
---
 tests/test_certify_build.py | 318 +++++++++++++++++++++++++++++++++++-
 1 file changed, 314 insertions(+), 4 deletions(-)

diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py
index b2daf264..8ea45019 100644
--- a/tests/test_certify_build.py
+++ b/tests/test_certify_build.py
@@ -5,6 +5,7 @@
 
 import importlib.util
 import json
+import os
 import subprocess
 import sys
 from pathlib import Path
@@ -84,7 +85,11 @@ def releases_record(release, build, *, withdrawn=False, current=None):
     }
 
 
-def folder_manifest(release, build, *, model="2.200.0", core="3.36.1"):
+#: The bundle's policyengine-core pin, which the fake builds were made with.
+BUNDLE_CORE = BUNDLE["packages"]["policyengine-core"]["version"]
+
+
+def folder_manifest(release, build, *, model="2.200.0", core=BUNDLE_CORE):
     return {
         "schema_version": 1,
         "data_package": {"name": "microcosm-data", "version": "0.1.0"},
@@ -109,11 +114,19 @@ def __init__(self, repo):
         self.sizes = {}
 
     def add_build(
-        self, release, build, commit, *, model="2.200.0", size=1000, manifest=None
+        self,
+        release,
+        build,
+        commit,
+        *,
+        model="2.200.0",
+        core=BUNDLE_CORE,
+        size=1000,
+        manifest=None,
     ):
         path = f"releases/{release}/{build}/release_manifest.json"
         self.files[(path, commit)] = manifest or folder_manifest(
-            release, build, model=model
+            release, build, model=model, core=core
         )
         self.last_commits[path] = commit
         self.sizes[(f"releases/{release}/{build}", commit)] = size
@@ -621,7 +634,9 @@ def public_commands(self, home=None):
 
     def __call__(self, argv, *, step, env=None, check=True, credentials=True):
         self.argvs.append(list(argv))
-        if argv[0] == "git":
+        if argv[:2] == ["git", "push"]:
+            pass
+        elif argv[0] == "git":
             subprocess.run(argv, cwd=self.cwd, check=True)
         elif "certify-data" in argv:
             bundle_path = self.cwd / "src/policyengine/data/bundle/manifest.json"
@@ -632,6 +647,19 @@ def __call__(self, argv, *, step, env=None, check=True, credentials=True):
             record["certification"]["compatibility_basis"] = (
                 "compatibility_checked_exact_pair"
             )
+            # Like certify-data: a named core, or a record's, binds the
+            # certificate to that core.
+            if "--core-version" in argv:
+                bound = argv[argv.index("--core-version") + 1]
+            elif {"--compatibility-record", "--regional-compatibility-record"} & set(
+                argv
+            ):
+                bound = BUNDLE_CORE
+            else:
+                bound = None
+            if bound is not None:
+                record["certification"]["core_binding"] = "certified"
+                record["certification"]["certified_for_core_version"] = bound
             bundle_path.write_text(json.dumps(bundle))
             (self.cwd / "changelog.d").mkdir(exist_ok=True)
             (self.cwd / f"changelog.d/certify-{country}-nat-b1.changed.md").write_text(
@@ -901,3 +929,285 @@ def test_in_place_run_refuses_a_checkout_with_changed_files(certify_build, tmp_p
 
     with pytest.raises(certify_build.CertifyError, match="no changes to tracked files"):
         certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+
+
+# --- Cores, constants and failures -------------------------------------------
+
+
+def test_us_certification_rewrites_the_us_region_and_model_pins(
+    certify_build, tmp_path
+):
+    old = record_for("nat-old", COMMIT_A, "2.2.2", "2.2.1")
+    new = record_for("nat-new", COMMIT_C, "2.3.0", "2.3.0")
+    old_local = certify_build.BuildPin("loc", "loc-old", COMMIT_B)
+    new_local = certify_build.BuildPin("loc", "loc-new", "d" * 40)
+    (tmp_path / "tests").mkdir()
+    (tmp_path / "tests/test_us_regions.py").write_text(
+        f'LOCAL = ("releases/loc/" "loc-old/" "x.h5@{COMMIT_B}")\n'
+        f'NATIONAL = ("releases/nat/" "nat-old/x.h5" "@{COMMIT_A}")\n'
+    )
+    (tmp_path / "tests/test_spm_bundle_tooling.py").write_text(
+        'assert version == "2.2.2"\n'
+    )
+
+    changed = certify_build.rewrite_constants(
+        tmp_path, certify_build.constant_replacements(old, new, old_local, new_local)
+    )
+
+    assert changed == ["tests/test_spm_bundle_tooling.py", "tests/test_us_regions.py"]
+    assert (tmp_path / "tests/test_us_regions.py").read_text() == (
+        f'LOCAL = ("releases/loc/" "loc-new/" "x.h5@{"d" * 40}")\n'
+        f'NATIONAL = ("releases/nat/" "nat-new/x.h5" "@{COMMIT_C}")\n'
+    )
+    assert (tmp_path / "tests/test_spm_bundle_tooling.py").read_text() == (
+        'assert version == "2.3.0"\n'
+    )
+    for relative in changed:
+        assert certify_build.certification_path(relative, "us", "nat-new")
+
+
+def test_kept_local_area_build_on_the_old_national_commit_is_left_to_a_person(
+    certify_build,
+):
+    old = record_for("nat-old", COMMIT_A, "2.199.0", "2.199.0")
+    new = record_for("nat-new", COMMIT_C, "2.200.0", "2.200.0")
+    kept = certify_build.BuildPin("loc", "loc-b1", COMMIT_A)
+
+    assert certify_build.shared_local_area_commit(old, new, kept, kept) == COMMIT_A
+
+
+def test_values_shared_with_the_other_country_are_left_to_a_person(certify_build):
+    split = getattr(certify_build, "split_shared_values", None)
+    shared_values = getattr(certify_build, "other_country_values", None)
+    assert split is not None and shared_values is not None, (
+        "no way to hold back values another country also certifies"
+    )
+    uk_values = shared_values(BUNDLE, "us")
+
+    kept, held = split([("0.1.0", "0.2.0"), ("nat-old", "nat-new")], uk_values)
+
+    assert BUNDLE["data_releases"]["uk"]["data_package"]["version"] in uk_values
+    assert BUNDLE["data_releases"]["uk"]["model_package"]["version"] in uk_values
+    assert kept == [("nat-old", "nat-new")]
+    assert held == [("0.1.0", "0.2.0")]
+    body = certify_build.pr_body(body_context("us", held_constants=held))
+    assert "- [ ] **Constants another country shares.**" in body
+    assert "`0.1.0` (now `0.2.0`)" in body
+
+
+def test_certificate_bound_to_the_checked_core_is_reported_as_certified(
+    certify_build, monkeypatch, tmp_path
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, _ = hub_for(certify_build, "us")
+    args = certify_build.parse(
+        ["--country", "us", "--national-build", "nat-b1", "--local-area-build",
+         "loc-b1", "--model-version", "2.201.0", "--in-place",
+         "--output-dir", str(tmp_path / "out")]
+    )  # fmt: skip
+
+    certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+
+    body = (tmp_path / "out" / "py.pr-body.md").read_text()
+    assert f"policyengine-core {BUNDLE_CORE} (`core_binding: certified`)" in body
+
+
+def test_build_without_a_record_outside_the_bound_core_is_refused_first(
+    certify_build, monkeypatch, tmp_path
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, session = hub_for(certify_build, "us")
+    session.add_build(RELEASES["us"][0], "nat-b1", COMMIT_A, core="3.32.5")
+    args = certify_build.parse(
+        ["--country", "us", "--national-build", "nat-b1", "--local-area-build",
+         "loc-b1", "--in-place", "--output-dir", str(tmp_path / "out")]
+    )  # fmt: skip
+    FakeShell.runs = []
+
+    with pytest.raises(Exception) as raised:
+        certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+
+    assert raised.type is certify_build.CertifyError
+    assert "--core-version 3.32.5" in str(raised.value)
+    assert FakeShell.runs == []
+
+
+def test_existing_local_branch_is_refused_before_the_worktree(
+    certify_build, monkeypatch, tmp_path
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    branch = "certify/uk/nat-b1/policyengine-uk-2.200.0"
+    subprocess.run(["git", "branch", branch], cwd=checkout, check=True)
+    hub, _ = hub_for(certify_build, "uk")
+    worktree = tmp_path / "second-try"
+    args = certify_build.parse(
+        ["--country", "uk", "--national-build", "nat-b1", "--drop-regional-release",
+         "--base-ref", "HEAD", "--worktree", str(worktree), "--skip-writer-check",
+         "testing"]
+    )  # fmt: skip
+
+    with pytest.raises(Exception) as raised:
+        certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+
+    assert raised.type is certify_build.CertifyError
+    assert f"git branch -D {branch}" in str(raised.value)
+    assert not worktree.exists()
+
+
+def test_failed_step_names_the_commands_that_clean_up(
+    certify_build, monkeypatch, tmp_path
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, _ = hub_for(certify_build, "uk")
+    worktree = tmp_path / "certify-worktree"
+    args = certify_build.parse(
+        ["--country", "uk", "--national-build", "nat-b1", "--drop-regional-release",
+         "--base-ref", "HEAD", "--worktree", str(worktree), "--skip-writer-check",
+         "testing"]
+    )  # fmt: skip
+
+    class StepFails(FakeShell):
+        """Fails at certify-data, as a real step can."""
+
+        def __call__(self, argv, **kwargs):
+            if "certify-data" in argv:
+                raise certify_build.CertifyError("certify-data exited 1")
+            return super().__call__(argv, **kwargs)
+
+    with pytest.raises(certify_build.CertifyError) as raised:
+        certify_build.certify(args, hub=hub, shell_factory=StepFails, repo=checkout)
+
+    message = str(raised.value)
+    assert message.startswith("certify-data exited 1")
+    assert f"git worktree remove --force {worktree}" in message
+    assert "git branch -D certify/uk/nat-b1/policyengine-uk-2.200.0" in message
+
+
+@pytest.mark.parametrize(
+    "failure",
+    [
+        subprocess.CalledProcessError(128, ["git", "fetch"]),
+        subprocess.TimeoutExpired(["gh", "pr", "list"], 60),
+        FileNotFoundError(2, "No such file or directory", "uv"),
+    ],
+    ids=["exit", "timeout", "missing-program"],
+)
+def test_command_failures_are_refusals(certify_build, monkeypatch, capsys, failure):
+    def fails(args, **kwargs):
+        raise failure
+
+    monkeypatch.setattr(certify_build, "certify", fails)
+    args = certify_build.parse(BASE_ARGUMENTS + ["--drop-regional-release"])
+
+    try:
+        code = certify_build.run_command(args)
+    except Exception as error:  # the failure escaped
+        code = error
+
+    assert code == 2
+    assert capsys.readouterr().err.startswith("REFUSED: ")
+
+
+class NotJsonAnswer:
+    status_code = 200
+    content = b"busy"
+    links: dict = {}
+
+    def json(self):
+        raise ValueError("Expecting value: line 1 column 1 (char 0)")
+
+
+class NotJsonSession:
+    def get(self, url, headers=None, timeout=None):
+        return NotJsonAnswer()
+
+    def post(self, url, headers=None, timeout=None, data=None):
+        return NotJsonAnswer()
+
+
+@pytest.mark.parametrize(
+    "read",
+    [
+        lambda hub: hub.commit_on_main(REPOS["us"], COMMIT_A),
+        lambda hub: hub.folder_bytes(REPOS["us"], "releases/r/b", COMMIT_A),
+        lambda hub: hub.last_commit(REPOS["us"], "releases/r/b/release_manifest.json"),
+    ],
+    ids=["history", "folder", "publishing-commit"],
+)
+def test_hub_answer_that_is_not_json_is_refused(certify_build, read):
+    hub = certify_build.Hub(token=None, session=NotJsonSession())
+
+    with pytest.raises(Exception) as raised:
+        read(hub)
+
+    assert raised.type is certify_build.CertifyError
+    assert "not JSON" in str(raised.value)
+
+
+def test_relative_paths_are_read_from_where_the_command_runs(
+    certify_build, monkeypatch, tmp_path
+):
+    monkeypatch.chdir(tmp_path)
+
+    args = certify_build.parse(
+        BASE_ARGUMENTS
+        + ["--drop-regional-release", "--worktree", "wt", "--output-dir", "out"]
+    )
+
+    assert args.worktree == (tmp_path / "wt").resolve()
+    assert args.output_dir == (tmp_path / "out").resolve()
+
+
+def test_pull_request_opens_against_the_named_base(
+    certify_build, monkeypatch, tmp_path
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, _ = hub_for(certify_build, "uk")
+    try:
+        args = certify_build.parse(
+            ["--country", "uk", "--national-build", "nat-b1",
+             "--drop-regional-release", "--base-ref", "HEAD", "--worktree",
+             str(tmp_path / "certify-worktree"), "--skip-writer-check", "testing",
+             "--push", "--open-pr", "--pr-base", "claude/earlier-change"]
+        )  # fmt: skip
+    except SystemExit:
+        args = None
+    assert args is not None, "certify-build has no --pr-base"
+
+    certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+
+    opened = next(argv for argv in FakeShell.runs if argv[:3] == ["gh", "pr", "create"])
+    assert opened[opened.index("--base") + 1] == "claude/earlier-change"
+
+
+def test_importing_the_script_skips_the_country_models_only_while_importing():
+    environment = {
+        key: value
+        for key, value in os.environ.items()
+        if key != "POLICYENGINE_SKIP_COUNTRY_IMPORTS"
+    }
+    probe = (
+        "import importlib.util, os, sys\n"
+        f"spec = importlib.util.spec_from_file_location('probe', {str(SCRIPT)!r})\n"
+        "module = importlib.util.module_from_spec(spec)\n"
+        "sys.modules['probe'] = module\n"
+        "spec.loader.exec_module(module)\n"
+        "import policyengine\n"
+        "print(policyengine._SKIP_COUNTRY_IMPORTS,"
+        " 'POLICYENGINE_SKIP_COUNTRY_IMPORTS' in os.environ)\n"
+    )
+
+    answer = subprocess.run(
+        [sys.executable, "-c", probe],
+        env=environment,
+        capture_output=True,
+        text=True,
+        check=True,
+    ).stdout.split()
+
+    assert answer == ["True", "False"]

From ff8ee1288ae734733abe51af6e29a4b956951ecf Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 00:30:08 +0400
Subject: [PATCH 13/25] Fix round 1 review findings in the certification
 command

- A US run now rewrites the US region test pins and the bundle tooling
  test's model version, not only the UK script's three test files.
- A compatibility record binds the certificate to the core the check
  ran, as certify-data does: the plan and body now report that binding,
  read from the new certificate, and a build without a record that was
  not made with that core and does not claim it is refused before any
  worktree or download, naming --core-version.
- A kept local-area build on the old national commit, and any value the
  other country also certifies, is left to a person in the body instead
  of being rewritten.
- A branch left by an earlier run is refused before the worktree, a
  failed run names the commands that remove what it made, and failures
  of the programs it runs, and Hub answers that are not JSON, are
  refusals (exit 2) instead of tracebacks.
- Relative --worktree and --output-dir paths are read where the command
  runs; --pr-base is back from the UK script; importing the script no
  longer loads the country models.

Co-Authored-By: Claude Opus 5.5 
---
 scripts/certify_build.py | 261 +++++++++++++++++++++++++++++++++------
 1 file changed, 225 insertions(+), 36 deletions(-)

diff --git a/scripts/certify_build.py b/scripts/certify_build.py
index 5296f4fb..8fc0cf6d 100644
--- a/scripts/certify_build.py
+++ b/scripts/certify_build.py
@@ -22,7 +22,8 @@
 7. for the UK, the Universal Credit floor (weighted national totals);
 8. a commit on a new branch in a new worktree, and a pull request body that
    lists every judgment left to a person. ``--push`` pushes the branch and
-   ``--open-pr`` opens a draft pull request. It never merges or releases.
+   ``--open-pr`` opens a draft pull request into ``--pr-base`` (``main``
+   unless named). It never merges or releases.
 
 ``--in-place`` changes the files of this checkout instead, and makes no
 worktree, branch or commit, for a job that commits the result itself. It
@@ -71,22 +72,35 @@
 REPO_ROOT = Path(__file__).resolve().parents[1]
 sys.path.insert(0, str(REPO_ROOT / "src"))
 
-from policyengine.provenance.certification import (  # noqa: E402
-    COUNTRY_MODEL_PACKAGES,
-    MICROCOSM_RELEASE_REPOS,
-)
-from policyengine.provenance.manifest import (  # noqa: E402
-    HF_REQUEST_TIMEOUT_SECONDS,
-    RELEASE_FOLDER_NAME,
-    RELEASE_MANIFEST_NAME,
-    RELEASES_FOLDER,
-    RELEASES_RECORD_NAME,
-    RELEASES_RECORD_REVISION,
-    DataReleaseManifest,
-    ReleaseBuildFolderError,
-    check_build_listed,
-    release_build_id,
-)
+# This process reads builds and runs .py's commands, and needs no country
+# model, so it skips them while importing .py. The setting is read once, at
+# that import, and is put back as it was for the commands this process runs.
+_SKIP_COUNTRY_IMPORTS = "POLICYENGINE_SKIP_COUNTRY_IMPORTS"
+_caller_skip_setting = os.environ.get(_SKIP_COUNTRY_IMPORTS)
+os.environ[_SKIP_COUNTRY_IMPORTS] = "1"
+try:
+    from policyengine.provenance.certification import (  # noqa: E402
+        COUNTRY_MODEL_PACKAGES,
+        MICROCOSM_RELEASE_REPOS,
+        core_claim_warning,
+    )
+    from policyengine.provenance.manifest import (  # noqa: E402
+        HF_REQUEST_TIMEOUT_SECONDS,
+        RELEASE_FOLDER_NAME,
+        RELEASE_MANIFEST_NAME,
+        RELEASES_FOLDER,
+        RELEASES_RECORD_NAME,
+        RELEASES_RECORD_REVISION,
+        DataReleaseManifest,
+        ReleaseBuildFolderError,
+        check_build_listed,
+        release_build_id,
+    )
+finally:
+    if _caller_skip_setting is None:
+        os.environ.pop(_SKIP_COUNTRY_IMPORTS, None)
+    else:
+        os.environ[_SKIP_COUNTRY_IMPORTS] = _caller_skip_setting
 
 PEPY_REPO = "PolicyEngine/policyengine.py"
 #: The interpreter the certified environment is made with.
@@ -102,7 +116,9 @@
 CONSTANT_FILES = (
     "tests/test_models.py",
     "tests/test_release_manifests.py",
+    "tests/test_spm_bundle_tooling.py",
     "tests/test_uk_regions.py",
+    "tests/test_us_regions.py",
 )
 #: A quoted certified value: ``"2.125.1"``, ``"@"``, ``"//"``.
 CONSTANT_PATTERN = r'(?P
["@/-]){old}(?P["/])'
@@ -179,6 +195,7 @@ class PublishedBuild:
     model: str
     core: str
     folder_bytes: int
+    manifest: DataReleaseManifest
 
     @property
     def pin(self) -> BuildPin:
@@ -219,6 +236,13 @@ def _answer(self, method: str, url: str, what: str, **kwargs: Any) -> Any:
             )
         return response
 
+    @staticmethod
+    def _json(response: Any, what: str) -> Any:
+        try:
+            return response.json()
+        except ValueError as error:
+            raise CertifyError(f"the Hub's answer for {what} is not JSON.") from error
+
     def file(self, repo: str, path: str, revision: str) -> bytes:
         url = f"{HUB}/datasets/{repo}/resolve/{revision}/{path}"
         content: bytes = self._answer(
@@ -230,12 +254,11 @@ def last_commit(self, repo: str, path: str) -> str:
         """The last commit of ``path`` on ``main``."""
 
         url = f"{HUB}/api/datasets/{repo}/paths-info/{RELEASES_RECORD_REVISION}"
-        entries = self._answer(
-            "post",
-            url,
-            f"which commit published {path} in {repo}",
-            data={"paths": path, "expand": "true"},
-        ).json()
+        what = f"which commit published {path} in {repo}"
+        entries = self._json(
+            self._answer("post", url, what, data={"paths": path, "expand": "true"}),
+            what,
+        )
         for entry in entries if isinstance(entries, list) else ():
             commit = (entry.get("lastCommit") or {}).get("id")
             if entry.get("path") == path and COMMIT_PATTERN.match(str(commit or "")):
@@ -252,8 +275,9 @@ def commit_on_main(self, repo: str, commit: str) -> bool:
             f"{HUB}/api/datasets/{repo}/commits/{RELEASES_RECORD_REVISION}"
         )
         while url:
-            response = self._answer("get", url, f"main's history in {repo}")
-            if any(entry.get("id") == commit for entry in response.json()):
+            what = f"main's history in {repo}"
+            response = self._answer("get", url, what)
+            if any(entry.get("id") == commit for entry in self._json(response, what)):
                 return True
             url = (getattr(response, "links", None) or {}).get("next", {}).get("url")
         return False
@@ -264,10 +288,11 @@ def folder_bytes(self, repo: str, folder: str, revision: str) -> int:
         url: Optional[str] = f"{HUB}/api/datasets/{repo}/tree/{revision}/{folder}"
         total = 0
         while url:
-            response = self._answer("get", url, f"the files of {folder} in {repo}")
+            what = f"the files of {folder} in {repo}"
+            response = self._answer("get", url, what)
             total += sum(
                 int(entry.get("size") or 0)
-                for entry in response.json()
+                for entry in self._json(response, what)
                 if entry.get("type") == "file"
             )
             url = (getattr(response, "links", None) or {}).get("next", {}).get("url")
@@ -331,6 +356,7 @@ def read_published_build(
         model=model.version,
         core=core.version,
         folder_bytes=hub.folder_bytes(repo, build_folder(release, build), commit),
+        manifest=manifest,
     )
 
 
@@ -661,6 +687,37 @@ def constant_replacements(
     return unique
 
 
+def other_country_values(bundle: Mapping[str, Any], country: str) -> set[str]:
+    """Every value the bundle certifies for the other countries: their
+    builds, commits, model and data versions and local-area builds."""
+
+    values: set[str] = set()
+    for other_country, other_record in (bundle.get("data_releases") or {}).items():
+        if other_country == country:
+            continue
+        values.update(
+            value for value in certified_values(other_record).values() if value
+        )
+        other_repo = MICROCOSM_RELEASE_REPOS.get(other_country)
+        other_local_area = (
+            pinned_local_area(other_record, other_repo) if other_repo else None
+        )
+        if other_local_area is not None:
+            values.update((other_local_area.build, other_local_area.commit))
+    return values
+
+
+def split_shared_values(
+    replacements: Sequence[tuple[str, str]], shared_values: set[str]
+) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]:
+    """The replacements to make, and those left to a person because another
+    country's constants hold the same old value."""
+
+    kept = [pair for pair in replacements if pair[0] not in shared_values]
+    held = [pair for pair in replacements if pair[0] in shared_values]
+    return kept, held
+
+
 def _keep_quotes_around(after: str) -> Callable[[re.Match[str]], str]:
     """A substitution that puts ``after`` between the matched delimiters."""
 
@@ -697,15 +754,16 @@ def shared_local_area_commit(
     old_local_area: Optional[BuildPin],
     new_local_area: Optional[BuildPin],
 ) -> Optional[str]:
-    """The old local-area commit when a rewrite cannot move it: it is also
-    the old or new national commit, and the new builds' commits differ."""
+    """The old local-area commit when a rewrite cannot tell its constants
+    from the national build's: it is also the old or new national commit, and
+    the new builds' commits differ. That holds for a kept local-area build
+    too, since moving the national commit would move its constants."""
 
     if old_local_area is None or new_local_area is None:
         return None
     old, new = certified_values(old_record), certified_values(new_record)
     if (
         old_local_area.commit in {old["revision"], new["revision"]}
-        and old_local_area.commit != new_local_area.commit
         and new_local_area.commit != new["revision"]
     ):
         return old_local_area.commit
@@ -840,6 +898,16 @@ def pr_body(context: Mapping[str, Any]) -> str:
             f"`{context['national_commit']}` and each local-area one names "
             + (f"`{regional}`." if regional else "the local-area build's commit.")
         )
+    if context.get("held_constants"):
+        needs.append(
+            "- [ ] **Constants another country shares.** The test constants "
+            "also hold these values for another country, so this command left "
+            "them unchanged; move only this country's: "
+            + ", ".join(
+                f"`{before}` (now `{after}`)"
+                for before, after in context["held_constants"]
+            )
+        )
     if context.get("dropped_overlays"):
         needs.append(
             "- [ ] **Dataset overlays dropped by certification:** "
@@ -955,6 +1023,11 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
     parser.add_argument(
         "--open-pr", action="store_true", help="open a draft pull request; needs --push"
     )
+    parser.add_argument(
+        "--pr-base",
+        default="main",
+        help="the branch the draft pull request merges into (default: main)",
+    )
     parser.add_argument("--dry-run", action="store_true", help="print the plan only")
     parser.add_argument(
         "--co-author",
@@ -979,6 +1052,7 @@ def validate(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None:
             ("--push", args.push),
             ("--co-author", bool(args.co_author)),
             ("--base-ref", args.base_ref != "origin/main"),
+            ("--pr-base", args.pr_base != "main"),
         ):
             if given:
                 parser.error(
@@ -1017,6 +1091,11 @@ def parse(argv: Optional[Sequence[str]]) -> argparse.Namespace:
     add_arguments(parser)
     args = parser.parse_args(argv)
     validate(args, parser)
+    # Commands run in the checkout, so a relative path is read here, once.
+    if args.worktree is not None:
+        args.worktree = args.worktree.resolve()
+    if args.output_dir is not None:
+        args.output_dir = args.output_dir.resolve()
     return args
 
 
@@ -1093,12 +1172,78 @@ def names(values: Sequence[str]) -> str:
     )
 
 
+#: Failures of the programs this command runs, which it reports as refusals.
+COMMAND_FAILURES = (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError)
+
+
+def describe_failure(error: BaseException) -> str:
+    """A program's failure in one sentence."""
+
+    if isinstance(error, (subprocess.CalledProcessError, subprocess.TimeoutExpired)):
+        command = error.cmd
+        shown = (
+            shlex.join(str(part) for part in command)
+            if isinstance(command, (list, tuple))
+            else str(command)
+        )
+        if isinstance(error, subprocess.TimeoutExpired):
+            return f"`{shown}` did not finish within {error.timeout} seconds."
+        return f"`{shown}` exited {error.returncode}."
+    if isinstance(error, CertifyError):
+        return str(error)
+    return f"could not run a program: {error}."
+
+
+def local_branch_exists(repo: Path, branch: str) -> bool:
+    return (
+        subprocess.run(
+            ["git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"],
+            cwd=repo,
+            capture_output=True,
+        ).returncode
+        == 0
+    )
+
+
 def certify(
     args: argparse.Namespace,
     *,
     hub: Optional[Hub] = None,
     shell_factory: Any = Shell,
     repo: Path = REPO_ROOT,
+) -> int:
+    """Certify the named build; see the module docstring.
+
+    A run that fails after making its worktree and branch says how to remove
+    them, since a second run needs neither to exist.
+    """
+
+    left_behind: list[str] = []
+    try:
+        return _certify(
+            args,
+            hub=hub,
+            shell_factory=shell_factory,
+            repo=repo,
+            left_behind=left_behind,
+        )
+    except (CertifyError, *COMMAND_FAILURES) as error:
+        if not left_behind:
+            raise
+        raise CertifyError(
+            f"{describe_failure(error)} This run left a worktree and a branch; "
+            f"remove them with {' and '.join(f'`{command}`' for command in left_behind)} "
+            "before running again."
+        ) from error
+
+
+def _certify(
+    args: argparse.Namespace,
+    *,
+    hub: Optional[Hub],
+    shell_factory: Any,
+    repo: Path,
+    left_behind: list[str],
 ) -> int:
     hub = Hub(hub_token()) if hub is None else hub
     country = args.country
@@ -1147,7 +1292,6 @@ def certify(
         (old_bundle.get("packages") or {}).get("policyengine-core") or {}
     ).get("version")
     core = args.core_version or pinned_core or national.core
-    core_binding = "certified" if args.core_version else "bundle_pin"
 
     local_area: Optional[PublishedBuild] = None
     if args.local_area_build:
@@ -1174,6 +1318,34 @@ def certify(
             old_local_area.build,
             commit=old_local_area.commit,
         )
+    # A build made with another model version is certified on its compatibility
+    # record. certify-data then binds the certificate to the core the check
+    # ran, as it does to a named --core-version, and refuses a build without a
+    # record that was not made with that core and does not claim it.
+    recorded = [
+        build for build in (national, local_area) if build and build.model != model
+    ]
+    bound_core = core if (args.core_version or recorded) else None
+    if bound_core is not None:
+        reason = (
+            "named by --core-version"
+            if args.core_version
+            else "the core the compatibility check runs, which its record binds "
+            "the certificate to"
+        )
+        for build in (national, local_area):
+            if build is None or build in recorded:
+                continue
+            if core_claim_warning(build.manifest, bound_core) is not None:
+                raise CertifyError(
+                    f"build {build.build} was made with policyengine-core "
+                    f"{build.core} and does not claim {bound_core}, {reason}; "
+                    f"certify-data would refuse it. Pass --core-version "
+                    f"{build.core} to check and certify on the core it was made "
+                    "with, which also moves the bundle's core pin."
+                )
+    core_binding = "certified" if bound_core is not None else "bundle_pin"
+
     if local_area is None:
         regional_flags = ["--drop-regional-release"]
         regional_summary = "no local-area build (`--drop-regional-release`)"
@@ -1190,6 +1362,13 @@ def certify(
         )
         if checkout.exists():
             raise CertifyError(f"{checkout} exists; choose another --worktree.")
+        if local_branch_exists(repo, branch):
+            raise CertifyError(
+                f"branch {branch} exists in this clone, left by an earlier run; "
+                f"remove it with `git branch -D {branch}`, and its worktree with "
+                "`git worktree remove --force ` if one remains, before "
+                "running again."
+            )
     output_dir = args.output_dir or checkout.parent
     log = output_dir / f"{checkout.name}.certify.log"
     # The check downloads the builds' files here, so the disk check is here.
@@ -1238,6 +1417,10 @@ def certify(
             cwd=repo,
             check=True,
         )  # fmt: skip
+        left_behind += [
+            f"git worktree remove --force {shlex.quote(str(checkout))}",
+            f"git branch -D {shlex.quote(branch)}",
+        ]
     run = shell_factory(checkout, log)
     python = str(checkout / ".venv/bin/python")
     sync = ["uv", "sync", "--frozen", "--extra", country, "--extra", "dev",
@@ -1304,14 +1487,19 @@ def certify(
 
     new_bundle = json.loads((checkout / BUNDLE_MANIFEST).read_text())
     new_record = new_bundle["data_releases"][country]
+    # What the certificate says, which certify-data decides.
+    new_certification = new_record.get("certification") or {}
+    core_binding = new_certification.get("core_binding") or core_binding
+    core = new_certification.get("certified_for_core_version") or core
     new_local_area = None if local_area is None else local_area.pin
     shared_old_commit = shared_local_area_commit(
         record, new_record, old_local_area, new_local_area
     )
-    constants = rewrite_constants(
-        checkout,
+    replacements, held_constants = split_shared_values(
         constant_replacements(record, new_record, old_local_area, new_local_area),
+        other_country_values(old_bundle, country),
     )
+    constants = rewrite_constants(checkout, replacements)
     run(
         [python, "-m", "pytest", "tests/test_household_calculator_snapshot.py", "-q"],
         env={"PE_UPDATE_SNAPSHOTS": "1"},
@@ -1371,6 +1559,7 @@ def certify(
         "uc_floor_passed": uc_passed,
         "constants": ", ".join(constants),
         "shared_old_commit": shared_old_commit,
+        "held_constants": held_constants,
         "dropped_overlays": dropped_overlays(country, old_bundle, new_bundle),
         "warnings": warnings,
         "footer": args.pr_body_footer,
@@ -1398,7 +1587,7 @@ def certify(
         run(["git", "push", "-u", "origin", branch], step="push")
     if args.open_pr:
         run(
-            ["gh", "pr", "create", "--draft", "--repo", PEPY_REPO, "--base", "main",
+            ["gh", "pr", "create", "--draft", "--repo", PEPY_REPO, "--base", args.pr_base,
              "--head", branch, "--title", title, "--body-file", str(body)],
             step="pull request",
         )  # fmt: skip
@@ -1408,8 +1597,8 @@ def certify(
 def run_command(args: argparse.Namespace) -> int:
     try:
         return certify(args)
-    except CertifyError as error:
-        print(f"REFUSED: {error}", file=sys.stderr)
+    except (CertifyError, *COMMAND_FAILURES) as error:
+        print(f"REFUSED: {describe_failure(error)}", file=sys.stderr)
         return 2
 
 

From c9ccf8b1ff6bbc566d61b32c9637cfef693540ec Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:07:22 +0400
Subject: [PATCH 14/25] Add failing tests for checking only builds made with
 another model

The compatibility check refuses a build made with the model version it
is asked about, and the fake check now does the same. A build made with
the target model is certified on that basis without a check, and the
free-disk check counts only the builds the check downloads.

Co-Authored-By: Claude Opus 5.5 
---
 tests/test_certify_build.py | 71 ++++++++++++++++++++++++++++++-------
 1 file changed, 58 insertions(+), 13 deletions(-)

diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py
index 8ea45019..0553ea33 100644
--- a/tests/test_certify_build.py
+++ b/tests/test_certify_build.py
@@ -105,7 +105,11 @@ def folder_manifest(release, build, *, model="2.200.0", core=BUNDLE_CORE):
 class FakeHubSession:
     """Answers the Hub's file, paths-info, commit and tree requests."""
 
+    #: The session the latest test made, which the fake check reads builds from.
+    latest = None
+
     def __init__(self, repo):
+        FakeHubSession.latest = self
         self.repo = repo
         self.files = {}
         self.records = {}
@@ -676,12 +680,31 @@ def __call__(self, argv, *, step, env=None, check=True, credentials=True):
             }
             Path(argv[argv.index("--output") + 1]).write_text(json.dumps(receipt))
         elif "check-compatibility" in argv:
+            # Like the real check: a build made with the model version it is
+            # asked about is refused (exit 1) and gets no record.
+            uri = argv[argv.index("--manifest-uri") + 1]
+            commit, path = uri.split("@", 1)[1].split("/", 1)
+            manifest = FakeHubSession.latest.files[(path, commit)]
+            built_with = manifest["built_with_model_package"]["version"]
+            if built_with == argv[argv.index("--model-version") + 1]:
+                return subprocess.CompletedProcess(argv, 1, "", "")
             record = Path(argv[argv.index("--output") + 1])
             record.parent.mkdir(parents=True, exist_ok=True)
             record.write_text(json.dumps(CHECK_RECORD))
         return subprocess.CompletedProcess(argv, 0, "", "")
 
 
+def certify_outcome(certify_build, args, hub, checkout, shell_factory=None):
+    """The exit code of a whole run, or the refusal that stopped it."""
+
+    try:
+        return certify_build.certify(
+            args, hub=hub, shell_factory=shell_factory or FakeShell, repo=checkout
+        )
+    except certify_build.CertifyError as refusal:
+        return refusal
+
+
 def bundle_checkout(tmp_path: Path) -> Path:
     checkout = git_repository(tmp_path / "py")
     bundle_path = checkout / "src/policyengine/data/bundle/manifest.json"
@@ -712,7 +735,7 @@ def step_names(runs):
 
 
 @pytest.mark.parametrize("country", ["us", "uk"])
-def test_in_place_run_checks_both_builds_then_certifies_without_committing(
+def test_in_place_run_checks_the_build_made_with_another_model_then_certifies(
     certify_build, monkeypatch, tmp_path, country
 ):
     monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
@@ -724,13 +747,13 @@ def test_in_place_run_checks_both_builds_then_certifies_without_committing(
          "--output-dir", str(tmp_path / "out")]
     )  # fmt: skip
 
-    code = certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+    code = certify_outcome(certify_build, args, hub, checkout)
 
     assert code == 0
+    # Only the local-area build was made with another model version (2.199.0).
     expected = [
         "uv sync",
         "check-compatibility",
-        "check-compatibility",
         "certify-data",
         "uv lock",
         "uv sync",
@@ -740,17 +763,16 @@ def test_in_place_run_checks_both_builds_then_certifies_without_committing(
         "check",
     ] + (["check_uk_uc_floor.py"] if country == "uk" else [])
     assert step_names(FakeShell.runs) == expected
-    checks = [argv for argv in FakeShell.runs if "check-compatibility" in argv]
-    national_uri, local_uri = (
-        argv[argv.index("--manifest-uri") + 1] for argv in checks
-    )
+    (check,) = [argv for argv in FakeShell.runs if "check-compatibility" in argv]
+    local_uri = check[check.index("--manifest-uri") + 1]
+    certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv)
+    national_uri = certify_data[certify_data.index("--manifest-uri") + 1]
     assert national_uri.endswith(
         f"@{COMMIT_A}/releases/{RELEASES[country][0]}/nat-b1/release_manifest.json"
     )
     assert local_uri.endswith(
         f"@{COMMIT_B}/releases/{RELEASES[country][1]}/loc-b1/release_manifest.json"
     )
-    certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv)
     assert certify_data[certify_data.index("--regional-manifest-uri") + 1] == local_uri
     assert certify_data[certify_data.index("--model-version") + 1] == "2.200.0"
     assert "--core-version" not in certify_data
@@ -776,7 +798,11 @@ def test_in_place_run_checks_both_builds_then_certifies_without_committing(
     ]
     body = (tmp_path / "out" / "py.pr-body.md").read_text()
     assert f"{MODEL_PACKAGES[country]} 2.200.0" in body
-    assert "`nat-b1`: passed; no stored column dropped" in body
+    assert (
+        f"`nat-b1`: made with {MODEL_PACKAGES[country]} 2.200.0, so certified on "
+        "that basis with no compatibility check." in body
+    )
+    assert "`loc-b1`: passed; no stored column dropped" in body
     assert "1 input takes a default (`is_disabled`)" in body
     assert "2000 of 20000 households in `x.h5`" in body
 
@@ -845,7 +871,7 @@ def test_worktree_run_commits_on_a_new_branch_with_the_named_co_author(
          "testing", "--co-author", "A B "]
     )  # fmt: skip
 
-    code = certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+    code = certify_outcome(certify_build, args, hub, checkout)
 
     assert code == 0
     branch = subprocess.run(
@@ -881,7 +907,7 @@ def test_worktree_run_commits_on_a_new_branch_with_the_named_co_author(
     certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv)
     assert "--drop-regional-release" in certify_data
     assert not any(argv[:2] == ["git", "push"] for argv in FakeShell.runs)
-    assert sum("check-compatibility" in argv for argv in FakeShell.runs) == 1
+    assert sum("check-compatibility" in argv for argv in FakeShell.runs) == 0
 
 
 def test_keep_regional_release_reads_the_bundles_local_area_build_at_its_commit(
@@ -903,7 +929,7 @@ def test_keep_regional_release_reads_the_bundles_local_area_build_at_its_commit(
          "--in-place", "--output-dir", str(tmp_path / "out")]
     )  # fmt: skip
 
-    certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+    assert certify_outcome(certify_build, args, hub, checkout) == 0
 
     certify_data = next(argv for argv in FakeShell.runs if "certify-data" in argv)
     assert (
@@ -1179,7 +1205,7 @@ def test_pull_request_opens_against_the_named_base(
         args = None
     assert args is not None, "certify-build has no --pr-base"
 
-    certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+    assert certify_outcome(certify_build, args, hub, checkout) == 0
 
     opened = next(argv for argv in FakeShell.runs if argv[:3] == ["gh", "pr", "create"])
     assert opened[opened.index("--base") + 1] == "claude/earlier-change"
@@ -1211,3 +1237,22 @@ def test_importing_the_script_skips_the_country_models_only_while_importing():
     ).stdout.split()
 
     assert answer == ["True", "False"]
+
+
+def test_disk_check_counts_only_the_builds_the_check_downloads(
+    certify_build, monkeypatch, tmp_path, capsys
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, session = hub_for(certify_build, "us")
+    session.add_build(RELEASES["us"][0], "nat-b1", COMMIT_A, size=5000)
+    session.add_build(RELEASES["us"][1], "loc-b1", COMMIT_B, model="2.199.0", size=3000)
+    args = certify_build.parse(
+        ["--country", "us", "--national-build", "nat-b1", "--local-area-build",
+         "loc-b1", "--in-place", "--dry-run", "--output-dir", str(tmp_path / "out")]
+    )  # fmt: skip
+
+    certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
+
+    plan = json.loads(capsys.readouterr().out)
+    assert plan["needed_bytes"] == 3000

From 60f62c02dcee3147f8df9e29d400e5c0ea4a96b3 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:07:54 +0400
Subject: [PATCH 15/25] Check only the builds made with another model version

The compatibility check refuses a build made with the model version it
is asked about, so a default run (the national build's own model) always
failed at its first check. Each build made with another model version is
checked and certified on its record; a build made with the target model
is certified on that basis, and the pull request body says it needed no
check. The free-disk check counts only the builds the check downloads.

Co-Authored-By: Claude Opus 5.5 
---
 scripts/certify_build.py | 34 ++++++++++++++++++++--------------
 1 file changed, 20 insertions(+), 14 deletions(-)

diff --git a/scripts/certify_build.py b/scripts/certify_build.py
index 8fc0cf6d..d6243ca3 100644
--- a/scripts/certify_build.py
+++ b/scripts/certify_build.py
@@ -9,10 +9,11 @@
 2. read each build from its own folder, ``releases///``, at
    the commit that published it, after checking that ``releases.json`` at
    ``main`` lists the build and has not withdrawn it, and check that the disk
-   has room for the builds' files;
-3. ``scripts/bundle.py check-compatibility`` for each build and the model
-   version; certification takes a build's record as its compatibility basis
-   when the build was made with another model version;
+   has room for the files the compatibility check downloads;
+3. ``scripts/bundle.py check-compatibility`` for each build made with another
+   model version, whose record certification then takes as its compatibility
+   basis; a build made with the model version is certified on that basis,
+   with no check;
 4. ``scripts/bundle.py certify-data`` with the national build and the chosen
    regional route;
 5. ``uv lock`` and ``scripts/release_lock.py``;
@@ -1385,11 +1386,8 @@ def _certify(
                 + ". Work on that pull request instead of opening a second one."
             )
 
-    needed = (
-        national.folder_bytes
-        + (local_area.folder_bytes if local_area else 0)
-        + DISK_MARGIN_BYTES
-    )
+    # Only the builds the compatibility check runs on are downloaded.
+    needed = sum(build.folder_bytes for build in recorded) + DISK_MARGIN_BYTES
     free = check_free_disk(work_dir, needed)
 
     plan = {
@@ -1427,9 +1425,9 @@ def _certify(
             "--python", PEPY_PYTHON]  # fmt: skip
     run(sync, step="sync", credentials=False)
 
-    # The check runs for every build. A build made with another model version
-    # is certified on its record; certify-data refuses a record for a build
-    # made with this one.
+    # The check runs on each build made with another model version, which is
+    # certified on its record. The check refuses a build made with this one,
+    # and certify-data refuses a record for it: it is certified on that basis.
     checks = []
     record_flags: list[str] = []
     for build, flag in (
@@ -1438,6 +1436,15 @@ def _certify(
     ):
         if build is None:
             continue
+        if build not in recorded:
+            checks.append(
+                {
+                    "build": build.build,
+                    "summary": f"made with {model_label}, so certified on that "
+                    "basis with no compatibility check.",
+                }
+            )
+            continue
         record_path = work_dir / f"{build.build}.record.json"
         # An earlier run's record must not stand in for this check.
         record_path.unlink(missing_ok=True)
@@ -1455,8 +1462,7 @@ def _certify(
                 f"record at {record_path}."
             ) from error
         checks.append({"build": build.build, "summary": check_summary(record_document)})
-        if build.model != model:
-            record_flags += [flag, str(record_path)]
+        record_flags += [flag, str(record_path)]
 
     certify_result = run(
         [

From 45a696261c4dfb32872c783d0236b19604ba00fc Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:21:29 +0400
Subject: [PATCH 16/25] Add failing tests for round 2 review findings

Tests for: the fake builds' core in the pinning test; the compatibility
basis assertion in the test that pins the country's certificate; an old
value that stands for two new ones (the UK's model and built-with
version); keeping a committed certification when the push or the pull
request fails; and the order of the cleanup commands for a leftover
branch. The fake certify-data now records the basis it would.

Co-Authored-By: Claude Opus 5.5 
---
 tests/test_certify_build.py | 106 +++++++++++++++++++++++++++++++++++-
 1 file changed, 104 insertions(+), 2 deletions(-)

diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py
index 0553ea33..6dedd053 100644
--- a/tests/test_certify_build.py
+++ b/tests/test_certify_build.py
@@ -263,7 +263,7 @@ def test_build_is_pinned_at_the_commit_that_published_its_folder(certify_build):
     )
 
     assert build.commit == COMMIT_A
-    assert (build.model, build.core) == ("2.200.0", "3.36.1")
+    assert (build.model, build.core) == ("2.200.0", BUNDLE_CORE)
     assert build.folder_bytes == 1000
     assert build.manifest_uri == (
         f"hf://dataset/policyengine/populace-uk-private@{COMMIT_A}"
@@ -648,8 +648,14 @@ def __call__(self, argv, *, step, env=None, check=True, credentials=True):
             country = argv[argv.index("--country") + 1]
             record = bundle["data_releases"][country]
             record["certification"]["data_build_id"] = "nat-b1"
+            on_record = bool(
+                {"--compatibility-record", "--regional-compatibility-record"}
+                & set(argv)
+            )
             record["certification"]["compatibility_basis"] = (
                 "compatibility_checked_exact_pair"
+                if on_record
+                else "built_with_model_package"
             )
             # Like certify-data: a named core, or a record's, binds the
             # certificate to that core.
@@ -1079,7 +1085,10 @@ def test_existing_local_branch_is_refused_before_the_worktree(
         certify_build.certify(args, hub=hub, shell_factory=FakeShell, repo=checkout)
 
     assert raised.type is certify_build.CertifyError
-    assert f"git branch -D {branch}" in str(raised.value)
+    message = str(raised.value)
+    assert f"git branch -D {branch}" in message
+    # A branch checked out in a worktree cannot be deleted, so that goes first.
+    assert message.index("git worktree remove") < message.index("git branch -D")
     assert not worktree.exists()
 
 
@@ -1256,3 +1265,96 @@ def test_disk_check_counts_only_the_builds_the_check_downloads(
 
     plan = json.loads(capsys.readouterr().out)
     assert plan["needed_bytes"] == 3000
+
+
+def test_old_value_that_stands_for_two_new_values_is_left_to_a_person(certify_build):
+    # The UK today: built with and certified for 2.179.2; now certified for
+    # 2.180.0 on the same build.
+    old = record_for("nat-b1", COMMIT_A, "2.179.2", "2.179.2")
+    new = record_for("nat-b1", COMMIT_A, "2.180.0", "2.179.2")
+
+    replacements = certify_build.constant_replacements(old, new, None, None)
+
+    assert ("2.179.2", "2.180.0") not in replacements
+    ambiguous = getattr(certify_build, "ambiguous_constants", None)
+    assert ambiguous is not None, "no way to find values a rewrite cannot place"
+    assert ambiguous(old, new) == {"2.179.2": ["2.179.2", "2.180.0"]}
+    body = certify_build.pr_body(
+        body_context("uk", ambiguous_constants=ambiguous(old, new))
+    )
+    assert "- [ ] **Constants that hold more than one certified value.**" in body
+    assert "`2.179.2` (now `2.179.2` and `2.180.0`)" in body
+
+
+BASIS_TESTS = """class TestBundle:
+    def test__given_us_manifest__then_has_pinned_model_and_data_packages(self):
+        fixture = {"built_with_model_package": {"version": "2.2.1"}}
+        assert manifest.certification.compatibility_basis == (
+            "legacy_compatible_model_package"
+        )
+
+    @pytest.mark.slow
+    def test__given_legacy_manifest__then_keeps_its_basis(self):
+        assert basis == "legacy_compatible_model_package"
+"""
+
+
+def test_basis_moves_only_in_the_test_that_pins_the_countrys_certificate(
+    certify_build, tmp_path
+):
+    rewrite = getattr(certify_build, "rewrite_basis_constant", None)
+    assert rewrite is not None, "the basis constant is never rewritten"
+    (tmp_path / "tests").mkdir()
+    tests = tmp_path / "tests/test_release_manifests.py"
+    tests.write_text(BASIS_TESTS)
+
+    moved = rewrite(
+        tmp_path, "us", "legacy_compatible_model_package", "built_with_model_package"
+    )
+
+    assert moved is True
+    assert tests.read_text() == BASIS_TESTS.replace(
+        '            "legacy_compatible_model_package"\n',
+        '            "built_with_model_package"\n',
+    )
+    assert rewrite(tmp_path, "uk", "built_with_model_package", "x") is False
+    assert rewrite(tmp_path, "us", "same", "same") is None
+    body = certify_build.pr_body(
+        body_context("uk", basis_left=("built_with_model_package", "x"))
+    )
+    assert "- [ ] **Compatibility basis constant.**" in body
+
+
+@pytest.mark.parametrize(
+    ("failing_step", "expected", "advice"),
+    [
+        (["git", "push"], "is committed on branch", "push -u origin"),
+        (["gh", "pr"], "is pushed", "gh pr create --draft"),
+    ],
+    ids=["push", "pull-request"],
+)
+def test_failure_after_the_commit_keeps_the_certification(
+    certify_build, monkeypatch, tmp_path, failing_step, expected, advice
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, _ = hub_for(certify_build, "uk")
+    args = certify_build.parse(
+        ["--country", "uk", "--national-build", "nat-b1", "--drop-regional-release",
+         "--base-ref", "HEAD", "--worktree", str(tmp_path / "certify-worktree"),
+         "--skip-writer-check", "testing", "--push", "--open-pr"]
+    )  # fmt: skip
+
+    class StepFails(FakeShell):
+        def __call__(self, argv, **kwargs):
+            if list(argv[:2]) == failing_step:
+                raise certify_build.CertifyError(f"{' '.join(failing_step)} failed")
+            return super().__call__(argv, **kwargs)
+
+    refusal = certify_outcome(certify_build, args, hub, checkout, StepFails)
+
+    message = str(refusal)
+    assert expected in message
+    assert advice in message
+    assert "git branch -D" not in message
+    assert "git worktree remove" not in message

From 42b014959c38e0767e2cf69e3ab6a7ee6a17e847 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:23:16 +0400
Subject: [PATCH 17/25] Fix round 2 review findings in the certification
 command

- The compatibility basis assertion moves with the certificate, in the
  one test that pins the country's certificate only, since the same
  literals name other bases and fixture keys elsewhere in that file; a
  missing test or literal is left to a person in the body.
- An old value that now stands for two new values (the UK's model and
  built-with version, certified for a new model on the same build) is
  left to a person instead of being rewritten to one of them.
- A failure after the commit keeps the certification: the refusal says
  how to push it and open the pull request, not to remove it.
- A leftover branch's cleanup removes its worktree first; other errors
  after the worktree exists print what the run left.

Co-Authored-By: Claude Opus 5.5 
---
 scripts/certify_build.py | 158 +++++++++++++++++++++++++++++++++------
 1 file changed, 134 insertions(+), 24 deletions(-)

diff --git a/scripts/certify_build.py b/scripts/certify_build.py
index d6243ca3..c43c042c 100644
--- a/scripts/certify_build.py
+++ b/scripts/certify_build.py
@@ -648,6 +648,28 @@ def certified_values(record: Mapping[str, Any]) -> dict[str, Optional[str]]:
     }
 
 
+#: The certified values whose quoted literals the tests pin, national first.
+CERTIFIED_KEYS = ("build_id", "revision", "model", "built_with", "data")
+
+
+def ambiguous_constants(
+    old_record: Mapping[str, Any], new_record: Mapping[str, Any]
+) -> dict[str, list[str]]:
+    """Old certified values that now stand for more than one value, such as a
+    model version the build was also made with, certified for a new model on
+    the same build. A literal rewrite cannot tell their constants apart."""
+
+    old, new = certified_values(old_record), certified_values(new_record)
+    targets: dict[str, set[str]] = {}
+    for key in CERTIFIED_KEYS:
+        before, after = old[key], new[key]
+        if before and after:
+            targets.setdefault(before, set()).add(after)
+    return {
+        before: sorted(afters) for before, afters in targets.items() if len(afters) > 1
+    }
+
+
 def constant_replacements(
     old_record: Mapping[str, Any],
     new_record: Mapping[str, Any],
@@ -663,10 +685,11 @@ def constant_replacements(
     """
 
     old, new = certified_values(old_record), certified_values(new_record)
+    ambiguous = ambiguous_constants(old_record, new_record)
     pairs: list[tuple[str, str]] = []
-    for key in ("build_id", "revision", "model", "built_with", "data"):
+    for key in CERTIFIED_KEYS:
         before, after = old[key], new[key]
-        if before and after and before != after:
+        if before and after and before != after and before not in ambiguous:
             pairs.append((before, after))
     if old_local_area is not None and new_local_area is not None:
         national_commits = {
@@ -688,6 +711,54 @@ def constant_replacements(
     return unique
 
 
+#: The test that pins each country's certificate, basis included.
+BASIS_TEST_FILE = "tests/test_release_manifests.py"
+BASIS_TEST = "test__given_{country}_manifest__then_has_pinned_model_and_data_packages"
+
+
+def rewrite_basis_constant(
+    checkout: Path, country: str, old_basis: Optional[str], new_basis: Optional[str]
+) -> Optional[bool]:
+    """Move the basis literal in the test that pins ``country``'s certificate.
+
+    The same literals name other bases, and fixture keys, elsewhere in the
+    file, so only that test changes. Returns ``None`` when the basis does not
+    move or the file is absent, ``True`` once rewritten, and ``False`` when
+    the test or its literal is not there, which is left to a person.
+    """
+
+    if not old_basis or not new_basis or old_basis == new_basis:
+        return None
+    path = checkout / BASIS_TEST_FILE
+    if not path.exists():
+        return None
+    lines = path.read_text().splitlines(keepends=True)
+    definition = f"def {BASIS_TEST.format(country=country)}("
+    start = next(
+        (
+            index
+            for index, line in enumerate(lines)
+            if line.lstrip().startswith(definition)
+        ),
+        None,
+    )
+    if start is None:
+        return False
+    indent = len(lines[start]) - len(lines[start].lstrip())
+    end = start + 1
+    while end < len(lines) and (
+        not lines[end].strip() or len(lines[end]) - len(lines[end].lstrip()) > indent
+    ):
+        end += 1
+    test = "".join(lines[start:end])
+    literal = f'"{old_basis}"'
+    if literal not in test:
+        return False
+    lines[start:end] = [test.replace(literal, f'"{new_basis}"')]
+    path.write_text("".join(lines))
+    return True
+
+
 def other_country_values(bundle: Mapping[str, Any], country: str) -> set[str]:
     """Every value the bundle certifies for the other countries: their
     builds, commits, model and data versions and local-area builds."""
@@ -899,6 +970,24 @@ def pr_body(context: Mapping[str, Any]) -> str:
             f"`{context['national_commit']}` and each local-area one names "
             + (f"`{regional}`." if regional else "the local-area build's commit.")
         )
+    if context.get("ambiguous_constants"):
+        needs.append(
+            "- [ ] **Constants that hold more than one certified value.** Each of "
+            "these old values now stands for more than one value, so this command "
+            "left constants holding it unchanged; set each to its own value: "
+            + ", ".join(
+                f"`{before}` (now {' and '.join(f'`{after}`' for after in afters)})"
+                for before, afters in context["ambiguous_constants"].items()
+            )
+        )
+    if context.get("basis_left"):
+        old_basis, new_basis = context["basis_left"]
+        needs.append(
+            "- [ ] **Compatibility basis constant.** The certificate's basis moved "
+            f"from `{old_basis}` to `{new_basis}`, but `{BASIS_TEST_FILE}` has no "
+            f'`"{old_basis}"` in `{BASIS_TEST.format(country=context["country"])}`; '
+            "set the basis that test expects by hand."
+        )
     if context.get("held_constants"):
         needs.append(
             "- [ ] **Constants another country shares.** The test constants "
@@ -1192,7 +1281,7 @@ def describe_failure(error: BaseException) -> str:
         return f"`{shown}` exited {error.returncode}."
     if isinstance(error, CertifyError):
         return str(error)
-    return f"could not run a program: {error}."
+    return f"a program or file could not be used: {error}."
 
 
 def local_branch_exists(repo: Path, branch: str) -> bool:
@@ -1219,23 +1308,24 @@ def certify(
     them, since a second run needs neither to exist.
     """
 
-    left_behind: list[str] = []
+    # What a failure from here on leaves, and what to do about it.
+    after_failure: list[str] = []
     try:
         return _certify(
             args,
             hub=hub,
             shell_factory=shell_factory,
             repo=repo,
-            left_behind=left_behind,
+            after_failure=after_failure,
         )
     except (CertifyError, *COMMAND_FAILURES) as error:
-        if not left_behind:
+        if not after_failure:
             raise
-        raise CertifyError(
-            f"{describe_failure(error)} This run left a worktree and a branch; "
-            f"remove them with {' and '.join(f'`{command}`' for command in left_behind)} "
-            "before running again."
-        ) from error
+        raise CertifyError(f"{describe_failure(error)} {after_failure[-1]}") from error
+    except Exception:
+        if after_failure:
+            print(after_failure[-1], file=sys.stderr)
+        raise
 
 
 def _certify(
@@ -1244,7 +1334,7 @@ def _certify(
     hub: Optional[Hub],
     shell_factory: Any,
     repo: Path,
-    left_behind: list[str],
+    after_failure: list[str],
 ) -> int:
     hub = Hub(hub_token()) if hub is None else hub
     country = args.country
@@ -1366,9 +1456,9 @@ def _certify(
         if local_branch_exists(repo, branch):
             raise CertifyError(
                 f"branch {branch} exists in this clone, left by an earlier run; "
-                f"remove it with `git branch -D {branch}`, and its worktree with "
-                "`git worktree remove --force ` if one remains, before "
-                "running again."
+                "remove its worktree, if one remains, with `git worktree remove "
+                f"--force `, then the branch with `git branch -D {branch}`, "
+                "before running again."
             )
     output_dir = args.output_dir or checkout.parent
     log = output_dir / f"{checkout.name}.certify.log"
@@ -1415,10 +1505,11 @@ def _certify(
             cwd=repo,
             check=True,
         )  # fmt: skip
-        left_behind += [
-            f"git worktree remove --force {shlex.quote(str(checkout))}",
-            f"git branch -D {shlex.quote(branch)}",
-        ]
+        after_failure.append(
+            "This run left a worktree and a branch; remove them with "
+            f"`git worktree remove --force {shlex.quote(str(checkout))}` and "
+            f"`git branch -D {shlex.quote(branch)}` before running again."
+        )
     run = shell_factory(checkout, log)
     python = str(checkout / ".venv/bin/python")
     sync = ["uv", "sync", "--frozen", "--extra", country, "--extra", "dev",
@@ -1506,6 +1597,11 @@ def _certify(
         other_country_values(old_bundle, country),
     )
     constants = rewrite_constants(checkout, replacements)
+    old_basis = (record.get("certification") or {}).get("compatibility_basis")
+    new_basis = new_certification.get("compatibility_basis")
+    basis_moved = rewrite_basis_constant(checkout, country, old_basis, new_basis)
+    if basis_moved and BASIS_TEST_FILE not in constants:
+        constants = sorted([*constants, BASIS_TEST_FILE])
     run(
         [python, "-m", "pytest", "tests/test_household_calculator_snapshot.py", "-q"],
         env={"PE_UPDATE_SNAPSHOTS": "1"},
@@ -1566,6 +1662,8 @@ def _certify(
         "constants": ", ".join(constants),
         "shared_old_commit": shared_old_commit,
         "held_constants": held_constants,
+        "ambiguous_constants": ambiguous_constants(record, new_record),
+        "basis_left": (old_basis, new_basis) if basis_moved is False else None,
         "dropped_overlays": dropped_overlays(country, old_bundle, new_bundle),
         "warnings": warnings,
         "footer": args.pr_body_footer,
@@ -1589,14 +1687,26 @@ def _certify(
         step="commit",
     )
     print(f"\ncommitted on {branch} in {checkout}; pull request body: {body}")
+    open_pr = ["gh", "pr", "create", "--draft", "--repo", PEPY_REPO, "--base",
+               args.pr_base, "--head", branch, "--title", title, "--body-file",
+               str(body)]  # fmt: skip
+    open_instruction = f"open the pull request with `{shlex.join(open_pr)}`"
+    after_failure.append(
+        f"The certification is committed on branch {branch} in {checkout}; push "
+        f"it with `git -C {shlex.quote(str(checkout))} push -u origin "
+        f"{shlex.quote(branch)}`"
+        + (f" and {open_instruction}" if args.open_pr else "")
+        + ". Running this command again is refused once the branch is on origin."
+    )
     if args.push:
         run(["git", "push", "-u", "origin", branch], step="push")
+        after_failure.append(
+            f"Branch {branch} is pushed"
+            + (f"; {open_instruction}" if args.open_pr else "")
+            + "."
+        )
     if args.open_pr:
-        run(
-            ["gh", "pr", "create", "--draft", "--repo", PEPY_REPO, "--base", args.pr_base,
-             "--head", branch, "--title", title, "--body-file", str(body)],
-            step="pull request",
-        )  # fmt: skip
+        run(open_pr, step="pull request")
     return 0
 
 

From db30f3c5edb54cd1ec9acf47e4cfe1d6ffabdbf1 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:23:26 +0400
Subject: [PATCH 18/25] Add a failing test for formatting rewritten constant
 files

Co-Authored-By: Claude Opus 5.5 
---
 tests/test_certify_build.py | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py
index 6dedd053..b569491f 100644
--- a/tests/test_certify_build.py
+++ b/tests/test_certify_build.py
@@ -1358,3 +1358,33 @@ def __call__(self, argv, **kwargs):
     assert advice in message
     assert "git branch -D" not in message
     assert "git worktree remove" not in message
+
+
+def test_rewritten_constant_files_are_formatted(certify_build, monkeypatch, tmp_path):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    (checkout / "tests").mkdir()
+    (checkout / "tests/test_release_manifests.py").write_text(BASIS_TESTS)
+    commit_all(checkout)
+    hub, _ = hub_for(certify_build, "us")
+    args = certify_build.parse(
+        ["--country", "us", "--national-build", "nat-b1", "--drop-regional-release",
+         "--in-place", "--output-dir", str(tmp_path / "out")]
+    )  # fmt: skip
+
+    assert certify_outcome(certify_build, args, hub, checkout) == 0
+
+    # The US basis moved, and a longer literal can outgrow the line length.
+    assert (checkout / "tests/test_release_manifests.py").read_text() == (
+        BASIS_TESTS.replace(
+            '            "legacy_compatible_model_package"\n',
+            '            "built_with_model_package"\n',
+        )
+    )
+    formats = [argv for argv in FakeShell.runs if argv[1:4] == ["-m", "ruff", "format"]]
+    assert formats == [
+        [str(checkout / ".venv/bin/python"), "-m", "ruff", "format",
+         "tests/test_release_manifests.py"]
+    ]  # fmt: skip
+    steps = step_names(FakeShell.runs)
+    assert steps.index("ruff") < steps.index("snapshots")

From f3173371e0badb81a89aa02fdbd870a2e03303ab Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:23:41 +0400
Subject: [PATCH 19/25] Format the constant files the certification rewrites

A rewritten literal can change a line's length, and the pull request's
CI checks the format, so the command runs ruff format on the files it
rewrote before regenerating the household snapshots.

Co-Authored-By: Claude Opus 5.5 
---
 scripts/certify_build.py | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/scripts/certify_build.py b/scripts/certify_build.py
index c43c042c..216e7102 100644
--- a/scripts/certify_build.py
+++ b/scripts/certify_build.py
@@ -18,7 +18,8 @@
    regional route;
 5. ``uv lock`` and ``scripts/release_lock.py``;
 6. ``scripts/bundle.py generate --include-tros``, the rewrite of the
-   certified constants the tests pin, the household snapshots, then
+   certified constants the tests pin (then ``ruff format`` on those files),
+   the household snapshots, then
    ``scripts/bundle.py check --published-spm --include-tros --strict-tros``;
 7. for the UK, the Universal Credit floor (weighted national totals);
 8. a commit on a new branch in a new worktree, and a pull request body that
@@ -1602,6 +1603,9 @@ def _certify(
     basis_moved = rewrite_basis_constant(checkout, country, old_basis, new_basis)
     if basis_moved and BASIS_TEST_FILE not in constants:
         constants = sorted([*constants, BASIS_TEST_FILE])
+    if constants:
+        # A rewritten literal can change a line's length, and CI checks format.
+        run([python, "-m", "ruff", "format", *constants], step="format constants")
     run(
         [python, "-m", "pytest", "tests/test_household_calculator_snapshot.py", "-q"],
         env={"PE_UPDATE_SNAPSHOTS": "1"},

From d4bf6fbdd4870d6178330fb75e2bcc8342dd9afe Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:25:19 +0400
Subject: [PATCH 20/25] Add failing tests for naming the local-area build in
 the branch

The scheduled workflow names both builds in its branches; a hand-run
certification must use the same name, and another local-area build
must not count as the same certification.

Co-Authored-By: Claude Opus 5.5 
---
 tests/test_certify_build.py | 63 +++++++++++++++++++++++++++++++++++++
 1 file changed, 63 insertions(+)

diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py
index b569491f..8753539c 100644
--- a/tests/test_certify_build.py
+++ b/tests/test_certify_build.py
@@ -1388,3 +1388,66 @@ def test_rewritten_constant_files_are_formatted(certify_build, monkeypatch, tmp_
     ]  # fmt: skip
     steps = step_names(FakeShell.runs)
     assert steps.index("ruff") < steps.index("snapshots")
+
+
+def test_branch_names_both_builds_like_the_scheduled_workflow(
+    certify_build, monkeypatch, tmp_path
+):
+    # The scheduled workflow (scripts/compatibility_workflow.py) names its
+    # branches certify////-,
+    # and skips a model version once a pull request from that branch exists.
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, _ = hub_for(certify_build, "uk")
+    worktree = tmp_path / "certify-worktree"
+    args = certify_build.parse(
+        ["--country", "uk", "--national-build", "nat-b1", "--local-area-build",
+         "loc-b1", "--base-ref", "HEAD", "--worktree", str(worktree),
+         "--skip-writer-check", "testing"]
+    )  # fmt: skip
+
+    assert certify_outcome(certify_build, args, hub, checkout) == 0
+
+    branch = subprocess.run(
+        ["git", "branch", "--show-current"],
+        cwd=worktree,
+        capture_output=True,
+        text=True,
+        check=True,
+    ).stdout.strip()
+    assert branch == "certify/uk/nat-b1/loc-b1/policyengine-uk-2.200.0"
+
+
+def test_writer_check_lets_another_local_area_build_be_certified(
+    certify_build, monkeypatch, tmp_path
+):
+    fake_listing(
+        monkeypatch,
+        certify_build,
+        [
+            {
+                "number": 1,
+                "title": "Certify Microcosm UK build nat-b1 for policyengine-uk 2.200.0",
+                "body": "local-area build `loc-b1`",
+                "headRefName": "certify/uk/nat-b1/loc-b1/policyengine-uk-2.200.0",
+            }
+        ],
+    )
+    branch = "certify/uk/nat-b1/loc-b2/policyengine-uk-2.200.0"
+
+    try:
+        found = certify_build.writer_check(
+            tmp_path, branch, "nat-b1", "policyengine-uk 2.200.0", "loc-b2"
+        )
+    except TypeError:
+        found = None
+    same = certify_build.writer_check(
+        tmp_path,
+        "certify/uk/nat-b1/loc-b1/policyengine-uk-2.200.0",
+        "nat-b1",
+        "policyengine-uk 2.200.0",
+        *(["loc-b1"] if found is not None else []),
+    )
+
+    assert found == []
+    assert len(same) == 1 and same[0].startswith("#1 ")

From f6d1e3f87f6a3eef98c3503fd190d30de9b97aac Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:25:49 +0400
Subject: [PATCH 21/25] Name the local-area build in the certification branch

Branches are now certify////-,
the name the scheduled workflow gives its own, so a hand-run
certification and the workflow find each other's pull requests, and a
model version is certified again once a new local-area build is pinned.
The open-pull-request check also matches on the local-area build.

Co-Authored-By: Claude Opus 5.5 
---
 scripts/certify_build.py | 62 +++++++++++++++++++++++++++++-----------
 1 file changed, 46 insertions(+), 16 deletions(-)

diff --git a/scripts/certify_build.py b/scripts/certify_build.py
index 216e7102..cdb0bafc 100644
--- a/scripts/certify_build.py
+++ b/scripts/certify_build.py
@@ -4,8 +4,10 @@
 request for one country's Microcosm national build, and the local-area build
 its regions use, named by release and build:
 
-1. refuse if an open pull request or a branch already certifies this national
-   build for this model version (``--skip-writer-check WHY`` skips this);
+1. refuse if an open pull request or a branch already certifies these builds
+   for this model version (``--skip-writer-check WHY`` skips this); the
+   branch is ``certify////-``,
+   as the scheduled workflow names its branches;
 2. read each build from its own folder, ``releases///``, at
    the commit that published it, after checking that ``releases.json`` at
    ``main`` lists the build and has not withdrawn it, and check that the disk
@@ -504,15 +506,20 @@ def git(checkout: Path, *arguments: str) -> str:
 
 
 def writer_check(
-    checkout: Path, branch: str, national_build: str, model_label: str
+    checkout: Path,
+    branch: str,
+    national_build: str,
+    model_label: str,
+    local_area_build: Optional[str] = None,
 ) -> list[str]:
-    """Open pull requests or branches already certifying this national build
-    for this model version.
-
-    A writer is an open pull request whose title or body names both the build
-    and ``model_label`` (``" "``), an open pull
-    request from ``branch``, or ``branch`` on ``origin``. A listing that
-    cannot be read refuses rather than passing.
+    """Open pull requests or branches already certifying these builds for this
+    model version.
+
+    A writer is an open pull request whose title or body names the national
+    build, the local-area build (when there is one) and ``model_label``
+    (``" "``), an open pull request from ``branch``,
+    or ``branch`` on ``origin``. A listing that cannot be read refuses rather
+    than passing.
     """
 
     found = []
@@ -534,8 +541,12 @@ def writer_check(
         )
     for pull_request in json.loads(listing.stdout or "[]"):
         text = f"{pull_request.get('title') or ''}\n{pull_request.get('body') or ''}"
-        names_pair = national_build in text and model_label in text
-        if names_pair or pull_request.get("headRefName") == branch:
+        names_same = (
+            national_build in text
+            and model_label in text
+            and (local_area_build is None or local_area_build in text)
+        )
+        if names_same or pull_request.get("headRefName") == branch:
             found.append(
                 f"#{pull_request['number']} {pull_request['title']} "
                 f"({pull_request['headRefName']})"
@@ -1193,8 +1204,19 @@ def parse(argv: Optional[Sequence[str]]) -> argparse.Namespace:
 # --- The certification -------------------------------------------------------
 
 
-def branch_name(country: str, national_build: str, model_label: str) -> str:
-    return f"certify/{country}/{national_build}/{model_label.replace(' ', '-')}"
+def branch_name(
+    country: str,
+    national_build: str,
+    local_area_build: Optional[str],
+    model_label: str,
+) -> str:
+    """``certify////-``, as
+    the scheduled workflow (``scripts/compatibility_workflow.py``) names its
+    branches, so either one finds the other's; without a local-area build,
+    that part is left out."""
+
+    builds = [national_build, *([local_area_build] if local_area_build else [])]
+    return "/".join(["certify", country, *builds, model_label.replace(" ", "-")])
 
 
 def compatibility_check_argv(
@@ -1447,7 +1469,9 @@ def _certify(
             f"local-area build `{local_area.build}` at commit `{local_area.commit}`"
         )
 
-    branch = branch_name(country, national.build, model_label)
+    branch = branch_name(
+        country, national.build, local_area.build if local_area else None, model_label
+    )
     if not args.in_place:
         checkout = args.worktree or (
             repo.parent / "_worktrees" / f"pepy-{branch.replace('/', '-')}"
@@ -1469,7 +1493,13 @@ def _certify(
     if args.skip_writer_check:
         print(f"writer check skipped: {args.skip_writer_check}")
     elif not args.in_place:
-        others = writer_check(repo, branch, national.build, model_label)
+        others = writer_check(
+            repo,
+            branch,
+            national.build,
+            model_label,
+            local_area.build if local_area else None,
+        )
         if others:
             raise CertifyError(
                 "this build is already being certified for this model version: "

From 8e9c1ee6e2ed4cf053a7758e9651c9146b34af31 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:41:33 +0400
Subject: [PATCH 22/25] Add failing tests for round 3 review findings

Tests for: the UK release-bundle test's basis assertion, which reads
the packaged bundle too; how to push a finished run made without
--push, and a leftover branch from such a run; and recovery commands
that name the clone with git -C. The fake certify-data now takes the
national basis from the national record alone.

Co-Authored-By: Claude Opus 5.5 
---
 tests/test_certify_build.py | 96 ++++++++++++++++++++++++++++++++-----
 1 file changed, 83 insertions(+), 13 deletions(-)

diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py
index 8753539c..813163c5 100644
--- a/tests/test_certify_build.py
+++ b/tests/test_certify_build.py
@@ -648,13 +648,10 @@ def __call__(self, argv, *, step, env=None, check=True, credentials=True):
             country = argv[argv.index("--country") + 1]
             record = bundle["data_releases"][country]
             record["certification"]["data_build_id"] = "nat-b1"
-            on_record = bool(
-                {"--compatibility-record", "--regional-compatibility-record"}
-                & set(argv)
-            )
+            # The national basis comes from the national build's record alone.
             record["certification"]["compatibility_basis"] = (
                 "compatibility_checked_exact_pair"
-                if on_record
+                if "--compatibility-record" in argv
                 else "built_with_model_package"
             )
             # Like certify-data: a named core, or a record's, binds the
@@ -1066,13 +1063,22 @@ def test_build_without_a_record_outside_the_bound_core_is_refused_first(
     assert FakeShell.runs == []
 
 
+@pytest.mark.parametrize("with_worktree", [False, True], ids=["branch", "worktree"])
 def test_existing_local_branch_is_refused_before_the_worktree(
-    certify_build, monkeypatch, tmp_path
+    certify_build, monkeypatch, tmp_path, with_worktree
 ):
     monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
     checkout = bundle_checkout(tmp_path)
     branch = "certify/uk/nat-b1/policyengine-uk-2.200.0"
-    subprocess.run(["git", "branch", branch], cwd=checkout, check=True)
+    earlier = tmp_path / "earlier-run"
+    if with_worktree:
+        subprocess.run(
+            ["git", "worktree", "add", "-q", "-b", branch, str(earlier)],
+            cwd=checkout,
+            check=True,
+        )
+    else:
+        subprocess.run(["git", "branch", branch], cwd=checkout, check=True)
     hub, _ = hub_for(certify_build, "uk")
     worktree = tmp_path / "second-try"
     args = certify_build.parse(
@@ -1086,9 +1092,15 @@ def test_existing_local_branch_is_refused_before_the_worktree(
 
     assert raised.type is certify_build.CertifyError
     message = str(raised.value)
-    assert f"git branch -D {branch}" in message
-    # A branch checked out in a worktree cannot be deleted, so that goes first.
-    assert message.index("git worktree remove") < message.index("git branch -D")
+    # A finished earlier run is pushed, not thrown away.
+    assert f"git -C {checkout} push -u origin {branch}" in message
+    assert f"git -C {checkout} branch -D {branch}" in message
+    if with_worktree:
+        # A branch checked out in a worktree cannot be deleted, so that goes first.
+        removal = f"git -C {checkout} worktree remove --force {earlier.resolve()}"
+        assert message.index(removal) < message.index("branch -D")
+    else:
+        assert "worktree remove" not in message
     assert not worktree.exists()
 
 
@@ -1118,8 +1130,12 @@ def __call__(self, argv, **kwargs):
 
     message = str(raised.value)
     assert message.startswith("certify-data exited 1")
-    assert f"git worktree remove --force {worktree}" in message
-    assert "git branch -D certify/uk/nat-b1/policyengine-uk-2.200.0" in message
+    # The commands work from any folder.
+    assert f"git -C {checkout} worktree remove --force {worktree}" in message
+    assert (
+        f"git -C {checkout} branch -D certify/uk/nat-b1/policyengine-uk-2.200.0"
+        in message
+    )
 
 
 @pytest.mark.parametrize(
@@ -1374,7 +1390,7 @@ def test_rewritten_constant_files_are_formatted(certify_build, monkeypatch, tmp_
 
     assert certify_outcome(certify_build, args, hub, checkout) == 0
 
-    # The US basis moved, and a longer literal can outgrow the line length.
+    # The US basis moved, and a rewritten literal changes the line's length.
     assert (checkout / "tests/test_release_manifests.py").read_text() == (
         BASIS_TESTS.replace(
             '            "legacy_compatible_model_package"\n',
@@ -1451,3 +1467,57 @@ def test_writer_check_lets_another_local_area_build_be_certified(
 
     assert found == []
     assert len(same) == 1 and same[0].startswith("#1 ")
+
+
+UK_BASIS_TESTS = """class TestBundle:
+    def test__given_uk_manifest__then_has_pinned_model_and_data_packages(self):
+        assert manifest.certification.compatibility_basis == "built_with_model_package"
+
+    def test__given_fixture__then_keeps_its_basis(self):
+        fixture = {"built_with_model_package": {"version": "2.179.2"}}
+        assert basis == "built_with_model_package"
+
+    def test__given_manifest_certification__then_release_bundle_exposes_it(self):
+        manifest = get_release_manifest("uk")
+        assert bundle["compatibility_basis"] == "built_with_model_package"
+"""
+
+
+def test_basis_moves_in_every_test_that_reads_the_countrys_bundle(
+    certify_build, tmp_path
+):
+    (tmp_path / "tests").mkdir()
+    tests = tmp_path / "tests/test_release_manifests.py"
+    tests.write_text(UK_BASIS_TESTS)
+
+    moved = certify_build.rewrite_basis_constant(
+        tmp_path, "uk", "built_with_model_package", "compatibility_checked_exact_pair"
+    )
+
+    assert moved is True
+    lines = tests.read_text().splitlines()
+    assert lines[2].endswith('== "compatibility_checked_exact_pair"')
+    # The fixture's key and its own basis stay as they are.
+    assert lines[3:8] == UK_BASIS_TESTS.splitlines()[3:8]
+    assert lines[-1].endswith('== "compatibility_checked_exact_pair"')
+
+
+def test_finished_run_without_push_says_how_to_push_it(
+    certify_build, monkeypatch, tmp_path, capsys
+):
+    monkeypatch.setattr(certify_build, "DISK_MARGIN_BYTES", 0)
+    checkout = bundle_checkout(tmp_path)
+    hub, _ = hub_for(certify_build, "uk")
+    worktree = tmp_path / "certify-worktree"
+    args = certify_build.parse(
+        ["--country", "uk", "--national-build", "nat-b1", "--drop-regional-release",
+         "--base-ref", "HEAD", "--worktree", str(worktree), "--skip-writer-check",
+         "testing"]
+    )  # fmt: skip
+
+    assert certify_outcome(certify_build, args, hub, checkout) == 0
+
+    printed = capsys.readouterr().out
+    branch = "certify/uk/nat-b1/policyengine-uk-2.200.0"
+    assert f"git -C {worktree} push -u origin {branch}" in printed
+    assert "gh pr create --draft" in printed

From d4d36f5c6010ef970d9631f3b4ceb8dd799be6df Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:45:05 +0400
Subject: [PATCH 23/25] Fix round 3 review findings in the certification
 command

- Rewrite the basis literal in every test that asserts a country's
  packaged basis, which for the UK includes the release-bundle test.
- Name the clone with `git -C` in every recovery command, and give the
  real path of a leftover branch's worktree.
- When an earlier run's branch exists, say how to push it if that run
  finished, before saying how to remove it.
- After a run without --push, or with --push but without --open-pr,
  print the commands that push the branch and open the pull request.
- Describe the shared local-area commit box and the certify() docstring
  as the code behaves.

Co-Authored-By: Claude Opus 5.5 
---
 scripts/certify_build.py | 157 ++++++++++++++++++++++++++-------------
 1 file changed, 106 insertions(+), 51 deletions(-)

diff --git a/scripts/certify_build.py b/scripts/certify_build.py
index cdb0bafc..4808f19e 100644
--- a/scripts/certify_build.py
+++ b/scripts/certify_build.py
@@ -723,20 +723,29 @@ def constant_replacements(
     return unique
 
 
-#: The test that pins each country's certificate, basis included.
+#: The tests in ``BASIS_TEST_FILE`` that read a country's packaged
+#: certificate and assert its basis.
 BASIS_TEST_FILE = "tests/test_release_manifests.py"
-BASIS_TEST = "test__given_{country}_manifest__then_has_pinned_model_and_data_packages"
+BASIS_TESTS = {
+    "us": ("test__given_us_manifest__then_has_pinned_model_and_data_packages",),
+    "uk": (
+        "test__given_uk_manifest__then_has_pinned_model_and_data_packages",
+        "test__given_manifest_certification__then_release_bundle_exposes_it",
+    ),
+}
 
 
 def rewrite_basis_constant(
     checkout: Path, country: str, old_basis: Optional[str], new_basis: Optional[str]
 ) -> Optional[bool]:
-    """Move the basis literal in the test that pins ``country``'s certificate.
+    """Move the basis literal in each test that asserts ``country``'s
+    packaged basis (``BASIS_TESTS``).
 
     The same literals name other bases, and fixture keys, elsewhere in the
-    file, so only that test changes. Returns ``None`` when the basis does not
-    move or the file is absent, ``True`` once rewritten, and ``False`` when
-    the test or its literal is not there, which is left to a person.
+    file, so only those tests change. Returns ``None`` when the basis does
+    not move or the file is absent, ``True`` once every one is rewritten, and
+    ``False`` when a test or its literal is not there, which is left to a
+    person.
     """
 
     if not old_basis or not new_basis or old_basis == new_basis:
@@ -745,30 +754,36 @@ def rewrite_basis_constant(
     if not path.exists():
         return None
     lines = path.read_text().splitlines(keepends=True)
-    definition = f"def {BASIS_TEST.format(country=country)}("
-    start = next(
-        (
-            index
-            for index, line in enumerate(lines)
-            if line.lstrip().startswith(definition)
-        ),
-        None,
-    )
-    if start is None:
-        return False
-    indent = len(lines[start]) - len(lines[start].lstrip())
-    end = start + 1
-    while end < len(lines) and (
-        not lines[end].strip() or len(lines[end]) - len(lines[end].lstrip()) > indent
-    ):
-        end += 1
-    test = "".join(lines[start:end])
     literal = f'"{old_basis}"'
-    if literal not in test:
-        return False
-    lines[start:end] = [test.replace(literal, f'"{new_basis}"')]
+    every_one = True
+    for name in BASIS_TESTS.get(country, ()):
+        definition = f"def {name}("
+        start = next(
+            (
+                index
+                for index, line in enumerate(lines)
+                if line.lstrip().startswith(definition)
+            ),
+            None,
+        )
+        if start is None:
+            every_one = False
+            continue
+        indent = len(lines[start]) - len(lines[start].lstrip())
+        end = start + 1
+        while end < len(lines) and (
+            not lines[end].strip()
+            or len(lines[end]) - len(lines[end].lstrip()) > indent
+        ):
+            end += 1
+        test = "".join(lines[start:end])
+        if literal not in test:
+            every_one = False
+            continue
+        rewritten = test.replace(literal, f'"{new_basis}"').splitlines(keepends=True)
+        lines[start:end] = rewritten
     path.write_text("".join(lines))
-    return True
+    return every_one
 
 
 def other_country_values(bundle: Mapping[str, Any], country: str) -> set[str]:
@@ -977,8 +992,9 @@ def pr_body(context: Mapping[str, Any]) -> str:
             "- [ ] **Local-area commit constants.** The previous local-area build "
             f"shared commit `{context['shared_old_commit']}` with a national "
             "build, so rewriting quoted literals cannot tell the two builds' "
-            "constants apart, and this command left the local-area commit to a "
-            "person. Check that each national revision constant names "
+            "constants apart, and this command could not move the local-area "
+            "commit constants on their own. 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.")
         )
@@ -996,9 +1012,10 @@ def pr_body(context: Mapping[str, Any]) -> str:
         old_basis, new_basis = context["basis_left"]
         needs.append(
             "- [ ] **Compatibility basis constant.** The certificate's basis moved "
-            f"from `{old_basis}` to `{new_basis}`, but `{BASIS_TEST_FILE}` has no "
-            f'`"{old_basis}"` in `{BASIS_TEST.format(country=context["country"])}`; '
-            "set the basis that test expects by hand."
+            f"from `{old_basis}` to `{new_basis}`, but this command did not find "
+            f'`"{old_basis}"` in each of '
+            + ", ".join(f"`{name}`" for name in BASIS_TESTS.get(context["country"], ()))
+            + f" in `{BASIS_TEST_FILE}`; set the basis those tests expect by hand."
         )
     if context.get("held_constants"):
         needs.append(
@@ -1307,6 +1324,23 @@ def describe_failure(error: BaseException) -> str:
     return f"a program or file could not be used: {error}."
 
 
+def branch_worktree(repo: Path, branch: str) -> Optional[str]:
+    """The worktree ``branch`` is checked out in, if any."""
+
+    listing = subprocess.run(
+        ["git", "worktree", "list", "--porcelain"],
+        cwd=repo,
+        capture_output=True,
+        text=True,
+        check=False,
+    ).stdout
+    for block in listing.split("\n\n"):
+        fields = dict(line.split(" ", 1) for line in block.splitlines() if " " in line)
+        if fields.get("branch") == f"refs/heads/{branch}":
+            return fields.get("worktree")
+    return None
+
+
 def local_branch_exists(repo: Path, branch: str) -> bool:
     return (
         subprocess.run(
@@ -1327,8 +1361,10 @@ def certify(
 ) -> int:
     """Certify the named build; see the module docstring.
 
-    A run that fails after making its worktree and branch says how to remove
-    them, since a second run needs neither to exist.
+    A run that fails after making its worktree and branch, but before its
+    commit, says how to remove them, since a second run needs neither to
+    exist. Once the certification is committed, a failure, or a run without
+    ``--push``, says how to push it and open the pull request instead.
     """
 
     # What a failure from here on leaves, and what to do about it.
@@ -1479,11 +1515,22 @@ def _certify(
         if checkout.exists():
             raise CertifyError(f"{checkout} exists; choose another --worktree.")
         if local_branch_exists(repo, branch):
+            in_repo = f"git -C {shlex.quote(str(repo))}"
+            earlier = branch_worktree(repo, branch)
+            removal = (
+                f"its worktree with `{in_repo} worktree remove --force "
+                f"{shlex.quote(earlier)}`, then the branch with "
+                if earlier
+                else "the branch with "
+            )
             raise CertifyError(
-                f"branch {branch} exists in this clone, left by an earlier run; "
-                "remove its worktree, if one remains, with `git worktree remove "
-                f"--force `, then the branch with `git branch -D {branch}`, "
-                "before running again."
+                f"branch {branch} exists in this clone, left by an earlier run"
+                + (f" in {earlier}" if earlier else "")
+                + ". If that run finished, its certification is committed on it: "
+                f"push it with `{in_repo} push -u origin {shlex.quote(branch)}` and "
+                "open the pull request. Otherwise remove "
+                + removal
+                + f"`{in_repo} branch -D {shlex.quote(branch)}`, before running again."
             )
     output_dir = args.output_dir or checkout.parent
     log = output_dir / f"{checkout.name}.certify.log"
@@ -1536,10 +1583,11 @@ def _certify(
             cwd=repo,
             check=True,
         )  # fmt: skip
+        in_repo = f"git -C {shlex.quote(str(repo))}"
         after_failure.append(
             "This run left a worktree and a branch; remove them with "
-            f"`git worktree remove --force {shlex.quote(str(checkout))}` and "
-            f"`git branch -D {shlex.quote(branch)}` before running again."
+            f"`{in_repo} worktree remove --force {shlex.quote(str(checkout))}` and "
+            f"`{in_repo} branch -D {shlex.quote(branch)}` before running again."
         )
     run = shell_factory(checkout, log)
     python = str(checkout / ".venv/bin/python")
@@ -1725,22 +1773,29 @@ def _certify(
                args.pr_base, "--head", branch, "--title", title, "--body-file",
                str(body)]  # fmt: skip
     open_instruction = f"open the pull request with `{shlex.join(open_pr)}`"
-    after_failure.append(
-        f"The certification is committed on branch {branch} in {checkout}; push "
-        f"it with `git -C {shlex.quote(str(checkout))} push -u origin "
+    push_instruction = (
+        f"push it with `git -C {shlex.quote(str(checkout))} push -u origin "
         f"{shlex.quote(branch)}`"
+    )
+    after_failure.append(
+        f"The certification is committed on branch {branch} in {checkout}; "
+        + push_instruction
         + (f" and {open_instruction}" if args.open_pr else "")
         + ". Running this command again is refused once the branch is on origin."
     )
-    if args.push:
-        run(["git", "push", "-u", "origin", branch], step="push")
-        after_failure.append(
-            f"Branch {branch} is pushed"
-            + (f"; {open_instruction}" if args.open_pr else "")
-            + "."
-        )
+    if not args.push:
+        print(f"Next: {push_instruction} and {open_instruction}.")
+        return 0
+    run(["git", "push", "-u", "origin", branch], step="push")
+    after_failure.append(
+        f"Branch {branch} is pushed"
+        + (f"; {open_instruction}" if args.open_pr else "")
+        + "."
+    )
     if args.open_pr:
         run(open_pr, step="pull request")
+    else:
+        print(f"Next: {open_instruction}.")
     return 0
 
 

From 90525c638ed48957ed26b18ea8143af797168dbc Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:45:37 +0400
Subject: [PATCH 24/25] Describe what the test stand-in for the shell runs

Co-Authored-By: Claude Opus 5.5 
---
 tests/test_certify_build.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tests/test_certify_build.py b/tests/test_certify_build.py
index 813163c5..e11c0785 100644
--- a/tests/test_certify_build.py
+++ b/tests/test_certify_build.py
@@ -624,7 +624,7 @@ def test_commit_credits_only_the_named_co_authors(certify_build):
 
 
 class FakeShell:
-    """Records each command; runs git and gh for real, imitates the rest."""
+    """Records each command; runs git for real except `git push`, imitates the rest."""
 
     runs: list[list[str]] = []
 

From 648db8b1e9bc2a577c034599fd03349afcc85a82 Mon Sep 17 00:00:00 2001
From: Anthony Volk <14987227+anth-volk@users.noreply.github.com>
Date: Fri, 4 Dec 2026 01:46:08 +0400
Subject: [PATCH 25/25] Add a changelog entry for certify-build

Co-Authored-By: Claude Opus 5.5 
---
 changelog.d/793.added.md | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 changelog.d/793.added.md

diff --git a/changelog.d/793.added.md b/changelog.d/793.added.md
new file mode 100644
index 00000000..4fea830c
--- /dev/null
+++ b/changelog.d/793.added.md
@@ -0,0 +1 @@
+`python scripts/bundle.py certify-build --country uk|us --national-build  (--local-area-build  | --keep-regional-release | --drop-regional-release)` certifies a Microcosm build of either country by release and build name. It reads each build's folder at the Hugging Face commit that published it, runs `check-compatibility` on a build made with a model version other than the target and certifies the others on the version they were made with, then runs `certify-data`, regenerates the lock and provenance files, moves the test constants that name the certified build, and runs the strict bundle check (and, for the UK, the Universal Credit floor). It commits the result on `certify////-` in a new worktree, with a pull request body listing anything left to a person; `--push` and `--open-pr` publish it, and `--in-place` makes the same changes in the current checkout without committing.